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
|
lgpl-2.1
|
cc91dfeb7f6a2733842f7805bae8b5918b9d4571
| 0
|
CreativeMD/LittleTiles
|
package com.creativemd.littletiles.common.items;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.Nullable;
import org.lwjgl.util.Color;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.client.rendering.RenderCubeObject;
import com.creativemd.creativecore.client.rendering.model.CreativeBakedModel;
import com.creativemd.creativecore.client.rendering.model.ICreativeRendered;
import com.creativemd.creativecore.common.packet.PacketHandler;
import com.creativemd.creativecore.common.utils.ColorUtils;
import com.creativemd.creativecore.common.utils.Rotation;
import com.creativemd.creativecore.gui.container.SubContainer;
import com.creativemd.creativecore.gui.container.SubGui;
import com.creativemd.creativecore.gui.controls.gui.GuiAvatarLabel;
import com.creativemd.creativecore.gui.controls.gui.GuiColorPicker;
import com.creativemd.creativecore.gui.controls.gui.GuiSteppedSlider;
import com.creativemd.creativecore.gui.event.container.SlotChangeEvent;
import com.creativemd.creativecore.gui.event.gui.GuiControlChangedEvent;
import com.creativemd.creativecore.gui.event.gui.GuiControlClickEvent;
import com.creativemd.creativecore.gui.opener.GuiHandler;
import com.creativemd.creativecore.gui.opener.IGuiCreator;
import com.creativemd.littletiles.LittleTiles;
import com.creativemd.littletiles.common.action.LittleAction;
import com.creativemd.littletiles.common.action.block.LittleActionReplace;
import com.creativemd.littletiles.common.api.ILittleTile;
import com.creativemd.littletiles.common.blocks.BlockTile;
import com.creativemd.littletiles.common.container.SubContainerChisel;
import com.creativemd.littletiles.common.container.SubContainerGrabber;
import com.creativemd.littletiles.common.gui.SubGuiChisel;
import com.creativemd.littletiles.common.gui.SubGuiGrabber;
import com.creativemd.littletiles.common.items.ItemLittleGrabber.PlacePreviewMode;
import com.creativemd.littletiles.common.packet.LittleBlockPacket;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket;
import com.creativemd.littletiles.common.packet.LittleBlockPacket.BlockPacketAction;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket.VanillaBlockAction;
import com.creativemd.littletiles.common.structure.LittleStructure;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles;
import com.creativemd.littletiles.common.tiles.LittleTile;
import com.creativemd.littletiles.common.tiles.LittleTileBlock;
import com.creativemd.littletiles.common.tiles.LittleTileBlockColored;
import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview;
import com.creativemd.littletiles.common.tiles.vec.LittleTileBox;
import com.creativemd.littletiles.common.tiles.vec.LittleTileSize;
import com.creativemd.littletiles.common.tiles.vec.LittleTileVec;
import com.creativemd.littletiles.common.utils.geo.DragShape;
import com.creativemd.littletiles.common.utils.placing.PlacementHelper;
import com.n247s.api.eventapi.eventsystem.CustomEventSubscribe;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3i;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import scala.tools.nsc.doc.model.Def;
import scala.tools.nsc.transform.patmat.Solving.Solver.Lit;
public class ItemLittleGrabber extends Item implements ICreativeRendered, ILittleTile {
public ItemLittleGrabber()
{
setCreativeTab(LittleTiles.littleTab);
hasSubtypes = true;
setMaxStackSize(1);
}
@Override
public float getDestroySpeed(ItemStack stack, IBlockState state)
{
return 0F;
}
@Override
public boolean canDestroyBlockInCreative(World world, BlockPos pos, ItemStack stack, EntityPlayer player)
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(IBlockState state, TileEntity te, ItemStack stack) {
return getMode(stack).getRenderingCubes(stack);
}
@Override
@SideOnly(Side.CLIENT)
public void applyCustomOpenGLHackery(ItemStack stack, TransformType cameraTransformType)
{
Minecraft mc = Minecraft.getMinecraft();
GlStateManager.pushMatrix();
IBakedModel model = mc.getRenderItem().getItemModelMesher().getModelManager().getModel(new ModelResourceLocation(LittleTiles.modid + ":grabber_background", "inventory"));
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
mc.getRenderItem().renderItem(new ItemStack(Items.PAPER), model);
if(cameraTransformType == TransformType.GUI)
{
GlStateManager.scale(0.9, 0.9, 0.9);
GrabberMode mode = getMode(stack);
if(mode.renderBlockSeparately(stack))
{
LittleTilePreview preview = mode.getSeparateRenderingPreview(stack);
ItemStack blockStack = new ItemStack(preview.getPreviewBlock(), 1, preview.getPreviewBlockMeta());
model = mc.getRenderItem().getItemModelWithOverrides(blockStack, mc.world, mc.player); //getItemModelMesher().getItemModel(blockStack);
if(!(model instanceof CreativeBakedModel))
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
GlStateManager.disableDepth();
GlStateManager.pushMatrix();
GlStateManager.translate(-0.5F, -0.5F, -0.5F);
try {
if (model.isBuiltInRenderer())
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableRescaleNormal();
TileEntityItemStackRenderer.instance.renderByItem(blockStack);
}else{
Color color = preview.hasColor() ? ColorUtils.IntToRGBA(preview.getColor()) : ColorUtils.IntToRGBA(ColorUtils.WHITE);
color.setAlpha(255);
ReflectionHelper.findMethod(RenderItem.class, "renderModel", "func_191967_a", IBakedModel.class, int.class, ItemStack.class).invoke(mc.getRenderItem(), model, ColorUtils.RGBAToInt(color), blockStack);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
GlStateManager.popMatrix();
}
GlStateManager.enableDepth();
}
GlStateManager.popMatrix();
}
@Override
public boolean hasLittlePreview(ItemStack stack)
{
return true;
}
@Override
public List<LittleTilePreview> getLittlePreview(ItemStack stack)
{
return getMode(stack).getPreviews(stack);
}
@Override
public void saveLittlePreview(ItemStack stack, List<LittleTilePreview> previews)
{
getMode(stack).setPreviews(previews, stack);
}
@Override
public LittleStructure getLittleStructure(ItemStack stack)
{
return null;
}
@Override
public boolean containsIngredients(ItemStack stack)
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public void onClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
getMode(stack).onClickBlock(player, stack, result);
}
@Override
@SideOnly(Side.CLIENT)
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
return getMode(stack).onRightClick(player, stack, result);
}
@Override
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
return getMode(stack).onMouseWheelClickBlock(player, stack, result);
}
public static GrabberMode getMode(String name)
{
GrabberMode mode = GrabberMode.modes.get(name);
if(mode != null)
return mode;
return GrabberMode.defaultMode;
}
public static GrabberMode getMode(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
GrabberMode mode = GrabberMode.modes.get(stack.getTagCompound().getString("mode"));
if(mode != null)
return mode;
return GrabberMode.defaultMode;
}
public static void setMode(ItemStack stack, GrabberMode mode)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setString("mode", mode.name);
}
public static GrabberMode[] getModes()
{
return GrabberMode.modes.values().toArray(new GrabberMode[0]);
}
public static int indexOf(GrabberMode mode)
{
GrabberMode[] modes = getModes();
for (int i = 0; i < modes.length; i++) {
if(modes[i] == mode)
return i;
}
return -1;
}
public static abstract class GrabberMode {
public static HashMap<String, GrabberMode> modes = new LinkedHashMap<>();
public static PixelMode pixelMode = new PixelMode();
public static PlacePreviewMode placePreviewMode = new PlacePreviewMode();
public static ReplaceMode replaceMode = new ReplaceMode();
public static GrabberMode defaultMode = pixelMode;
public final String name;
public final String title;
public GrabberMode(String name)
{
this.name = name;
this.title = "grabber.mode." + name;
modes.put(name, this);
}
public String getLocalizedName()
{
return I18n.translateToLocal(title);
}
@SideOnly(Side.CLIENT)
public void onClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
GuiHandler.openGui("grabber", new NBTTagCompound(), player);
}
@SideOnly(Side.CLIENT)
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
return true;
}
@SideOnly(Side.CLIENT)
public abstract boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result);
@SideOnly(Side.CLIENT)
public abstract List<RenderCubeObject> getRenderingCubes(ItemStack stack);
@SideOnly(Side.CLIENT)
public abstract boolean renderBlockSeparately(ItemStack stack);
@SideOnly(Side.CLIENT)
public abstract SubGuiGrabber getGui(EntityPlayer player, ItemStack stack);
public abstract SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack);
public abstract List<LittleTilePreview> getPreviews(ItemStack stack);
public abstract void setPreviews(List<LittleTilePreview> previews, ItemStack stack);
public LittleTilePreview getSeparateRenderingPreview(ItemStack stack)
{
return getPreviews(stack).get(0);
}
public abstract void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state);
public abstract void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack, BlockPos pos, NBTTagCompound nbt);
}
public static abstract class SimpleMode extends GrabberMode {
public SimpleMode(String name) {
super(name);
}
@Override
@SideOnly(Side.CLIENT)
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
IBlockState state = player.world.getBlockState(result.getBlockPos());
if(SubContainerGrabber.isBlockValid(state.getBlock()))
{
PacketHandler.sendPacketToServer(new LittleVanillaBlockPacket(result.getBlockPos(), VanillaBlockAction.GRABBER));
return true;
}
else if(state.getBlock() instanceof BlockTile)
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setBoolean("secondMode", LittleAction.isUsingSecondMode(player));
PacketHandler.sendPacketToServer(new LittleBlockPacket(result.getBlockPos(), player, BlockPacketAction.GRABBER, nbt));
return true;
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(ItemStack stack) {
return Collections.emptyList();
}
@Override
@SideOnly(Side.CLIENT)
public boolean renderBlockSeparately(ItemStack stack) {
return true;
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
List<LittleTilePreview> previews = new ArrayList<>();
previews.add(getPreview(stack));
return previews;
}
@Override
public void setPreviews(List<LittleTilePreview> previews, ItemStack stack) {
setPreview(stack, previews.get(0));
}
@Override
public void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state) {
LittleTilePreview oldPreview = getPreview(stack);
LittleTile tile = new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = oldPreview.box;
setPreview(stack, tile.getPreviewTile());
}
@Override
public void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack,
BlockPos pos, NBTTagCompound nbt) {
LittleTilePreview oldPreview = getPreview(stack);
LittleTilePreview preview = tile.getPreviewTile();
preview.box = oldPreview.box;
setPreview(stack, preview);
}
public static LittleTilePreview getPreview(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
LittleTilePreview preview = null;
if(stack.getTagCompound().hasKey("preview"))
preview = LittleTilePreview.loadPreviewFromNBT(stack.getTagCompound().getCompoundTag("preview"));
else
{
IBlockState state = stack.getTagCompound().hasKey("state") ? Block.getStateById(stack.getTagCompound().getInteger("state")) : Blocks.STONE.getDefaultState();
LittleTile tile = stack.getTagCompound().hasKey("color") ? new LittleTileBlockColored(state.getBlock(), state.getBlock().getMetaFromState(state), stack.getTagCompound().getInteger("color")) : new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, 1, 1, 1);
preview = tile.getPreviewTile();
setPreview(stack, preview);
}
return preview;
}
public static void setPreview(ItemStack stack, LittleTilePreview preview)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
NBTTagCompound nbt = new NBTTagCompound();
preview.writeToNBT(nbt);
stack.getTagCompound().setTag("preview", nbt);
}
}
public static class PixelMode extends SimpleMode {
public PixelMode() {
super("pixel");
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack)
{
return new SubGuiGrabber(this, stack, 140, 140)
{
public LittleTileSize size;
public boolean isColored = false;
@Override
public void createControls() {
super.createControls();
LittleTilePreview preview = getPreview(stack);
size = preview.box.getSize();
controls.add(new GuiSteppedSlider("sizeX", 25, 30, 50, 14, size.sizeX, 1, LittleTile.gridSize));
controls.add(new GuiSteppedSlider("sizeY", 25, 50, 50, 14, size.sizeY, 1, LittleTile.gridSize));
controls.add(new GuiSteppedSlider("sizeZ", 25, 70, 50, 14, size.sizeZ, 1, LittleTile.gridSize));
Color color = ColorUtils.IntToRGBA(preview.getColor());
color.setAlpha(255);
controls.add(new GuiColorPicker("picker", 0, 95, color));
GuiAvatarLabel label = new GuiAvatarLabel("", 110, 40, 0, null);
label.name = "avatar";
label.height = 60;
label.avatarSize = 32;
controls.add(label);
updateLabel();
}
public void updateLabel()
{
GuiAvatarLabel label = (GuiAvatarLabel) get("avatar");
LittleTilePreview preview = getPreview(stack);
GuiColorPicker picker = (GuiColorPicker) get("picker");
preview.setColor(ColorUtils.RGBAToInt(picker.color));
preview.box.set(0, 0, 0, size.sizeX, size.sizeY, size.sizeZ);
label.avatar = new AvatarItemStack(ItemBlockTiles.getStackFromPreview(preview));
}
@CustomEventSubscribe
public void onSlotChange(SlotChangeEvent event)
{
ItemStack slotStack = container.getSlots().get(0).getStack();
Block block = Block.getBlockFromItem(slotStack.getItem());
if(block == LittleTiles.blockTile)
{
List<LittleTilePreview> previews = ((ILittleTile) slotStack.getItem()).getLittlePreview(slotStack);
if(previews.size() > 0)
{
int colorInt = previews.get(0).getColor();
Vec3i color = ColorUtils.IntToRGB(colorInt);
if(colorInt == -1)
color = new Vec3i(255, 255, 255);
GuiColorPicker picker = (GuiColorPicker) get("picker");
picker.color.set(color.getX(), color.getY(), color.getZ());
}
}
updateLabel();
}
@CustomEventSubscribe
public void onClick(GuiControlClickEvent event)
{
if(event.source.is("sliced"))
updateLabel();
}
@CustomEventSubscribe
public void onChange(GuiControlChangedEvent event)
{
size.sizeX = (int) ((GuiSteppedSlider) get("sizeX")).value;
size.sizeY = (int) ((GuiSteppedSlider) get("sizeY")).value;
size.sizeZ = (int) ((GuiSteppedSlider) get("sizeZ")).value;
updateLabel();
}
@Override
public void saveChanges() {
LittleTilePreview preview = getPreview(stack);
preview.box.set(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, size.sizeX, size.sizeY, size.sizeZ);
GuiColorPicker picker = (GuiColorPicker) get("picker");
preview.setColor(ColorUtils.RGBAToInt(picker.color));
setPreview(stack, preview);
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
}
public static class PlacePreviewMode extends GrabberMode {
public PlacePreviewMode() {
super("place_preview");
}
@Override
@SideOnly(Side.CLIENT)
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
IBlockState state = player.world.getBlockState(result.getBlockPos());
if(SubContainerGrabber.isBlockValid(state.getBlock()))
{
PacketHandler.sendPacketToServer(new LittleVanillaBlockPacket(result.getBlockPos(), VanillaBlockAction.GRABBER));
return true;
}
else if(state.getBlock() instanceof BlockTile)
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setBoolean("secondMode", LittleAction.isUsingSecondMode(player));
PacketHandler.sendPacketToServer(new LittleBlockPacket(result.getBlockPos(), player, BlockPacketAction.GRABBER, nbt));
return true;
}
return false;
}
@Override
public void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state)
{
LittleTile tile = new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, LittleTile.gridSize, LittleTile.gridSize, LittleTile.gridSize);
List<LittleTilePreview> previews = new ArrayList<>();
previews.add(tile.getPreviewTile());
PlacePreviewMode.setPreview(stack, previews);
}
@Override
public void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack, BlockPos pos, NBTTagCompound nbt)
{
List<LittleTilePreview> previews = new ArrayList<>();
if(nbt.getBoolean("secondMode"))
{
for (LittleTile tileFromTE : te.getTiles()) {
previews.add(tileFromTE.getPreviewTile());
}
}
else
previews.add(tile.getPreviewTile());
ItemLittleGrabber.PlacePreviewMode.setPreview(stack, previews);
}
public static List<LittleTilePreview> getPreview(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
List<LittleTilePreview> previews = LittleTilePreview.getPreview(stack);
if(previews.size() == 0)
{
IBlockState state = stack.getTagCompound().hasKey("state") ? Block.getStateById(stack.getTagCompound().getInteger("state")) : Blocks.STONE.getDefaultState();
LittleTile tile = stack.getTagCompound().hasKey("color") ? new LittleTileBlockColored(state.getBlock(), state.getBlock().getMetaFromState(state), stack.getTagCompound().getInteger("color")) : new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, 1, 1, 1);
LittleTilePreview preview = tile.getPreviewTile();
previews.add(preview);
setPreview(stack, previews);
}
return previews;
}
public static void setPreview(ItemStack stack, List<LittleTilePreview> previews)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
LittleTilePreview.savePreviewTiles(previews, stack);
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(ItemStack stack) {
return LittleTilePreview.getCubes(stack);
}
@Override
@SideOnly(Side.CLIENT)
public boolean renderBlockSeparately(ItemStack stack) {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack) {
return new SubGuiGrabber(this, stack, 140, 140) {
@Override
public void saveChanges() {
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
return getPreview(stack);
}
@Override
public void setPreviews(List<LittleTilePreview> previews, ItemStack stack) {
PlacePreviewMode.setPreview(stack, previews);
}
}
public static class ReplaceMode extends SimpleMode {
public ReplaceMode() {
super("replace");
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack) {
return new SubGuiGrabber(this, stack, 140, 140) {
@Override
public void saveChanges() {
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
return Collections.emptyList();
}
@Override
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result) {
if(PlacementHelper.canBlockBeUsed(player.world, result.getBlockPos()))
new LittleActionReplace(result.getBlockPos(), player, getPreview(stack)).execute();
return false;
}
@Override
public LittleTilePreview getSeparateRenderingPreview(ItemStack stack) {
return getPreview(stack);
}
}
}
|
src/main/java/com/creativemd/littletiles/common/items/ItemLittleGrabber.java
|
package com.creativemd.littletiles.common.items;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.Nullable;
import org.lwjgl.util.Color;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.client.rendering.RenderCubeObject;
import com.creativemd.creativecore.client.rendering.model.CreativeBakedModel;
import com.creativemd.creativecore.client.rendering.model.ICreativeRendered;
import com.creativemd.creativecore.common.packet.PacketHandler;
import com.creativemd.creativecore.common.utils.ColorUtils;
import com.creativemd.creativecore.common.utils.Rotation;
import com.creativemd.creativecore.gui.container.SubContainer;
import com.creativemd.creativecore.gui.container.SubGui;
import com.creativemd.creativecore.gui.controls.gui.GuiAvatarLabel;
import com.creativemd.creativecore.gui.controls.gui.GuiColorPicker;
import com.creativemd.creativecore.gui.controls.gui.GuiSteppedSlider;
import com.creativemd.creativecore.gui.event.container.SlotChangeEvent;
import com.creativemd.creativecore.gui.event.gui.GuiControlChangedEvent;
import com.creativemd.creativecore.gui.event.gui.GuiControlClickEvent;
import com.creativemd.creativecore.gui.opener.GuiHandler;
import com.creativemd.creativecore.gui.opener.IGuiCreator;
import com.creativemd.littletiles.LittleTiles;
import com.creativemd.littletiles.common.action.LittleAction;
import com.creativemd.littletiles.common.action.block.LittleActionReplace;
import com.creativemd.littletiles.common.api.ILittleTile;
import com.creativemd.littletiles.common.blocks.BlockTile;
import com.creativemd.littletiles.common.container.SubContainerChisel;
import com.creativemd.littletiles.common.container.SubContainerGrabber;
import com.creativemd.littletiles.common.gui.SubGuiChisel;
import com.creativemd.littletiles.common.gui.SubGuiGrabber;
import com.creativemd.littletiles.common.items.ItemLittleGrabber.PlacePreviewMode;
import com.creativemd.littletiles.common.packet.LittleBlockPacket;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket;
import com.creativemd.littletiles.common.packet.LittleBlockPacket.BlockPacketAction;
import com.creativemd.littletiles.common.packet.LittleVanillaBlockPacket.VanillaBlockAction;
import com.creativemd.littletiles.common.structure.LittleStructure;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles;
import com.creativemd.littletiles.common.tiles.LittleTile;
import com.creativemd.littletiles.common.tiles.LittleTileBlock;
import com.creativemd.littletiles.common.tiles.LittleTileBlockColored;
import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview;
import com.creativemd.littletiles.common.tiles.vec.LittleTileBox;
import com.creativemd.littletiles.common.tiles.vec.LittleTileSize;
import com.creativemd.littletiles.common.tiles.vec.LittleTileVec;
import com.creativemd.littletiles.common.utils.geo.DragShape;
import com.creativemd.littletiles.common.utils.placing.PlacementHelper;
import com.n247s.api.eventapi.eventsystem.CustomEventSubscribe;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3i;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import scala.tools.nsc.doc.model.Def;
import scala.tools.nsc.transform.patmat.Solving.Solver.Lit;
public class ItemLittleGrabber extends Item implements ICreativeRendered, ILittleTile {
public ItemLittleGrabber()
{
setCreativeTab(LittleTiles.littleTab);
hasSubtypes = true;
setMaxStackSize(1);
}
@Override
public float getDestroySpeed(ItemStack stack, IBlockState state)
{
return 0F;
}
@Override
public boolean canDestroyBlockInCreative(World world, BlockPos pos, ItemStack stack, EntityPlayer player)
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(IBlockState state, TileEntity te, ItemStack stack) {
return getMode(stack).getRenderingCubes(stack);
}
@Override
@SideOnly(Side.CLIENT)
public void applyCustomOpenGLHackery(ItemStack stack, TransformType cameraTransformType)
{
Minecraft mc = Minecraft.getMinecraft();
GlStateManager.pushMatrix();
IBakedModel model = mc.getRenderItem().getItemModelMesher().getModelManager().getModel(new ModelResourceLocation(LittleTiles.modid + ":grabber_background", "inventory"));
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
mc.getRenderItem().renderItem(new ItemStack(Items.PAPER), model);
if(cameraTransformType == TransformType.GUI)
{
GlStateManager.scale(0.9, 0.9, 0.9);
GrabberMode mode = getMode(stack);
if(mode.renderBlockSeparately(stack))
{
LittleTilePreview preview = mode.getSeparateRenderingPreview(stack);
ItemStack blockStack = new ItemStack(preview.getPreviewBlock(), 1, preview.getPreviewBlockMeta());
model = mc.getRenderItem().getItemModelWithOverrides(blockStack, mc.world, mc.player); //getItemModelMesher().getItemModel(blockStack);
if(!(model instanceof CreativeBakedModel))
ForgeHooksClient.handleCameraTransforms(model, cameraTransformType, false);
GlStateManager.disableDepth();
GlStateManager.pushMatrix();
GlStateManager.translate(-0.5F, -0.5F, -0.5F);
try {
if (model.isBuiltInRenderer())
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableRescaleNormal();
TileEntityItemStackRenderer.instance.renderByItem(blockStack);
}else{
Color color = preview.hasColor() ? ColorUtils.IntToRGBA(preview.getColor()) : ColorUtils.IntToRGBA(ColorUtils.WHITE);
color.setAlpha(255);
ReflectionHelper.findMethod(RenderItem.class, "renderModel", "func_191967_a", IBakedModel.class, int.class, ItemStack.class).invoke(mc.getRenderItem(), model, ColorUtils.RGBAToInt(color), blockStack);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
GlStateManager.popMatrix();
}
GlStateManager.enableDepth();
}
GlStateManager.popMatrix();
}
@Override
public boolean hasLittlePreview(ItemStack stack)
{
return true;
}
@Override
public List<LittleTilePreview> getLittlePreview(ItemStack stack)
{
return getMode(stack).getPreviews(stack);
}
@Override
public void saveLittlePreview(ItemStack stack, List<LittleTilePreview> previews)
{
PlacePreviewMode.setPreview(stack, previews);
}
@Override
public LittleStructure getLittleStructure(ItemStack stack)
{
return null;
}
@Override
public boolean containsIngredients(ItemStack stack)
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public void onClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
getMode(stack).onClickBlock(player, stack, result);
}
@Override
@SideOnly(Side.CLIENT)
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
return getMode(stack).onRightClick(player, stack, result);
}
@Override
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
return getMode(stack).onMouseWheelClickBlock(player, stack, result);
}
public static GrabberMode getMode(String name)
{
GrabberMode mode = GrabberMode.modes.get(name);
if(mode != null)
return mode;
return GrabberMode.defaultMode;
}
public static GrabberMode getMode(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
GrabberMode mode = GrabberMode.modes.get(stack.getTagCompound().getString("mode"));
if(mode != null)
return mode;
return GrabberMode.defaultMode;
}
public static void setMode(ItemStack stack, GrabberMode mode)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setString("mode", mode.name);
}
public static GrabberMode[] getModes()
{
return GrabberMode.modes.values().toArray(new GrabberMode[0]);
}
public static int indexOf(GrabberMode mode)
{
GrabberMode[] modes = getModes();
for (int i = 0; i < modes.length; i++) {
if(modes[i] == mode)
return i;
}
return -1;
}
public static abstract class GrabberMode {
public static HashMap<String, GrabberMode> modes = new LinkedHashMap<>();
public static PixelMode pixelMode = new PixelMode();
public static PlacePreviewMode placePreviewMode = new PlacePreviewMode();
public static ReplaceMode replaceMode = new ReplaceMode();
public static GrabberMode defaultMode = pixelMode;
public final String name;
public final String title;
public GrabberMode(String name)
{
this.name = name;
this.title = "grabber.mode." + name;
modes.put(name, this);
}
public String getLocalizedName()
{
return I18n.translateToLocal(title);
}
@SideOnly(Side.CLIENT)
public void onClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
GuiHandler.openGui("grabber", new NBTTagCompound(), player);
}
@SideOnly(Side.CLIENT)
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result)
{
return true;
}
@SideOnly(Side.CLIENT)
public abstract boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result);
@SideOnly(Side.CLIENT)
public abstract List<RenderCubeObject> getRenderingCubes(ItemStack stack);
@SideOnly(Side.CLIENT)
public abstract boolean renderBlockSeparately(ItemStack stack);
@SideOnly(Side.CLIENT)
public abstract SubGuiGrabber getGui(EntityPlayer player, ItemStack stack);
public abstract SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack);
public abstract List<LittleTilePreview> getPreviews(ItemStack stack);
public LittleTilePreview getSeparateRenderingPreview(ItemStack stack)
{
return getPreviews(stack).get(0);
}
public abstract void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state);
public abstract void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack, BlockPos pos, NBTTagCompound nbt);
}
public static abstract class SimpleMode extends GrabberMode {
public SimpleMode(String name) {
super(name);
}
@Override
@SideOnly(Side.CLIENT)
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
IBlockState state = player.world.getBlockState(result.getBlockPos());
if(SubContainerGrabber.isBlockValid(state.getBlock()))
{
PacketHandler.sendPacketToServer(new LittleVanillaBlockPacket(result.getBlockPos(), VanillaBlockAction.GRABBER));
return true;
}
else if(state.getBlock() instanceof BlockTile)
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setBoolean("secondMode", LittleAction.isUsingSecondMode(player));
PacketHandler.sendPacketToServer(new LittleBlockPacket(result.getBlockPos(), player, BlockPacketAction.GRABBER, nbt));
return true;
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(ItemStack stack) {
return Collections.emptyList();
}
@Override
@SideOnly(Side.CLIENT)
public boolean renderBlockSeparately(ItemStack stack) {
return true;
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
List<LittleTilePreview> previews = new ArrayList<>();
previews.add(getPreview(stack));
return previews;
}
@Override
public void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state) {
LittleTilePreview oldPreview = getPreview(stack);
LittleTile tile = new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = oldPreview.box;
setPreview(stack, tile.getPreviewTile());
}
@Override
public void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack,
BlockPos pos, NBTTagCompound nbt) {
LittleTilePreview oldPreview = getPreview(stack);
LittleTilePreview preview = tile.getPreviewTile();
preview.box = oldPreview.box;
setPreview(stack, preview);
}
public static LittleTilePreview getPreview(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
LittleTilePreview preview = null;
if(stack.getTagCompound().hasKey("preview"))
preview = LittleTilePreview.loadPreviewFromNBT(stack.getTagCompound().getCompoundTag("preview"));
else
{
IBlockState state = stack.getTagCompound().hasKey("state") ? Block.getStateById(stack.getTagCompound().getInteger("state")) : Blocks.STONE.getDefaultState();
LittleTile tile = stack.getTagCompound().hasKey("color") ? new LittleTileBlockColored(state.getBlock(), state.getBlock().getMetaFromState(state), stack.getTagCompound().getInteger("color")) : new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, 1, 1, 1);
preview = tile.getPreviewTile();
setPreview(stack, preview);
}
return preview;
}
public static void setPreview(ItemStack stack, LittleTilePreview preview)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
NBTTagCompound nbt = new NBTTagCompound();
preview.writeToNBT(nbt);
stack.getTagCompound().setTag("preview", nbt);
}
}
public static class PixelMode extends SimpleMode {
public PixelMode() {
super("pixel");
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack)
{
return new SubGuiGrabber(this, stack, 140, 140)
{
public LittleTileSize size;
public boolean isColored = false;
@Override
public void createControls() {
super.createControls();
LittleTilePreview preview = getPreview(stack);
size = preview.box.getSize();
controls.add(new GuiSteppedSlider("sizeX", 25, 30, 50, 14, size.sizeX, 1, LittleTile.gridSize));
controls.add(new GuiSteppedSlider("sizeY", 25, 50, 50, 14, size.sizeY, 1, LittleTile.gridSize));
controls.add(new GuiSteppedSlider("sizeZ", 25, 70, 50, 14, size.sizeZ, 1, LittleTile.gridSize));
Color color = ColorUtils.IntToRGBA(preview.getColor());
color.setAlpha(255);
controls.add(new GuiColorPicker("picker", 0, 95, color));
GuiAvatarLabel label = new GuiAvatarLabel("", 110, 40, 0, null);
label.name = "avatar";
label.height = 60;
label.avatarSize = 32;
controls.add(label);
updateLabel();
}
public void updateLabel()
{
GuiAvatarLabel label = (GuiAvatarLabel) get("avatar");
LittleTilePreview preview = getPreview(stack);
GuiColorPicker picker = (GuiColorPicker) get("picker");
preview.setColor(ColorUtils.RGBAToInt(picker.color));
preview.box.set(0, 0, 0, size.sizeX, size.sizeY, size.sizeZ);
label.avatar = new AvatarItemStack(ItemBlockTiles.getStackFromPreview(preview));
}
@CustomEventSubscribe
public void onSlotChange(SlotChangeEvent event)
{
ItemStack slotStack = container.getSlots().get(0).getStack();
Block block = Block.getBlockFromItem(slotStack.getItem());
if(block == LittleTiles.blockTile)
{
List<LittleTilePreview> previews = ((ILittleTile) slotStack.getItem()).getLittlePreview(slotStack);
if(previews.size() > 0)
{
int colorInt = previews.get(0).getColor();
Vec3i color = ColorUtils.IntToRGB(colorInt);
if(colorInt == -1)
color = new Vec3i(255, 255, 255);
GuiColorPicker picker = (GuiColorPicker) get("picker");
picker.color.set(color.getX(), color.getY(), color.getZ());
}
}
updateLabel();
}
@CustomEventSubscribe
public void onClick(GuiControlClickEvent event)
{
if(event.source.is("sliced"))
updateLabel();
}
@CustomEventSubscribe
public void onChange(GuiControlChangedEvent event)
{
size.sizeX = (int) ((GuiSteppedSlider) get("sizeX")).value;
size.sizeY = (int) ((GuiSteppedSlider) get("sizeY")).value;
size.sizeZ = (int) ((GuiSteppedSlider) get("sizeZ")).value;
updateLabel();
}
@Override
public void saveChanges() {
LittleTilePreview preview = getPreview(stack);
preview.box.set(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, size.sizeX, size.sizeY, size.sizeZ);
GuiColorPicker picker = (GuiColorPicker) get("picker");
preview.setColor(ColorUtils.RGBAToInt(picker.color));
setPreview(stack, preview);
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
}
public static class PlacePreviewMode extends GrabberMode {
public PlacePreviewMode() {
super("place_preview");
}
@Override
@SideOnly(Side.CLIENT)
public boolean onMouseWheelClickBlock(EntityPlayer player, ItemStack stack, RayTraceResult result) {
IBlockState state = player.world.getBlockState(result.getBlockPos());
if(SubContainerGrabber.isBlockValid(state.getBlock()))
{
PacketHandler.sendPacketToServer(new LittleVanillaBlockPacket(result.getBlockPos(), VanillaBlockAction.GRABBER));
return true;
}
else if(state.getBlock() instanceof BlockTile)
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setBoolean("secondMode", LittleAction.isUsingSecondMode(player));
PacketHandler.sendPacketToServer(new LittleBlockPacket(result.getBlockPos(), player, BlockPacketAction.GRABBER, nbt));
return true;
}
return false;
}
@Override
public void vanillaBlockAction(World world, ItemStack stack, BlockPos pos, IBlockState state)
{
LittleTile tile = new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, LittleTile.gridSize, LittleTile.gridSize, LittleTile.gridSize);
List<LittleTilePreview> previews = new ArrayList<>();
previews.add(tile.getPreviewTile());
PlacePreviewMode.setPreview(stack, previews);
}
@Override
public void littleBlockAction(World world, TileEntityLittleTiles te, LittleTile tile, ItemStack stack, BlockPos pos, NBTTagCompound nbt)
{
List<LittleTilePreview> previews = new ArrayList<>();
if(nbt.getBoolean("secondMode"))
{
for (LittleTile tileFromTE : te.getTiles()) {
previews.add(tileFromTE.getPreviewTile());
}
}
else
previews.add(tile.getPreviewTile());
ItemLittleGrabber.PlacePreviewMode.setPreview(stack, previews);
}
public static List<LittleTilePreview> getPreview(ItemStack stack)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
List<LittleTilePreview> previews = LittleTilePreview.getPreview(stack);
if(previews.size() == 0)
{
IBlockState state = stack.getTagCompound().hasKey("state") ? Block.getStateById(stack.getTagCompound().getInteger("state")) : Blocks.STONE.getDefaultState();
LittleTile tile = stack.getTagCompound().hasKey("color") ? new LittleTileBlockColored(state.getBlock(), state.getBlock().getMetaFromState(state), stack.getTagCompound().getInteger("color")) : new LittleTileBlock(state.getBlock(), state.getBlock().getMetaFromState(state));
tile.box = new LittleTileBox(LittleTile.minPos, LittleTile.minPos, LittleTile.minPos, 1, 1, 1);
LittleTilePreview preview = tile.getPreviewTile();
previews.add(preview);
setPreview(stack, previews);
}
return previews;
}
public static void setPreview(ItemStack stack, List<LittleTilePreview> previews)
{
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
LittleTilePreview.savePreviewTiles(previews, stack);
}
@Override
@SideOnly(Side.CLIENT)
public List<RenderCubeObject> getRenderingCubes(ItemStack stack) {
return LittleTilePreview.getCubes(stack);
}
@Override
@SideOnly(Side.CLIENT)
public boolean renderBlockSeparately(ItemStack stack) {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack) {
return new SubGuiGrabber(this, stack, 140, 140) {
@Override
public void saveChanges() {
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
return getPreview(stack);
}
}
public static class ReplaceMode extends SimpleMode {
public ReplaceMode() {
super("replace");
}
@Override
@SideOnly(Side.CLIENT)
public SubGuiGrabber getGui(EntityPlayer player, ItemStack stack) {
return new SubGuiGrabber(this, stack, 140, 140) {
@Override
public void saveChanges() {
}
};
}
@Override
public SubContainerGrabber getContainer(EntityPlayer player, ItemStack stack) {
return new SubContainerGrabber(player, stack);
}
@Override
public List<LittleTilePreview> getPreviews(ItemStack stack) {
return Collections.emptyList();
}
@Override
public boolean onRightClick(EntityPlayer player, ItemStack stack, RayTraceResult result) {
if(PlacementHelper.canBlockBeUsed(player.world, result.getBlockPos()))
new LittleActionReplace(result.getBlockPos(), player, getPreview(stack)).execute();
return false;
}
@Override
public LittleTilePreview getSeparateRenderingPreview(ItemStack stack) {
return getPreview(stack);
}
}
}
|
Fixed not being able to rotate stuff using pixel mode
|
src/main/java/com/creativemd/littletiles/common/items/ItemLittleGrabber.java
|
Fixed not being able to rotate stuff using pixel mode
|
|
Java
|
apache-2.0
|
ea7a728675c985afe14c1bb3b5650eb23333c0cd
| 0
|
matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk
|
/*
* Copyright 2014 OpenMarket 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.matrix.androidsdk;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.JsonObject;
import org.matrix.androidsdk.call.MXCallsManager;
import org.matrix.androidsdk.crypto.MXCrypto;
import org.matrix.androidsdk.crypto.MXCryptoError;
import org.matrix.androidsdk.data.DataRetriever;
import org.matrix.androidsdk.data.RoomSummary;
import org.matrix.androidsdk.data.cryptostore.IMXCryptoStore;
import org.matrix.androidsdk.data.store.IMXStore;
import org.matrix.androidsdk.data.cryptostore.MXFileCryptoStore;
import org.matrix.androidsdk.data.MyUser;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.db.MXLatestChatMessageCache;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.network.NetworkConnectivityReceiver;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.ApiFailureCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.client.AccountDataRestClient;
import org.matrix.androidsdk.rest.client.BingRulesRestClient;
import org.matrix.androidsdk.rest.client.CallRestClient;
import org.matrix.androidsdk.rest.client.CryptoRestClient;
import org.matrix.androidsdk.rest.client.EventsRestClient;
import org.matrix.androidsdk.rest.client.LoginRestClient;
import org.matrix.androidsdk.rest.client.PresenceRestClient;
import org.matrix.androidsdk.rest.client.ProfileRestClient;
import org.matrix.androidsdk.rest.client.PushersRestClient;
import org.matrix.androidsdk.rest.client.RoomsRestClient;
import org.matrix.androidsdk.rest.client.ThirdPidRestClient;
import org.matrix.androidsdk.rest.model.CreateRoomResponse;
import org.matrix.androidsdk.rest.model.DeleteDeviceAuth;
import org.matrix.androidsdk.rest.model.DeleteDeviceParams;
import org.matrix.androidsdk.rest.model.DevicesListResponse;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.rest.model.RoomResponse;
import org.matrix.androidsdk.rest.model.Search.SearchResponse;
import org.matrix.androidsdk.rest.model.User;
import org.matrix.androidsdk.rest.model.bingrules.BingRule;
import org.matrix.androidsdk.rest.model.login.Credentials;
import org.matrix.androidsdk.rest.model.login.RegistrationFlowResponse;
import org.matrix.androidsdk.sync.DefaultEventsThreadListener;
import org.matrix.androidsdk.sync.EventsThread;
import org.matrix.androidsdk.sync.EventsThreadListener;
import org.matrix.androidsdk.util.BingRulesManager;
import org.matrix.androidsdk.util.ContentManager;
import org.matrix.androidsdk.util.JsonUtils;
import org.matrix.androidsdk.util.UnsentEventsManager;
import org.matrix.olm.OlmManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Class that represents one user's session with a particular home server.
* There can potentially be multiple sessions for handling multiple accounts.
*/
public class MXSession {
private static final String LOG_TAG = "MXSession";
private DataRetriever mDataRetriever;
private MXDataHandler mDataHandler;
private EventsThread mEventsThread;
private Credentials mCredentials;
// Api clients
private EventsRestClient mEventsRestClient;
private ProfileRestClient mProfileRestClient;
private PresenceRestClient mPresenceRestClient;
private RoomsRestClient mRoomsRestClient;
private BingRulesRestClient mBingRulesRestClient;
private PushersRestClient mPushersRestClient;
private ThirdPidRestClient mThirdPidRestClient;
private CallRestClient mCallRestClient;
private AccountDataRestClient mAccountDataRestClient;
private CryptoRestClient mCryptoRestClient;
private LoginRestClient mLoginRestClient;
private ApiFailureCallback mFailureCallback;
private ContentManager mContentManager;
public MXCallsManager mCallsManager;
private Context mAppContent;
private NetworkConnectivityReceiver mNetworkConnectivityReceiver;
private UnsentEventsManager mUnsentEventsManager;
private MXLatestChatMessageCache mLatestChatMessageCache;
private MXMediasCache mMediasCache;
private BingRulesManager mBingRulesManager = null;
private boolean mIsAliveSession = true;
// online status
private boolean mIsOnline = true;
private HomeserverConnectionConfig mHsConfig;
// the application is launched from a notification
// so, mEventsThread.start might be not ready
private boolean mIsCatchupPending = false;
// load the crypto libs.
public static OlmManager mOlmManager = new OlmManager(android.os.Build.VERSION.SDK_INT < 23);
// regex pattern to find matrix user ids in a string.
public static final String MATRIX_USER_IDENTIFIER_REGEX = "@[A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_USER_IDENTIFIER = Pattern.compile(MATRIX_USER_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find room aliases in a string.
public static final String MATRIX_ROOM_ALIAS_REGEX = "#[A-Z0-9._%+-\\\\#]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_ALIAS = Pattern.compile(MATRIX_ROOM_ALIAS_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find room ids in a string.
public static final String MATRIX_ROOM_IDENTIFIER_REGEX = "![A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_ROOM_IDENTIFIER = Pattern.compile(MATRIX_ROOM_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find message ids in a string.
public static final String MATRIX_MESSAGE_IDENTIFIER_REGEX = "\\$[A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_MESSAGE_IDENTIFIER = Pattern.compile(MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find permalink with message id.
// Android does not support in URL so extract it.
public static final Pattern PATTERN_CONTAIN_MATRIX_TO_PERMALINK_ROOM_ID = Pattern.compile("https:\\/\\/matrix\\.to\\/#\\/"+ MATRIX_ROOM_IDENTIFIER_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_MATRIX_TO_PERMALINK_ROOM_ALIAS = Pattern.compile("https:\\/\\/matrix\\.to\\/#\\/"+ MATRIX_ROOM_ALIAS_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_APP_LINK_PERMALINK_ROOM_ID = Pattern.compile("https:\\/\\/[A-Z0-9.-]+\\.[A-Z]{2,}\\/[A-Z]{3,}\\/#\\/room\\/"+ MATRIX_ROOM_IDENTIFIER_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_APP_LINK_PERMALINK_ROOM_ALIAS = Pattern.compile("https:\\/\\/[A-Z0-9.-]+\\.[A-Z]{2,}\\/[A-Z]{3,}\\/#\\/room\\/"+ MATRIX_ROOM_ALIAS_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
/**
* Create a basic session for direct API calls.
*
* @param hsConfig the home server connection config
*/
public MXSession(HomeserverConnectionConfig hsConfig) {
mCredentials = hsConfig.getCredentials();
mHsConfig = hsConfig;
mEventsRestClient = new EventsRestClient(hsConfig);
mProfileRestClient = new ProfileRestClient(hsConfig);
mPresenceRestClient = new PresenceRestClient(hsConfig);
mRoomsRestClient = new RoomsRestClient(hsConfig);
mBingRulesRestClient = new BingRulesRestClient(hsConfig);
mPushersRestClient = new PushersRestClient(hsConfig);
mThirdPidRestClient = new ThirdPidRestClient(hsConfig);
mCallRestClient = new CallRestClient(hsConfig);
mAccountDataRestClient = new AccountDataRestClient(hsConfig);
mCryptoRestClient = new CryptoRestClient(hsConfig);
mLoginRestClient = new LoginRestClient(hsConfig);
}
/**
* Create a user session with a data handler.
*
* @param hsConfig the home server connection config
* @param dataHandler the data handler
* @param appContext the application context
*/
public MXSession(HomeserverConnectionConfig hsConfig, MXDataHandler dataHandler, Context appContext) {
this(hsConfig);
mDataHandler = dataHandler;
mDataHandler.getStore().addMXStoreListener(new IMXStore.MXStoreListener() {
@Override
public void postProcess(String accountId) {
MXFileCryptoStore store = new MXFileCryptoStore();
store.initWithCredentials(mAppContent, mCredentials);
if (store.hasData() || mEnableCryptoWhenStartingMXSession) {
// open the store
store.open();
// enable
mCrypto = new MXCrypto(MXSession.this, store);
mDataHandler.setCrypto(mCrypto);
// the room summaries are not stored with decrypted content
decryptRoomSummaries();
}
}
@Override
public void onStoreReady(String accountId) {
}
@Override
public void onStoreCorrupted(String accountId, String description) {
}
@Override
public void onStoreOOM(String accountId, String description) {
}
});
// Initialize a data retriever with rest clients
mDataRetriever = new DataRetriever();
mDataRetriever.setRoomsRestClient(mRoomsRestClient);
mDataHandler.setDataRetriever(mDataRetriever);
mDataHandler.setProfileRestClient(mProfileRestClient);
mDataHandler.setPresenceRestClient(mPresenceRestClient);
mDataHandler.setThirdPidRestClient(mThirdPidRestClient);
mDataHandler.setRoomsRestClient(mRoomsRestClient);
// application context
mAppContent = appContext;
mNetworkConnectivityReceiver = new NetworkConnectivityReceiver();
mNetworkConnectivityReceiver.checkNetworkConnection(appContext);
mDataHandler.setNetworkConnectivityReceiver(mNetworkConnectivityReceiver);
mAppContent.registerReceiver(mNetworkConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mBingRulesManager = new BingRulesManager(this, mNetworkConnectivityReceiver);
mDataHandler.setPushRulesManager(mBingRulesManager);
mUnsentEventsManager = new UnsentEventsManager(mNetworkConnectivityReceiver, mDataHandler);
mContentManager = new ContentManager(hsConfig, mUnsentEventsManager);
//
mCallsManager = new MXCallsManager(this, mAppContent);
mDataHandler.setCallsManager(mCallsManager);
// the rest client
mEventsRestClient.setUnsentEventsManager(mUnsentEventsManager);
mProfileRestClient.setUnsentEventsManager(mUnsentEventsManager);
mPresenceRestClient.setUnsentEventsManager(mUnsentEventsManager);
mRoomsRestClient.setUnsentEventsManager(mUnsentEventsManager);
mBingRulesRestClient.setUnsentEventsManager(mUnsentEventsManager);
mThirdPidRestClient.setUnsentEventsManager(mUnsentEventsManager);
mCallRestClient.setUnsentEventsManager(mUnsentEventsManager);
mAccountDataRestClient.setUnsentEventsManager(mUnsentEventsManager);
mCryptoRestClient.setUnsentEventsManager(mUnsentEventsManager);
mLoginRestClient.setUnsentEventsManager(mUnsentEventsManager);
// return the default cache manager
mLatestChatMessageCache = new MXLatestChatMessageCache(mCredentials.userId);
mMediasCache = new MXMediasCache(mContentManager, mCredentials.userId, appContext);
mDataHandler.setMediasCache(mMediasCache);
}
private void checkIfAlive() {
synchronized (this) {
if (!mIsAliveSession) {
Log.e(LOG_TAG, "Use of a release session");
//throw new AssertionError("Should not used a cleared mxsession ");
}
}
}
/**
* @return the SDK version.
*/
public String getVersion(boolean longFormat) {
checkIfAlive();
String versionName = BuildConfig.VERSION_NAME;
if (!TextUtils.isEmpty(versionName)) {
String gitVersion = mAppContent.getResources().getString(R.string.git_sdk_revision);
if (longFormat) {
String date = mAppContent.getResources().getString(R.string.git_sdk_revision_date);
versionName += " (" + gitVersion + "-" + date + ")";
} else {
versionName += " (" + gitVersion + ")";
}
}
return versionName;
}
/**
* @return the crypto lib version
*/
public String getCryptoVersion() {
if (null != mOlmManager) {
return mOlmManager.getOlmLibVersion();
}
return "";
}
/**
* Get the data handler.
*
* @return the data handler.
*/
public MXDataHandler getDataHandler() {
checkIfAlive();
return mDataHandler;
}
/**
* Get the user credentials.
*
* @return the credentials
*/
public Credentials getCredentials() {
checkIfAlive();
return mCredentials;
}
/**
* Get the API client for requests to the events API.
*
* @return the events API client
*/
public EventsRestClient getEventsApiClient() {
checkIfAlive();
return mEventsRestClient;
}
/**
* Get the API client for requests to the profile API.
*
* @return the profile API client
*/
public ProfileRestClient getProfileApiClient() {
checkIfAlive();
return mProfileRestClient;
}
/**
* Get the API client for requests to the presence API.
*
* @return the presence API client
*/
public PresenceRestClient getPresenceApiClient() {
checkIfAlive();
return mPresenceRestClient;
}
/**
* Refresh the presence info of a dedicated user.
*
* @param userId the user userID.
* @param callback the callback.
*/
public void refreshUserPresence(final String userId, final ApiCallback<Void> callback) {
mPresenceRestClient.getPresence(userId, new ApiCallback<User>() {
@Override
public void onSuccess(User user) {
User currentUser = mDataHandler.getStore().getUser(userId);
if (null != currentUser) {
currentUser.presence = user.presence;
currentUser.currently_active = user.currently_active;
currentUser.lastActiveAgo = user.lastActiveAgo;
} else {
currentUser = user;
}
currentUser.setLatestPresenceTs(System.currentTimeMillis());
mDataHandler.getStore().storeUser(currentUser);
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Get the API client for requests to the bing rules API.
*
* @return the bing rules API client
*/
public BingRulesRestClient getBingRulesApiClient() {
checkIfAlive();
return mBingRulesRestClient;
}
public CallRestClient getCallRestClient() {
checkIfAlive();
return mCallRestClient;
}
public PushersRestClient getPushersRestClient() {
checkIfAlive();
return mPushersRestClient;
}
public CryptoRestClient getCryptoRestClient() {
checkIfAlive();
return mCryptoRestClient;
}
public HomeserverConnectionConfig getHomeserverConfig() {
checkIfAlive();
return mHsConfig;
}
/**
* Get the API client for requests to the rooms API.
*
* @return the rooms API client
*/
public RoomsRestClient getRoomsApiClient() {
checkIfAlive();
return mRoomsRestClient;
}
protected void setEventsApiClient(EventsRestClient eventsRestClient) {
checkIfAlive();
this.mEventsRestClient = eventsRestClient;
}
protected void setProfileApiClient(ProfileRestClient profileRestClient) {
checkIfAlive();
this.mProfileRestClient = profileRestClient;
}
protected void setPresenceApiClient(PresenceRestClient presenceRestClient) {
checkIfAlive();
this.mPresenceRestClient = presenceRestClient;
}
protected void setRoomsApiClient(RoomsRestClient roomsRestClient) {
checkIfAlive();
this.mRoomsRestClient = roomsRestClient;
}
public MXLatestChatMessageCache getLatestChatMessageCache() {
checkIfAlive();
return mLatestChatMessageCache;
}
public MXMediasCache getMediasCache() {
checkIfAlive();
return mMediasCache;
}
/**
* Clear the session data
*/
public void clear(Context context) {
checkIfAlive();
synchronized (this) {
mIsAliveSession = false;
}
// stop events stream
stopEventStream();
// cancel any listener
mDataHandler.clear();
// network event will not be listened anymore
mAppContent.unregisterReceiver(mNetworkConnectivityReceiver);
mNetworkConnectivityReceiver.removeListeners();
// auto resent messages will not be resent
mUnsentEventsManager.clear();
mLatestChatMessageCache.clearCache(context);
mMediasCache.clear();
if (null != mCrypto) {
mCrypto.close();
}
}
/**
* @return true if the session is active i.e. has not been cleared after a logout.
*/
public boolean isAlive() {
synchronized (this) {
return mIsAliveSession;
}
}
/**
* Get the content manager (for uploading and downloading content) associated with the session.
*
* @return the content manager
*/
public ContentManager getContentManager() {
checkIfAlive();
return mContentManager;
}
/**
* Get the session's current user. The MyUser object provides methods for updating user properties which are not possible for other users.
*
* @return the session's MyUser object
*/
public MyUser getMyUser() {
checkIfAlive();
return mDataHandler.getMyUser();
}
/**
* Get the session's current userid.
*
* @return the session's MyUser id
*/
public String getMyUserId() {
checkIfAlive();
if (null != mDataHandler.getMyUser()) {
return mDataHandler.getMyUser().user_id;
}
return null;
}
/**
* Start the event stream (events thread that listens for events) with an event listener.
*
* @param anEventsListener the event listener or null if using a DataHandler
* @param networkConnectivityReceiver the network connectivity listener.
* @param initialToken the initial sync token (null to start from scratch)
*/
public void startEventStream(final EventsThreadListener anEventsListener, final NetworkConnectivityReceiver networkConnectivityReceiver, final String initialToken) {
checkIfAlive();
if (mEventsThread != null) {
Log.e(LOG_TAG, "Ignoring startEventStream() : Thread already created.");
return;
}
if (mDataHandler == null) {
Log.e(LOG_TAG, "Error starting the event stream: No data handler is defined");
return;
}
Log.d(LOG_TAG, "startEventStream : create the event stream");
final EventsThreadListener fEventsListener = (null == anEventsListener) ? new DefaultEventsThreadListener(mDataHandler) : anEventsListener;
mEventsThread = new EventsThread(mEventsRestClient, fEventsListener, initialToken);
mEventsThread.setNetworkConnectivityReceiver(networkConnectivityReceiver);
if (mFailureCallback != null) {
mEventsThread.setFailureCallback(mFailureCallback);
}
if (mCredentials.accessToken != null && !mEventsThread.isAlive()) {
mEventsThread.start();
if (mIsCatchupPending) {
Log.d(LOG_TAG, "startEventStream : there was a pending catchup : the catchup will be triggered in 5 seconds");
mIsCatchupPending = false;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, "startEventStream : pause the stream");
pauseEventStream();
}
}, 5000);
}
}
}
/**
* Refresh the access token
*/
public void refreshToken() {
checkIfAlive();
mProfileRestClient.refreshTokens(new ApiCallback<Credentials>() {
@Override
public void onSuccess(Credentials info) {
Log.d(LOG_TAG, "refreshToken : succeeds.");
}
@Override
public void onNetworkError(Exception e) {
Log.d(LOG_TAG, "refreshToken : onNetworkError " + e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
Log.d(LOG_TAG, "refreshToken : onMatrixError " + e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
Log.d(LOG_TAG, "refreshToken : onMatrixError " + e.getLocalizedMessage());
}
});
}
/**
* Update the online status
* @param isOnline true if the client must be seen as online
*/
public void setIsOnline(boolean isOnline) {
if (isOnline != mIsOnline) {
mIsOnline = isOnline;
if (null != mEventsThread) {
mEventsThread.setIsOnline(isOnline);
}
}
}
/**
* Tell if the client is seen as "online"
*/
public boolean isOnline() {
return mIsOnline;
}
/**
* Update the heartbeat request timeout.
* @param ms the delay in ms
*/
public void setSyncTimeout(int ms) {
if (null != mEventsThread) {
mEventsThread.setServerLongPollTimeout(ms);
}
}
/**
* @return the heartbeat request timeout
*/
public int getSyncTimeout() {
if (null != mEventsThread) {
return mEventsThread.getServerLongPollTimeout();
}
return 0;
}
/**
* Set a delay between two sync requests.
* @param ms the delay in ms
*/
public void setSyncDelay(int ms) {
if (null != mEventsThread) {
mEventsThread.setSyncDelay(ms);
}
}
/**
* @return the delay between two sync requests.
*/
public int getSyncDelay() {
if (null != mEventsThread) {
mEventsThread.getSyncDelay();
}
return 0;
}
/**
* Shorthand for {@link #startEventStream(EventsThreadListener, NetworkConnectivityReceiver, String)} with no eventListener
* using a DataHandler and no specific failure callback.
*
* @param initialToken the initial sync token (null to sync from scratch).
*/
public void startEventStream(String initialToken) {
checkIfAlive();
startEventStream(null, this.mNetworkConnectivityReceiver, initialToken);
}
/**
* Gracefully stop the event stream.
*/
public void stopEventStream() {
if (null != mCallsManager) {
mCallsManager.stopTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "stopEventStream");
mEventsThread.kill();
mEventsThread = null;
} else {
Log.e(LOG_TAG, "stopEventStream : mEventsThread is already null");
}
}
/**
* Pause the event stream
*/
public void pauseEventStream() {
checkIfAlive();
if (null != mCallsManager) {
mCallsManager.pauseTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "pauseEventStream");
mEventsThread.pause();
} else {
Log.e(LOG_TAG, "pauseEventStream : mEventsThread is null");
}
if (null != mCrypto) {
mCrypto.pause();
}
}
/**
* Resume the event stream
*/
public void resumeEventStream() {
checkIfAlive();
if (null != mNetworkConnectivityReceiver) {
// mNetworkConnectivityReceiver is a broadcastReceiver
// but some users reported that the network updates wre not broadcasted.
mNetworkConnectivityReceiver.checkNetworkConnection(mAppContent);
}
if (null != mCallsManager) {
mCallsManager.unpauseTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "unpause");
mEventsThread.unpause();
} else {
Log.e(LOG_TAG, "resumeEventStream : mEventsThread is null");
}
if (null != mCrypto) {
mCrypto.resume();
}
}
/**
* Trigger a catchup
*/
public void catchupEventStream() {
checkIfAlive();
if (null != mEventsThread) {
Log.d(LOG_TAG, "catchupEventStream");
mEventsThread.catchup();
} else {
Log.e(LOG_TAG, "catchupEventStream : mEventsThread is null so catchup when the thread will be created");
mIsCatchupPending = true;
}
}
/**
* Set a global failure callback implementation.
*
* @param failureCallback the failure callback
*/
public void setFailureCallback(ApiFailureCallback failureCallback) {
checkIfAlive();
mFailureCallback = failureCallback;
if (mEventsThread != null) {
mEventsThread.setFailureCallback(failureCallback);
}
}
/**
* Create a direct message room with one participant.<br>
* The participant can be a user ID or mail address. Once the room is created, on success, the room
* is set as a "direct message" with the participant.
* @param aParticipantUserId user ID (or user mail) to be invited in the direct message room
* @param aCreateRoomCallBack async call back response
* @return true if the invite was performed, false otherwise
*/
public boolean createRoomDirectMessage(final String aParticipantUserId, final ApiCallback<String> aCreateRoomCallBack) {
boolean retCode = false;
if(!TextUtils.isEmpty(aParticipantUserId)) {
retCode = true;
HashMap<String, Object> params = new HashMap<>();
params.put("preset","trusted_private_chat");
params.put("is_direct", true);
if (android.util.Patterns.EMAIL_ADDRESS.matcher(aParticipantUserId).matches()) {
// retrieve the identity server
String identityServer = mHsConfig.getIdentityServerUri().toString();
if (identityServer.startsWith("http://")) {
identityServer = identityServer.substring("http://".length());
} else if (identityServer.startsWith("https://")) {
identityServer = identityServer.substring("https://".length());
}
// build the invite third party object
HashMap<String, String> parameters = new HashMap<>();
parameters.put("id_server", identityServer);
parameters.put("medium", "email");
parameters.put("address", aParticipantUserId);
params.put("invite_3pid", Arrays.asList(parameters));
} else {
if (!aParticipantUserId.equals(getMyUserId())) {
// send invite only if the participant ID is not the user ID
params.put("invite", Arrays.asList(aParticipantUserId));
}
}
createRoom(params, new ApiCallback<String>() {
@Override
public void onSuccess(String roomId) {
final Room room = getDataHandler().getRoom(roomId);
final String fRoomId = roomId;
toggleDirectChatRoom(roomId, aParticipantUserId, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onSuccess(fRoomId);
}
}
@Override
public void onNetworkError(Exception e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onUnexpectedError(e);
}
}
});
}
@Override
public void onNetworkError(Exception e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if(null != aCreateRoomCallBack) {
aCreateRoomCallBack.onUnexpectedError(e);
}
}
});
}
return retCode;
}
/**
* Create a new room.
*
* @param callback the async callback once the room is ready
*/
public void createRoom(final ApiCallback<String> callback) {
createRoom(null, null, null, callback);
}
/**
* Create a new room with given properties.
*
* @param params the creation parameters.
* @param callback the async callback once the room is ready
*/
public void createRoom(final Map<String, Object> params, final ApiCallback<String> callback) {
mRoomsRestClient.createRoom(params, new SimpleApiCallback<CreateRoomResponse>(callback) {
@Override
public void onSuccess(CreateRoomResponse info) {
final String roomId = info.roomId;
Room createdRoom = mDataHandler.getRoom(roomId);
// the creation events are not be called during the creation
if (createdRoom.getState().getMember(mCredentials.userId) == null) {
createdRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
/**
* Create a new room with given properties. Needs the data handler.
*
* @param name the room name
* @param topic the room topic
* @param alias the room alias
* @param callback the async callback once the room is ready
*/
public void createRoom(String name, String topic, String alias, final ApiCallback<String> callback) {
createRoom(name, topic, RoomState.DIRECTORY_VISIBILITY_PRIVATE, alias, RoomState.GUEST_ACCESS_CAN_JOIN, RoomState.HISTORY_VISIBILITY_SHARED, callback);
}
/**
* Create a new room with given properties. Needs the data handler.
*
* @param name the room name
* @param topic the room topic
* @param visibility the room visibility
* @param alias the room alias
* @param guestAccess the guest access rule (see {@link RoomState#GUEST_ACCESS_CAN_JOIN} or {@link RoomState#GUEST_ACCESS_FORBIDDEN})
* @param historyVisibility the history visibility
* @param callback the async callback once the room is ready
*/
public void createRoom(String name, String topic, String visibility, String alias, String guestAccess, String historyVisibility, final ApiCallback<String> callback) {
checkIfAlive();
mRoomsRestClient.createRoom(name, topic, visibility, alias, guestAccess, historyVisibility, new SimpleApiCallback<CreateRoomResponse>(callback) {
@Override
public void onSuccess(CreateRoomResponse info) {
final String roomId = info.roomId;
Room createdRoom = mDataHandler.getRoom(roomId);
// the creation events are not be called during the creation
if (createdRoom.getState().getMember(mCredentials.userId) == null) {
createdRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
/**
* Join a room by its roomAlias
*
* @param roomIdOrAlias the room alias
* @param callback the async callback once the room is joined. The RoomId is provided.
*/
public void joinRoom(String roomIdOrAlias, final ApiCallback<String> callback) {
checkIfAlive();
// sanity check
if ((null != mDataHandler) && (null != roomIdOrAlias)) {
mDataRetriever.getRoomsRestClient().joinRoom(roomIdOrAlias, new SimpleApiCallback<RoomResponse>(callback) {
@Override
public void onSuccess(final RoomResponse roomResponse) {
final String roomId = roomResponse.roomId;
Room joinedRoom = mDataHandler.getRoom(roomId);
RoomMember member = joinedRoom.getState().getMember(mCredentials.userId);
String state = (null != member) ? member.membership : null;
// wait until the initial sync is done
if ((state == null) || TextUtils.equals(state, RoomMember.MEMBERSHIP_INVITE)) {
joinedRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
}
/**
* Retrieve user matrix id from a 3rd party id.
*
* @param address the user id.
* @param media the media.
* @param callback the 3rd party callback
*/
public void lookup3Pid(String address, String media, final ApiCallback<String> callback) {
checkIfAlive();
mThirdPidRestClient.lookup3Pid(address, media, callback);
}
/**
* Retrieve user matrix id from a 3rd party id.
*
* @param addresses 3rd party ids
* @param mediums the medias.
* @param callback the 3rd parties callback
*/
public void lookup3Pids(ArrayList<String> addresses, ArrayList<String> mediums, ApiCallback<ArrayList<String>> callback) {
checkIfAlive();
mThirdPidRestClient.lookup3Pids(addresses, mediums, callback);
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param beforeLimit the number of events to get before the matching results.
* @param afterLimit the number of events to get after the matching results.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessageText(String text, List<String> rooms, int beforeLimit, int afterLimit, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, rooms, beforeLimit, afterLimit, nextBatch, callback);
}
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessagesByText(String text, List<String> rooms, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, rooms, 0, 0, nextBatch, callback);
}
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessagesByText(String text, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, null, 0, 0, nextBatch, callback);
}
}
/**
* Cancel any pending search request
*/
public void cancelSearchMessagesByText() {
checkIfAlive();
mEventsRestClient.cancelSearchMessagesByText();
}
/**
* Perform a remote text search for a dedicated media types list
*
* @param name the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMediasByName(String name, List<String> rooms, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMediasByText(name, rooms, 0, 0, nextBatch, callback);
}
}
/**
* Cancel any pending file search request
*/
public void cancelSearchMediasByText() {
checkIfAlive();
mEventsRestClient.cancelSearchMediasByText();
}
/**
* Return the fulfilled active BingRule for the event.
*
* @param event the event
* @return the fulfilled bingRule
*/
public BingRule fulfillRule(Event event) {
checkIfAlive();
return mBingRulesManager.fulfilledBingRule(event);
}
/**
* @return true if the calls are supported
*/
public boolean isVoipCallSupported() {
if (null != mCallsManager) {
return mCallsManager.isSupported();
} else {
return false;
}
}
/**
* Get the list of rooms that are tagged the specified tag.
* The returned array is ordered according to the room tag order.
*
* @param tag RoomTag.ROOM_TAG_XXX values
* @return the rooms list.
*/
public List<Room> roomsWithTag(final String tag) {
ArrayList<Room> taggedRooms = new ArrayList<>();
if (!TextUtils.equals(tag, RoomTag.ROOM_TAG_NO_TAG)) {
Collection<Room> rooms = mDataHandler.getStore().getRooms();
for (Room room : rooms) {
if (null != room.getAccountData().roomTag(tag)) {
taggedRooms.add(room);
}
}
if (taggedRooms.size() > 0) {
Collections.sort(taggedRooms, new Comparator<Room>() {
@Override
public int compare(Room r1, Room r2) {
int res = 0;
RoomTag tag1 = r1.getAccountData().roomTag(tag);
RoomTag tag2 = r2.getAccountData().roomTag(tag);
if ((null != tag1.mOrder) && (null != tag2.mOrder)) {
double diff = (tag1.mOrder - tag2.mOrder);
res = (diff == 0) ? 0 : (diff > 0) ? +1 : -1;
} else if (null != tag1.mOrder) {
res = -1;
} else if (null != tag2.mOrder) {
res = +1;
}
// In case of same order, order rooms by their last event
if (0 == res) {
IMXStore store = mDataHandler.getStore();
Event latestEvent1 = store.getLatestEvent(r1.getRoomId());
Event latestEvent2 = store.getLatestEvent(r2.getRoomId());
// sanity check
if ((null != latestEvent2) && (null != latestEvent1)) {
long diff = (latestEvent2.getOriginServerTs() - latestEvent1.getOriginServerTs());
res = (diff == 0) ? 0 : (diff > 0) ? +1 : -1;
}
}
return res;
}
});
}
} else {
Collection<Room> rooms = mDataHandler.getStore().getRooms();
for (Room room : rooms) {
if (!room.getAccountData().hasTags()) {
taggedRooms.add(room);
}
}
}
return taggedRooms;
}
/**
* Get the list of roomIds that are tagged the specified tag.
* The returned array is ordered according to the room tag order.
*
* @param tag RoomTag.ROOM_TAG_XXX values
* @return the room IDs list.
*/
public List<String> roomIdsWithTag(final String tag) {
List<Room> roomsWithTag = roomsWithTag(tag);
ArrayList<String> roomIdsList = new ArrayList<>();
for (Room room : roomsWithTag) {
roomIdsList.add(room.getRoomId());
}
return roomIdsList;
}
/**
* Compute the tag order to use for a room tag so that the room will appear in the expected position
* in the list of rooms stamped with this tag.
*
* @param index the targeted index of the room in the list of rooms with the tag `tag`.
* @param originIndex the origin index. Integer.MAX_VALUE if there is none.
* @param tag the tag
* @return the tag order to apply to get the expected position.
*/
public Double tagOrderToBeAtIndex(int index, int originIndex, String tag) {
// Algo (and the [0.0, 1.0] assumption) inspired from matrix-react-sdk:
// We sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
// For convenience, we calculate this for now a floating point number between 0.0 and 1.0.
Double orderA = 0.0; // by default we're next to the beginning of the list
Double orderB = 1.0; // by default we're next to the end of the list too
List<Room> roomsWithTag = roomsWithTag(tag);
if (roomsWithTag.size() > 0) {
// when an object is moved down, the index must be incremented
// because the object will be removed from the list to be inserted after its destination
if ((originIndex != Integer.MAX_VALUE) && (originIndex < index)) {
index++;
}
if (index > 0) {
// Bound max index to the array size
int prevIndex = (index < roomsWithTag.size()) ? index : roomsWithTag.size();
RoomTag prevTag = roomsWithTag.get(prevIndex - 1).getAccountData().roomTag(tag);
if (null == prevTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Previous room in sublist has no ordering metadata. This should never happen.");
} else {
orderA = prevTag.mOrder;
}
}
if (index <= roomsWithTag.size() - 1) {
RoomTag nextTag = roomsWithTag.get(index).getAccountData().roomTag(tag);
if (null == nextTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Next room in sublist has no ordering metadata. This should never happen.");
} else {
orderB = nextTag.mOrder;
}
}
}
return (orderA + orderB) / 2.0;
}
/**
* @return the direct chat room ids list
*/
public List<String> getDirectChatRoomIdsList() {
IMXStore store = getDataHandler().getStore();
ArrayList<String> directChatRoomIdsList = new ArrayList<>();
Collection<List<String>> listOfList = null;
if (null != store.getDirectChatRoomsDict()) {
listOfList = store.getDirectChatRoomsDict().values();
}
// if the direct messages entry has been defined
if (null != listOfList) {
for (List<String> list : listOfList) {
for (String roomId : list) {
// test if the room is defined once and exists
if ((directChatRoomIdsList.indexOf(roomId) < 0) && (null != store.getRoom(roomId))) {
directChatRoomIdsList.add(roomId);
}
}
}
} else {
// background compatibility heuristic (named looksLikeDirectMessageRoom in the JS)
ArrayList<Room> rooms = new ArrayList<>(store.getRooms());
for (Room r : rooms) {
// Show 1:1 chats in separate "Direct Messages" section as long as they haven't
// been moved to a different tag section
if ((r.getMembers().size() == 2) && (null != r.getAccountData()) && (!r.getAccountData().hasTags())) {
RoomMember roomMember = r.getMember(getMyUserId());
if (null != roomMember) {
String membership = roomMember.membership;
if (TextUtils.equals(membership, RoomMember.MEMBERSHIP_JOIN) ||
TextUtils.equals(membership, RoomMember.MEMBERSHIP_BAN) ||
TextUtils.equals(membership, RoomMember.MEMBERSHIP_LEAVE)) {
directChatRoomIdsList.add(r.getRoomId());
}
}
}
}
}
return directChatRoomIdsList;
}
/**
* Return the list of the direct chat room IDs for the user given in parameter.<br>
* Based on the account_data map content, the entry associated with aSearchedUserId is returned.
* @param aSearchedUserId user ID
* @return the list of the direct chat room Id
*/
public List<String> getDirectChatRoomIdsList(String aSearchedUserId) {
ArrayList<String> directChatRoomIdsList = new ArrayList<>();
IMXStore store = getDataHandler().getStore();
Room room;
HashMap<String, List<String>> params;
if(null != store.getDirectChatRoomsDict()) {
params = new HashMap<>(store.getDirectChatRoomsDict());
if (params.containsKey(aSearchedUserId)) {
directChatRoomIdsList = new ArrayList<>();
for(String roomId: params.get(aSearchedUserId)) {
room = store.getRoom(roomId);
if(null != room) { // skipp empty rooms
directChatRoomIdsList.add(roomId);
}
}
} else {
Log.w(LOG_TAG,"## getDirectChatRoomIdsList(): UserId "+aSearchedUserId+" has no entry in account_data");
}
} else {
Log.w(LOG_TAG,"## getDirectChatRoomIdsList(): failure - getDirectChatRoomsDict()=null");
}
return directChatRoomIdsList;
}
/**
* Toggles the direct chat status of a room.<br>
* Create a new direct chat room in the account data section if the room does not exist,
* otherwise the room is removed from the account data section.
* Direct chat room user ID choice algorithm:<br>
* 1- oldest joined room member
* 2- oldest invited room member
* 3- the user himself
* @param roomId the room roomId
* @param callback the asynchronous callback
*/
public void toggleDirectChatRoom(String roomId, String aParticipantUserId, ApiCallback<Void> callback) {
IMXStore store = getDataHandler().getStore();
Room room = store.getRoom(roomId);
if (null != room) {
HashMap<String, List<String>> params;
if (null != store.getDirectChatRoomsDict()) {
params = new HashMap<>(store.getDirectChatRoomsDict());
} else {
params = new HashMap<>();
}
// if the room was not yet seen as direct chat
if (getDirectChatRoomIdsList().indexOf(roomId) < 0) {
ArrayList<String> roomIdsList = new ArrayList<>();
RoomMember directChatMember = null;
String chosenUserId;
if(null == aParticipantUserId) {
ArrayList<RoomMember> members = new ArrayList<>(room.getActiveMembers());
if(members.size()>1) {
// sort algo: oldest join first, then oldest invited
Collections.sort(members, new Comparator<RoomMember>() {
@Override
public int compare(RoomMember r1, RoomMember r2) {
int res;
long diff;
if (RoomMember.MEMBERSHIP_JOIN.equals(r2.membership) && RoomMember.MEMBERSHIP_INVITE.equals(r1.membership)) {
res = 1;
} else if (r2.membership.equals(r1.membership)) {
diff = r1.getOriginServerTs() - r2.getOriginServerTs();
res = (0 == diff) ? 0 : ((diff > 0) ? 1 : -1);
} else {
res = -1;
}
return res;
}
});
int nextIndexSearch = 0;
// take the oldest join member
if (!TextUtils.equals(members.get(0).getUserId(), getMyUserId())) {
if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(0).membership)) {
directChatMember = members.get(0);
}
} else {
nextIndexSearch = 1;
if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(1).membership)) {
directChatMember = members.get(1);
}
}
// no join member found, test the oldest join member
if (null == directChatMember) {
if (RoomMember.MEMBERSHIP_INVITE.equals(members.get(nextIndexSearch).membership)) {
directChatMember = members.get(nextIndexSearch);
}
}
}
// last option: get the logged user
if (null == directChatMember) {
directChatMember = members.get(0);
}
chosenUserId = directChatMember.getUserId();
} else {
chosenUserId = aParticipantUserId;
}
// search if there is an entry with the same user
if (params.containsKey(chosenUserId)) {
roomIdsList = new ArrayList<>(params.get(chosenUserId));
}
roomIdsList.add(roomId); // update room list with the new room
params.put(chosenUserId, roomIdsList);
} else {
// remove the current room from the direct chat list rooms
if (null != store.getDirectChatRoomsDict()) {
Collection<List<String>> listOfList = store.getDirectChatRoomsDict().values();
for (List<String> list : listOfList) {
if (list.contains(roomId)) {
list.remove(roomId);
}
}
} else {
// should not happen: if the room has to be removed, it means the room has been
// previously detected as being part of the listOfList
Log.e(LOG_TAG, "## toggleDirectChatRoom(): failed to remove a direct chat room (not seen as direct chat room)");
return;
}
}
HashMap<String, Object> requestParams = new HashMap<>();
Collection<String> userIds = params.keySet();
for(String userId : userIds) {
requestParams.put(userId, params.get(userId));
}
mAccountDataRestClient.setAccountData(getMyUserId(), AccountDataRestClient.ACCOUNT_DATA_TYPE_DIRECT_MESSAGES, requestParams, callback);
}
}
/**
* Update the account password
*
* @param oldPassword the former account password
* @param newPassword the new account password
* @param callback the callback
*/
public void updatePassword(String oldPassword, String newPassword, ApiCallback<Void> callback) {
mProfileRestClient.updatePassword(getMyUserId(), oldPassword, newPassword, callback);
}
/**
* Reset the password to a new one.
*
* @param newPassword the new password
* @param threepid_creds the three pids.
* @param callback the callback
*/
public void resetPassword(final String newPassword, final Map<String, String> threepid_creds, final ApiCallback<Void> callback) {
mProfileRestClient.resetPassword(newPassword, threepid_creds, callback);
}
/**
* Triggers a request to update the userId to ignore
* @param userIds the userIds to ignoer
* @param callback the callback
*/
private void updateUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
HashMap<String, Object> ignoredUsersDict = new HashMap<>();
for (String userId : userIds) {
ignoredUsersDict.put(userId, new ArrayList<>());
}
HashMap<String, Object> params = new HashMap<>();
params.put(AccountDataRestClient.ACCOUNT_DATA_KEY_IGNORED_USERS, ignoredUsersDict);
mAccountDataRestClient.setAccountData(getMyUserId(), AccountDataRestClient.ACCOUNT_DATA_TYPE_IGNORED_USER_LIST, params, callback);
}
/**
* Tells if an user is in the ignored user ids list
* @param userId the user id to test
* @return true if the user is ignored
*/
public boolean isUserIgnored(String userId) {
if (null != userId) {
return getDataHandler().getIgnoredUserIds().indexOf(userId) >= 0;
}
return false;
}
/**
* Ignore a list of users.
* @param userIds the user ids list to ignore
* @param callback the result callback
*/
public void ignoreUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
List<String> curUserIdsToIgnore = getDataHandler().getIgnoredUserIds();
ArrayList<String> userIdsToIgnore = new ArrayList<>(getDataHandler().getIgnoredUserIds());
// something to add
if ((null != userIds) && (userIds.size() > 0)) {
// add the new one
for (String userId : userIds) {
if (userIdsToIgnore.indexOf(userId) < 0) {
userIdsToIgnore.add(userId);
}
}
// some items have been added
if (curUserIdsToIgnore.size() != userIdsToIgnore.size()) {
updateUsers(userIdsToIgnore, callback);
}
}
}
/**
* Unignore a list of users.
* @param userIds the user ids list to unignore
* @param callback the result callback
*/
public void unIgnoreUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
List<String> curUserIdsToIgnore = getDataHandler().getIgnoredUserIds();
ArrayList<String> userIdsToIgnore = new ArrayList<>(getDataHandler().getIgnoredUserIds());
// something to add
if ((null != userIds) && (userIds.size() > 0)) {
// add the new one
for (String userId : userIds) {
userIdsToIgnore.remove(userId);
}
// some items have been added
if (curUserIdsToIgnore.size() != userIdsToIgnore.size()) {
updateUsers(userIdsToIgnore, callback);
}
}
}
/**
* @return the network receiver.
*/
public NetworkConnectivityReceiver getNetworkConnectivityReceiver() {
return mNetworkConnectivityReceiver;
}
/**
* Invalidate the access token, so that it can no longer be used for authorization.
* @param context the application context
* @param callback the callback success and failure callback
*/
public void logout(final Context context, final ApiCallback<Void> callback) {
// Clear crypto data
// For security and because it will be no more useful as we will get a new device id
// on the next log in
enableCrypto(false, null);
mLoginRestClient.logout(new ApiCallback<JsonObject>() {
@Override
public void onSuccess(JsonObject info) {
clear(context);
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
clear(context);
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
clear(context);
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
clear(context);
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
//==============================================================================================================
// Crypto
//==============================================================================================================
/**
* The module that manages E2E encryption.
* Null if the feature is not enabled
*/
private MXCrypto mCrypto;
/**
* @return the crypto instance
*/
public MXCrypto getCrypto() {
return mCrypto;
}
/**
* @return true if the crypto is enabled
*/
public boolean isCryptoEnabled() {
return null != mCrypto;
}
/**
* enable encryption by default when launching the session
*/
private boolean mEnableCryptoWhenStartingMXSession = false;
/**
* Enable the crypto when initializing a new session.
*/
public void enableCryptoWhenStarting() {
mEnableCryptoWhenStartingMXSession = true;
}
/**
* When the encryption is toogled, the room summaries must be updated
* to display the right messages.
*/
private void decryptRoomSummaries() {
Collection<RoomSummary> summaries = getDataHandler().getStore().getSummaries();
for(RoomSummary summary :summaries) {
mDataHandler.decryptEvent(summary.getLatestReceivedEvent());
}
}
/**
* Enable / disable the crypto
* @param cryptoEnabled true to enable the crypto
*/
public void enableCrypto(boolean cryptoEnabled, final ApiCallback<Void> callback) {
if (cryptoEnabled != isCryptoEnabled()) {
if (cryptoEnabled) {
Log.d(LOG_TAG, "Crypto is enabled");
MXFileCryptoStore fileCryptoStore = new MXFileCryptoStore();
fileCryptoStore.initWithCredentials(mAppContent, mCredentials);
fileCryptoStore.open();
mCrypto = new MXCrypto(this, fileCryptoStore);
mCrypto.start(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
decryptRoomSummaries();
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} else if (null != mCrypto) {
Log.d(LOG_TAG, "Crypto is disabled");
IMXCryptoStore store = mCrypto.mCryptoStore;
mCrypto.close();
store.deleteStore();
mCrypto = null;
mDataHandler.setCrypto(null);
decryptRoomSummaries();
if (null != callback) {
callback.onSuccess(null);
}
}
mDataHandler.setCrypto(mCrypto);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Retrieves the devices list
* @param callback the asynchronous callback
*/
public void getDevicesList(ApiCallback<DevicesListResponse> callback) {
mCryptoRestClient.getDevices(callback);
}
/**
* Delete a device
* @param deviceId the device id
* @param password the passwoerd
* @param callback the asynchronous callback.
*/
public void deleteDevice(final String deviceId, final String password, final ApiCallback<Void> callback) {
DeleteDeviceParams dummyparams = new DeleteDeviceParams();
mCryptoRestClient.deleteDevice(deviceId, dummyparams, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// should never happen
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError matrixError) {
Log.d(LOG_TAG, "## checkNameAvailability(): The registration continues");
RegistrationFlowResponse registrationFlowResponse = null;
// expected status code is 401
if ((null != matrixError.mStatus) && (matrixError.mStatus == 401)) {
try {
registrationFlowResponse = JsonUtils.toRegistrationFlowResponse(matrixError.mErrorBodyAsString);
} catch (Exception castExcept) {
Log.e(LOG_TAG, "## deleteDevice(): Received status 401 - Exception - JsonUtils.toRegistrationFlowResponse()");
}
} else {
Log.d(LOG_TAG, "## deleteDevice(): Received not expected status 401 ="+ matrixError.mStatus);
}
// check if the server response can be casted
if (null != registrationFlowResponse) {
DeleteDeviceParams params = new DeleteDeviceParams();
params.auth = new DeleteDeviceAuth();
params.auth.session = registrationFlowResponse.session;
params.auth.type = "m.login.password";
params.auth.user = mCredentials.userId;
params.auth.password = password;
mCryptoRestClient.deleteDevice(deviceId, params, callback);
} else {
if (null != callback) {
callback.onMatrixError(matrixError);
}
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
});
}
}
|
matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java
|
/*
* Copyright 2014 OpenMarket 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.matrix.androidsdk;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.JsonObject;
import org.matrix.androidsdk.call.MXCallsManager;
import org.matrix.androidsdk.crypto.MXCrypto;
import org.matrix.androidsdk.crypto.MXCryptoError;
import org.matrix.androidsdk.data.DataRetriever;
import org.matrix.androidsdk.data.RoomSummary;
import org.matrix.androidsdk.data.cryptostore.IMXCryptoStore;
import org.matrix.androidsdk.data.store.IMXStore;
import org.matrix.androidsdk.data.cryptostore.MXFileCryptoStore;
import org.matrix.androidsdk.data.MyUser;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.db.MXLatestChatMessageCache;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.network.NetworkConnectivityReceiver;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.ApiFailureCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.client.AccountDataRestClient;
import org.matrix.androidsdk.rest.client.BingRulesRestClient;
import org.matrix.androidsdk.rest.client.CallRestClient;
import org.matrix.androidsdk.rest.client.CryptoRestClient;
import org.matrix.androidsdk.rest.client.EventsRestClient;
import org.matrix.androidsdk.rest.client.LoginRestClient;
import org.matrix.androidsdk.rest.client.PresenceRestClient;
import org.matrix.androidsdk.rest.client.ProfileRestClient;
import org.matrix.androidsdk.rest.client.PushersRestClient;
import org.matrix.androidsdk.rest.client.RoomsRestClient;
import org.matrix.androidsdk.rest.client.ThirdPidRestClient;
import org.matrix.androidsdk.rest.model.CreateRoomResponse;
import org.matrix.androidsdk.rest.model.DeleteDeviceAuth;
import org.matrix.androidsdk.rest.model.DeleteDeviceParams;
import org.matrix.androidsdk.rest.model.DevicesListResponse;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.rest.model.RoomResponse;
import org.matrix.androidsdk.rest.model.Search.SearchResponse;
import org.matrix.androidsdk.rest.model.User;
import org.matrix.androidsdk.rest.model.bingrules.BingRule;
import org.matrix.androidsdk.rest.model.login.Credentials;
import org.matrix.androidsdk.rest.model.login.RegistrationFlowResponse;
import org.matrix.androidsdk.sync.DefaultEventsThreadListener;
import org.matrix.androidsdk.sync.EventsThread;
import org.matrix.androidsdk.sync.EventsThreadListener;
import org.matrix.androidsdk.util.BingRulesManager;
import org.matrix.androidsdk.util.ContentManager;
import org.matrix.androidsdk.util.JsonUtils;
import org.matrix.androidsdk.util.UnsentEventsManager;
import org.matrix.olm.OlmManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Class that represents one user's session with a particular home server.
* There can potentially be multiple sessions for handling multiple accounts.
*/
public class MXSession {
private static final String LOG_TAG = "MXSession";
private DataRetriever mDataRetriever;
private MXDataHandler mDataHandler;
private EventsThread mEventsThread;
private Credentials mCredentials;
// Api clients
private EventsRestClient mEventsRestClient;
private ProfileRestClient mProfileRestClient;
private PresenceRestClient mPresenceRestClient;
private RoomsRestClient mRoomsRestClient;
private BingRulesRestClient mBingRulesRestClient;
private PushersRestClient mPushersRestClient;
private ThirdPidRestClient mThirdPidRestClient;
private CallRestClient mCallRestClient;
private AccountDataRestClient mAccountDataRestClient;
private CryptoRestClient mCryptoRestClient;
private LoginRestClient mLoginRestClient;
private ApiFailureCallback mFailureCallback;
private ContentManager mContentManager;
public MXCallsManager mCallsManager;
private Context mAppContent;
private NetworkConnectivityReceiver mNetworkConnectivityReceiver;
private UnsentEventsManager mUnsentEventsManager;
private MXLatestChatMessageCache mLatestChatMessageCache;
private MXMediasCache mMediasCache;
private BingRulesManager mBingRulesManager = null;
private boolean mIsAliveSession = true;
// online status
private boolean mIsOnline = true;
private HomeserverConnectionConfig mHsConfig;
// the application is launched from a notification
// so, mEventsThread.start might be not ready
private boolean mIsCatchupPending = false;
// load the crypto libs.
public static OlmManager mOlmManager = new OlmManager(android.os.Build.VERSION.SDK_INT < 23);
// regex pattern to find matrix user ids in a string.
public static final String MATRIX_USER_IDENTIFIER_REGEX = "@[A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_USER_IDENTIFIER = Pattern.compile(MATRIX_USER_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find room aliases in a string.
public static final String MATRIX_ROOM_ALIAS_REGEX = "#[A-Z0-9._%+-\\\\#]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_ALIAS = Pattern.compile(MATRIX_ROOM_ALIAS_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find room ids in a string.
public static final String MATRIX_ROOM_IDENTIFIER_REGEX = "![A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_ROOM_IDENTIFIER = Pattern.compile(MATRIX_ROOM_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find message ids in a string.
public static final String MATRIX_MESSAGE_IDENTIFIER_REGEX = "\\$[A-Z0-9]+:[A-Z0-9.-]+\\.[A-Z]{2,}";
public static final Pattern PATTERN_CONTAIN_MATRIX_MESSAGE_IDENTIFIER = Pattern.compile(MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
// regex pattern to find permalink with message id.
// Android does not support in URL so extract it.
public static final Pattern PATTERN_CONTAIN_MATRIX_TO_PERMALINK_ROOM_ID = Pattern.compile("https:\\/\\/matrix\\.to\\/#\\/"+ MATRIX_ROOM_IDENTIFIER_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_MATRIX_TO_PERMALINK_ROOM_ALIAS = Pattern.compile("https:\\/\\/matrix\\.to\\/#\\/"+ MATRIX_ROOM_ALIAS_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_APP_LINK_PERMALINK_ROOM_ID = Pattern.compile("https:\\/\\/[A-Z0-9.-]+\\.[A-Z]{2,}\\/[A-Z]{3,}\\/#\\/room\\/"+ MATRIX_ROOM_IDENTIFIER_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_CONTAIN_APP_LINK_PERMALINK_ROOM_ALIAS = Pattern.compile("https:\\/\\/[A-Z0-9.-]+\\.[A-Z]{2,}\\/[A-Z]{3,}\\/#\\/room\\/"+ MATRIX_ROOM_ALIAS_REGEX +"\\/" + MATRIX_MESSAGE_IDENTIFIER_REGEX, Pattern.CASE_INSENSITIVE);
/**
* Create a basic session for direct API calls.
*
* @param hsConfig the home server connection config
*/
public MXSession(HomeserverConnectionConfig hsConfig) {
mCredentials = hsConfig.getCredentials();
mHsConfig = hsConfig;
mEventsRestClient = new EventsRestClient(hsConfig);
mProfileRestClient = new ProfileRestClient(hsConfig);
mPresenceRestClient = new PresenceRestClient(hsConfig);
mRoomsRestClient = new RoomsRestClient(hsConfig);
mBingRulesRestClient = new BingRulesRestClient(hsConfig);
mPushersRestClient = new PushersRestClient(hsConfig);
mThirdPidRestClient = new ThirdPidRestClient(hsConfig);
mCallRestClient = new CallRestClient(hsConfig);
mAccountDataRestClient = new AccountDataRestClient(hsConfig);
mCryptoRestClient = new CryptoRestClient(hsConfig);
mLoginRestClient = new LoginRestClient(hsConfig);
}
/**
* Create a user session with a data handler.
*
* @param hsConfig the home server connection config
* @param dataHandler the data handler
* @param appContext the application context
*/
public MXSession(HomeserverConnectionConfig hsConfig, MXDataHandler dataHandler, Context appContext) {
this(hsConfig);
mDataHandler = dataHandler;
mDataHandler.getStore().addMXStoreListener(new IMXStore.MXStoreListener() {
@Override
public void postProcess(String accountId) {
MXFileCryptoStore store = new MXFileCryptoStore();
store.initWithCredentials(mAppContent, mCredentials);
if (store.hasData() || mEnableCryptoWhenStartingMXSession) {
// open the store
store.open();
// enable
mCrypto = new MXCrypto(MXSession.this, store);
mDataHandler.setCrypto(mCrypto);
// the room summaries are not stored with decrypted content
decryptRoomSummaries();
}
}
@Override
public void onStoreReady(String accountId) {
}
@Override
public void onStoreCorrupted(String accountId, String description) {
}
@Override
public void onStoreOOM(String accountId, String description) {
}
});
// Initialize a data retriever with rest clients
mDataRetriever = new DataRetriever();
mDataRetriever.setRoomsRestClient(mRoomsRestClient);
mDataHandler.setDataRetriever(mDataRetriever);
mDataHandler.setProfileRestClient(mProfileRestClient);
mDataHandler.setPresenceRestClient(mPresenceRestClient);
mDataHandler.setThirdPidRestClient(mThirdPidRestClient);
mDataHandler.setRoomsRestClient(mRoomsRestClient);
// application context
mAppContent = appContext;
mNetworkConnectivityReceiver = new NetworkConnectivityReceiver();
mNetworkConnectivityReceiver.checkNetworkConnection(appContext);
mDataHandler.setNetworkConnectivityReceiver(mNetworkConnectivityReceiver);
mAppContent.registerReceiver(mNetworkConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mBingRulesManager = new BingRulesManager(this, mNetworkConnectivityReceiver);
mDataHandler.setPushRulesManager(mBingRulesManager);
mUnsentEventsManager = new UnsentEventsManager(mNetworkConnectivityReceiver, mDataHandler);
mContentManager = new ContentManager(hsConfig, mUnsentEventsManager);
//
mCallsManager = new MXCallsManager(this, mAppContent);
mDataHandler.setCallsManager(mCallsManager);
// the rest client
mEventsRestClient.setUnsentEventsManager(mUnsentEventsManager);
mProfileRestClient.setUnsentEventsManager(mUnsentEventsManager);
mPresenceRestClient.setUnsentEventsManager(mUnsentEventsManager);
mRoomsRestClient.setUnsentEventsManager(mUnsentEventsManager);
mBingRulesRestClient.setUnsentEventsManager(mUnsentEventsManager);
mThirdPidRestClient.setUnsentEventsManager(mUnsentEventsManager);
mCallRestClient.setUnsentEventsManager(mUnsentEventsManager);
mAccountDataRestClient.setUnsentEventsManager(mUnsentEventsManager);
mCryptoRestClient.setUnsentEventsManager(mUnsentEventsManager);
mLoginRestClient.setUnsentEventsManager(mUnsentEventsManager);
// return the default cache manager
mLatestChatMessageCache = new MXLatestChatMessageCache(mCredentials.userId);
mMediasCache = new MXMediasCache(mContentManager, mCredentials.userId, appContext);
mDataHandler.setMediasCache(mMediasCache);
}
private void checkIfAlive() {
synchronized (this) {
if (!mIsAliveSession) {
Log.e(LOG_TAG, "Use of a release session");
//throw new AssertionError("Should not used a cleared mxsession ");
}
}
}
/**
* @return the SDK version.
*/
public String getVersion(boolean longFormat) {
checkIfAlive();
String versionName = BuildConfig.VERSION_NAME;
if (!TextUtils.isEmpty(versionName)) {
String gitVersion = mAppContent.getResources().getString(R.string.git_sdk_revision);
if (longFormat) {
String date = mAppContent.getResources().getString(R.string.git_sdk_revision_date);
versionName += " (" + gitVersion + "-" + date + ")";
} else {
versionName += " (" + gitVersion + ")";
}
}
return versionName;
}
/**
* @return the crypto lib version
*/
public String getCryptoVersion() {
if (null != mOlmManager) {
return mOlmManager.getOlmLibVersion();
}
return "";
}
/**
* Get the data handler.
*
* @return the data handler.
*/
public MXDataHandler getDataHandler() {
checkIfAlive();
return mDataHandler;
}
/**
* Get the user credentials.
*
* @return the credentials
*/
public Credentials getCredentials() {
checkIfAlive();
return mCredentials;
}
/**
* Get the API client for requests to the events API.
*
* @return the events API client
*/
public EventsRestClient getEventsApiClient() {
checkIfAlive();
return mEventsRestClient;
}
/**
* Get the API client for requests to the profile API.
*
* @return the profile API client
*/
public ProfileRestClient getProfileApiClient() {
checkIfAlive();
return mProfileRestClient;
}
/**
* Get the API client for requests to the presence API.
*
* @return the presence API client
*/
public PresenceRestClient getPresenceApiClient() {
checkIfAlive();
return mPresenceRestClient;
}
/**
* Refresh the presence info of a dedicated user.
*
* @param userId the user userID.
* @param callback the callback.
*/
public void refreshUserPresence(final String userId, final ApiCallback<Void> callback) {
mPresenceRestClient.getPresence(userId, new ApiCallback<User>() {
@Override
public void onSuccess(User user) {
User currentUser = mDataHandler.getStore().getUser(userId);
if (null != currentUser) {
currentUser.presence = user.presence;
currentUser.currently_active = user.currently_active;
currentUser.lastActiveAgo = user.lastActiveAgo;
} else {
currentUser = user;
}
currentUser.setLatestPresenceTs(System.currentTimeMillis());
mDataHandler.getStore().storeUser(currentUser);
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Get the API client for requests to the bing rules API.
*
* @return the bing rules API client
*/
public BingRulesRestClient getBingRulesApiClient() {
checkIfAlive();
return mBingRulesRestClient;
}
public CallRestClient getCallRestClient() {
checkIfAlive();
return mCallRestClient;
}
public PushersRestClient getPushersRestClient() {
checkIfAlive();
return mPushersRestClient;
}
public CryptoRestClient getCryptoRestClient() {
checkIfAlive();
return mCryptoRestClient;
}
public HomeserverConnectionConfig getHomeserverConfig() {
checkIfAlive();
return mHsConfig;
}
/**
* Get the API client for requests to the rooms API.
*
* @return the rooms API client
*/
public RoomsRestClient getRoomsApiClient() {
checkIfAlive();
return mRoomsRestClient;
}
protected void setEventsApiClient(EventsRestClient eventsRestClient) {
checkIfAlive();
this.mEventsRestClient = eventsRestClient;
}
protected void setProfileApiClient(ProfileRestClient profileRestClient) {
checkIfAlive();
this.mProfileRestClient = profileRestClient;
}
protected void setPresenceApiClient(PresenceRestClient presenceRestClient) {
checkIfAlive();
this.mPresenceRestClient = presenceRestClient;
}
protected void setRoomsApiClient(RoomsRestClient roomsRestClient) {
checkIfAlive();
this.mRoomsRestClient = roomsRestClient;
}
public MXLatestChatMessageCache getLatestChatMessageCache() {
checkIfAlive();
return mLatestChatMessageCache;
}
public MXMediasCache getMediasCache() {
checkIfAlive();
return mMediasCache;
}
/**
* Clear the session data
*/
public void clear(Context context) {
checkIfAlive();
synchronized (this) {
mIsAliveSession = false;
}
// stop events stream
stopEventStream();
// cancel any listener
mDataHandler.clear();
// network event will not be listened anymore
mAppContent.unregisterReceiver(mNetworkConnectivityReceiver);
mNetworkConnectivityReceiver.removeListeners();
// auto resent messages will not be resent
mUnsentEventsManager.clear();
mLatestChatMessageCache.clearCache(context);
mMediasCache.clear();
if (null != mCrypto) {
mCrypto.close();
}
}
/**
* @return true if the session is active i.e. has not been cleared after a logout.
*/
public boolean isAlive() {
synchronized (this) {
return mIsAliveSession;
}
}
/**
* Get the content manager (for uploading and downloading content) associated with the session.
*
* @return the content manager
*/
public ContentManager getContentManager() {
checkIfAlive();
return mContentManager;
}
/**
* Get the session's current user. The MyUser object provides methods for updating user properties which are not possible for other users.
*
* @return the session's MyUser object
*/
public MyUser getMyUser() {
checkIfAlive();
return mDataHandler.getMyUser();
}
/**
* Get the session's current userid.
*
* @return the session's MyUser id
*/
public String getMyUserId() {
checkIfAlive();
if (null != mDataHandler.getMyUser()) {
return mDataHandler.getMyUser().user_id;
}
return null;
}
/**
* Start the event stream (events thread that listens for events) with an event listener.
*
* @param anEventsListener the event listener or null if using a DataHandler
* @param networkConnectivityReceiver the network connectivity listener.
* @param initialToken the initial sync token (null to start from scratch)
*/
public void startEventStream(final EventsThreadListener anEventsListener, final NetworkConnectivityReceiver networkConnectivityReceiver, final String initialToken) {
checkIfAlive();
if (mEventsThread != null) {
Log.e(LOG_TAG, "Ignoring startEventStream() : Thread already created.");
return;
}
if (mDataHandler == null) {
Log.e(LOG_TAG, "Error starting the event stream: No data handler is defined");
return;
}
Log.d(LOG_TAG, "startEventStream : create the event stream");
final EventsThreadListener fEventsListener = (null == anEventsListener) ? new DefaultEventsThreadListener(mDataHandler) : anEventsListener;
mEventsThread = new EventsThread(mEventsRestClient, fEventsListener, initialToken);
mEventsThread.setNetworkConnectivityReceiver(networkConnectivityReceiver);
if (mFailureCallback != null) {
mEventsThread.setFailureCallback(mFailureCallback);
}
if (mCredentials.accessToken != null && !mEventsThread.isAlive()) {
mEventsThread.start();
if (mIsCatchupPending) {
Log.d(LOG_TAG, "startEventStream : there was a pending catchup : the catchup will be triggered in 5 seconds");
mIsCatchupPending = false;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, "startEventStream : pause the stream");
pauseEventStream();
}
}, 5000);
}
}
}
/**
* Refresh the access token
*/
public void refreshToken() {
checkIfAlive();
mProfileRestClient.refreshTokens(new ApiCallback<Credentials>() {
@Override
public void onSuccess(Credentials info) {
Log.d(LOG_TAG, "refreshToken : succeeds.");
}
@Override
public void onNetworkError(Exception e) {
Log.d(LOG_TAG, "refreshToken : onNetworkError " + e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
Log.d(LOG_TAG, "refreshToken : onMatrixError " + e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
Log.d(LOG_TAG, "refreshToken : onMatrixError " + e.getLocalizedMessage());
}
});
}
/**
* Update the online status
* @param isOnline true if the client must be seen as online
*/
public void setIsOnline(boolean isOnline) {
if (isOnline != mIsOnline) {
mIsOnline = isOnline;
if (null != mEventsThread) {
mEventsThread.setIsOnline(isOnline);
}
}
}
/**
* Tell if the client is seen as "online"
*/
public boolean isOnline() {
return mIsOnline;
}
/**
* Update the heartbeat request timeout.
* @param ms the delay in ms
*/
public void setSyncTimeout(int ms) {
if (null != mEventsThread) {
mEventsThread.setServerLongPollTimeout(ms);
}
}
/**
* @return the heartbeat request timeout
*/
public int getSyncTimeout() {
if (null != mEventsThread) {
return mEventsThread.getServerLongPollTimeout();
}
return 0;
}
/**
* Set a delay between two sync requests.
* @param ms the delay in ms
*/
public void setSyncDelay(int ms) {
if (null != mEventsThread) {
mEventsThread.setSyncDelay(ms);
}
}
/**
* @return the delay between two sync requests.
*/
public int getSyncDelay() {
if (null != mEventsThread) {
mEventsThread.getSyncDelay();
}
return 0;
}
/**
* Shorthand for {@link #startEventStream(EventsThreadListener, NetworkConnectivityReceiver, String)} with no eventListener
* using a DataHandler and no specific failure callback.
*
* @param initialToken the initial sync token (null to sync from scratch).
*/
public void startEventStream(String initialToken) {
checkIfAlive();
startEventStream(null, this.mNetworkConnectivityReceiver, initialToken);
}
/**
* Gracefully stop the event stream.
*/
public void stopEventStream() {
if (null != mCallsManager) {
mCallsManager.stopTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "stopEventStream");
mEventsThread.kill();
mEventsThread = null;
} else {
Log.e(LOG_TAG, "stopEventStream : mEventsThread is already null");
}
}
/**
* Pause the event stream
*/
public void pauseEventStream() {
checkIfAlive();
if (null != mCallsManager) {
mCallsManager.pauseTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "pauseEventStream");
mEventsThread.pause();
} else {
Log.e(LOG_TAG, "pauseEventStream : mEventsThread is null");
}
if (null != mCrypto) {
mCrypto.pause();
}
}
/**
* Resume the event stream
*/
public void resumeEventStream() {
checkIfAlive();
if (null != mNetworkConnectivityReceiver) {
// mNetworkConnectivityReceiver is a broadcastReceiver
// but some users reported that the network updates wre not broadcasted.
mNetworkConnectivityReceiver.checkNetworkConnection(mAppContent);
}
if (null != mCallsManager) {
mCallsManager.unpauseTurnServerRefresh();
}
if (null != mEventsThread) {
Log.d(LOG_TAG, "unpause");
mEventsThread.unpause();
} else {
Log.e(LOG_TAG, "resumeEventStream : mEventsThread is null");
}
if (null != mCrypto) {
mCrypto.resume();
}
}
/**
* Trigger a catchup
*/
public void catchupEventStream() {
checkIfAlive();
if (null != mEventsThread) {
Log.d(LOG_TAG, "catchupEventStream");
mEventsThread.catchup();
} else {
Log.e(LOG_TAG, "catchupEventStream : mEventsThread is null so catchup when the thread will be created");
mIsCatchupPending = true;
}
}
/**
* Set a global failure callback implementation.
*
* @param failureCallback the failure callback
*/
public void setFailureCallback(ApiFailureCallback failureCallback) {
checkIfAlive();
mFailureCallback = failureCallback;
if (mEventsThread != null) {
mEventsThread.setFailureCallback(failureCallback);
}
}
/**
* Create a new room.
*
* @param callback the async callback once the room is ready
*/
public void createRoom(final ApiCallback<String> callback) {
createRoom(null, null, null, callback);
}
/**
* Create a new room with given properties.
*
* @param params the creation parameters.
* @param callback the async callback once the room is ready
*/
public void createRoom(final Map<String, Object> params, final ApiCallback<String> callback) {
mRoomsRestClient.createRoom(params, new SimpleApiCallback<CreateRoomResponse>(callback) {
@Override
public void onSuccess(CreateRoomResponse info) {
final String roomId = info.roomId;
Room createdRoom = mDataHandler.getRoom(roomId);
// the creation events are not be called during the creation
if (createdRoom.getState().getMember(mCredentials.userId) == null) {
createdRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
/**
* Create a new room with given properties. Needs the data handler.
*
* @param name the room name
* @param topic the room topic
* @param alias the room alias
* @param callback the async callback once the room is ready
*/
public void createRoom(String name, String topic, String alias, final ApiCallback<String> callback) {
createRoom(name, topic, RoomState.DIRECTORY_VISIBILITY_PRIVATE, alias, RoomState.GUEST_ACCESS_CAN_JOIN, RoomState.HISTORY_VISIBILITY_SHARED, callback);
}
/**
* Create a new room with given properties. Needs the data handler.
*
* @param name the room name
* @param topic the room topic
* @param visibility the room visibility
* @param alias the room alias
* @param guestAccess the guest access rule (see {@link RoomState#GUEST_ACCESS_CAN_JOIN} or {@link RoomState#GUEST_ACCESS_FORBIDDEN})
* @param historyVisibility the history visibility
* @param callback the async callback once the room is ready
*/
public void createRoom(String name, String topic, String visibility, String alias, String guestAccess, String historyVisibility, final ApiCallback<String> callback) {
checkIfAlive();
mRoomsRestClient.createRoom(name, topic, visibility, alias, guestAccess, historyVisibility, new SimpleApiCallback<CreateRoomResponse>(callback) {
@Override
public void onSuccess(CreateRoomResponse info) {
final String roomId = info.roomId;
Room createdRoom = mDataHandler.getRoom(roomId);
// the creation events are not be called during the creation
if (createdRoom.getState().getMember(mCredentials.userId) == null) {
createdRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
/**
* Join a room by its roomAlias
*
* @param roomIdOrAlias the room alias
* @param callback the async callback once the room is joined. The RoomId is provided.
*/
public void joinRoom(String roomIdOrAlias, final ApiCallback<String> callback) {
checkIfAlive();
// sanity check
if ((null != mDataHandler) && (null != roomIdOrAlias)) {
mDataRetriever.getRoomsRestClient().joinRoom(roomIdOrAlias, new SimpleApiCallback<RoomResponse>(callback) {
@Override
public void onSuccess(final RoomResponse roomResponse) {
final String roomId = roomResponse.roomId;
Room joinedRoom = mDataHandler.getRoom(roomId);
RoomMember member = joinedRoom.getState().getMember(mCredentials.userId);
String state = (null != member) ? member.membership : null;
// wait until the initial sync is done
if ((state == null) || TextUtils.equals(state, RoomMember.MEMBERSHIP_INVITE)) {
joinedRoom.setOnInitialSyncCallback(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(roomId);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
} else {
callback.onSuccess(roomId);
}
}
});
}
}
/**
* Retrieve user matrix id from a 3rd party id.
*
* @param address the user id.
* @param media the media.
* @param callback the 3rd party callback
*/
public void lookup3Pid(String address, String media, final ApiCallback<String> callback) {
checkIfAlive();
mThirdPidRestClient.lookup3Pid(address, media, callback);
}
/**
* Retrieve user matrix id from a 3rd party id.
*
* @param addresses 3rd party ids
* @param mediums the medias.
* @param callback the 3rd parties callback
*/
public void lookup3Pids(ArrayList<String> addresses, ArrayList<String> mediums, ApiCallback<ArrayList<String>> callback) {
checkIfAlive();
mThirdPidRestClient.lookup3Pids(addresses, mediums, callback);
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param beforeLimit the number of events to get before the matching results.
* @param afterLimit the number of events to get after the matching results.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessageText(String text, List<String> rooms, int beforeLimit, int afterLimit, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, rooms, beforeLimit, afterLimit, nextBatch, callback);
}
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessagesByText(String text, List<String> rooms, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, rooms, 0, 0, nextBatch, callback);
}
}
/**
* Perform a remote text search.
*
* @param text the text to search for.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMessagesByText(String text, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMessagesByText(text, null, 0, 0, nextBatch, callback);
}
}
/**
* Cancel any pending search request
*/
public void cancelSearchMessagesByText() {
checkIfAlive();
mEventsRestClient.cancelSearchMessagesByText();
}
/**
* Perform a remote text search for a dedicated media types list
*
* @param name the text to search for.
* @param rooms a list of rooms to search in. nil means all rooms the user is in.
* @param nextBatch the token to pass for doing pagination from a previous response.
* @param callback the request callback
*/
public void searchMediasByName(String name, List<String> rooms, String nextBatch, final ApiCallback<SearchResponse> callback) {
checkIfAlive();
if (null != callback) {
mEventsRestClient.searchMediasByText(name, rooms, 0, 0, nextBatch, callback);
}
}
/**
* Cancel any pending file search request
*/
public void cancelSearchMediasByText() {
checkIfAlive();
mEventsRestClient.cancelSearchMediasByText();
}
/**
* Return the fulfilled active BingRule for the event.
*
* @param event the event
* @return the fulfilled bingRule
*/
public BingRule fulfillRule(Event event) {
checkIfAlive();
return mBingRulesManager.fulfilledBingRule(event);
}
/**
* @return true if the calls are supported
*/
public boolean isVoipCallSupported() {
if (null != mCallsManager) {
return mCallsManager.isSupported();
} else {
return false;
}
}
/**
* Get the list of rooms that are tagged the specified tag.
* The returned array is ordered according to the room tag order.
*
* @param tag RoomTag.ROOM_TAG_XXX values
* @return the rooms list.
*/
public List<Room> roomsWithTag(final String tag) {
ArrayList<Room> taggedRooms = new ArrayList<>();
if (!TextUtils.equals(tag, RoomTag.ROOM_TAG_NO_TAG)) {
Collection<Room> rooms = mDataHandler.getStore().getRooms();
for (Room room : rooms) {
if (null != room.getAccountData().roomTag(tag)) {
taggedRooms.add(room);
}
}
if (taggedRooms.size() > 0) {
Collections.sort(taggedRooms, new Comparator<Room>() {
@Override
public int compare(Room r1, Room r2) {
int res = 0;
RoomTag tag1 = r1.getAccountData().roomTag(tag);
RoomTag tag2 = r2.getAccountData().roomTag(tag);
if ((null != tag1.mOrder) && (null != tag2.mOrder)) {
double diff = (tag1.mOrder - tag2.mOrder);
res = (diff == 0) ? 0 : (diff > 0) ? +1 : -1;
} else if (null != tag1.mOrder) {
res = -1;
} else if (null != tag2.mOrder) {
res = +1;
}
// In case of same order, order rooms by their last event
if (0 == res) {
IMXStore store = mDataHandler.getStore();
Event latestEvent1 = store.getLatestEvent(r1.getRoomId());
Event latestEvent2 = store.getLatestEvent(r2.getRoomId());
// sanity check
if ((null != latestEvent2) && (null != latestEvent1)) {
long diff = (latestEvent2.getOriginServerTs() - latestEvent1.getOriginServerTs());
res = (diff == 0) ? 0 : (diff > 0) ? +1 : -1;
}
}
return res;
}
});
}
} else {
Collection<Room> rooms = mDataHandler.getStore().getRooms();
for (Room room : rooms) {
if (!room.getAccountData().hasTags()) {
taggedRooms.add(room);
}
}
}
return taggedRooms;
}
/**
* Get the list of roomIds that are tagged the specified tag.
* The returned array is ordered according to the room tag order.
*
* @param tag RoomTag.ROOM_TAG_XXX values
* @return the room IDs list.
*/
public List<String> roomIdsWithTag(final String tag) {
List<Room> roomsWithTag = roomsWithTag(tag);
ArrayList<String> roomIdsList = new ArrayList<>();
for (Room room : roomsWithTag) {
roomIdsList.add(room.getRoomId());
}
return roomIdsList;
}
/**
* Compute the tag order to use for a room tag so that the room will appear in the expected position
* in the list of rooms stamped with this tag.
*
* @param index the targeted index of the room in the list of rooms with the tag `tag`.
* @param originIndex the origin index. Integer.MAX_VALUE if there is none.
* @param tag the tag
* @return the tag order to apply to get the expected position.
*/
public Double tagOrderToBeAtIndex(int index, int originIndex, String tag) {
// Algo (and the [0.0, 1.0] assumption) inspired from matrix-react-sdk:
// We sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
// For convenience, we calculate this for now a floating point number between 0.0 and 1.0.
Double orderA = 0.0; // by default we're next to the beginning of the list
Double orderB = 1.0; // by default we're next to the end of the list too
List<Room> roomsWithTag = roomsWithTag(tag);
if (roomsWithTag.size() > 0) {
// when an object is moved down, the index must be incremented
// because the object will be removed from the list to be inserted after its destination
if ((originIndex != Integer.MAX_VALUE) && (originIndex < index)) {
index++;
}
if (index > 0) {
// Bound max index to the array size
int prevIndex = (index < roomsWithTag.size()) ? index : roomsWithTag.size();
RoomTag prevTag = roomsWithTag.get(prevIndex - 1).getAccountData().roomTag(tag);
if (null == prevTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Previous room in sublist has no ordering metadata. This should never happen.");
} else {
orderA = prevTag.mOrder;
}
}
if (index <= roomsWithTag.size() - 1) {
RoomTag nextTag = roomsWithTag.get(index).getAccountData().roomTag(tag);
if (null == nextTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Next room in sublist has no ordering metadata. This should never happen.");
} else {
orderB = nextTag.mOrder;
}
}
}
return (orderA + orderB) / 2.0;
}
/**
* @return the direct chat room ids list
*/
public List<String> getDirectChatRoomIdsList() {
IMXStore store = getDataHandler().getStore();
ArrayList<String> directChatRoomIdsList = new ArrayList<>();
Collection<List<String>> listOfList = null;
if (null != store.getDirectChatRoomsDict()) {
listOfList = store.getDirectChatRoomsDict().values();
}
// if the direct messages entry has been defined
if (null != listOfList) {
for (List<String> list : listOfList) {
for (String roomId : list) {
// test if the room is defined once and exists
if ((directChatRoomIdsList.indexOf(roomId) < 0) && (null != store.getRoom(roomId))) {
directChatRoomIdsList.add(roomId);
}
}
}
} else {
// background compatibility heuristic (named looksLikeDirectMessageRoom in the JS)
ArrayList<Room> rooms = new ArrayList<>(store.getRooms());
for (Room r : rooms) {
// Show 1:1 chats in separate "Direct Messages" section as long as they haven't
// been moved to a different tag section
if ((r.getMembers().size() == 2) && (null != r.getAccountData()) && (!r.getAccountData().hasTags())) {
RoomMember roomMember = r.getMember(getMyUserId());
if (null != roomMember) {
String membership = roomMember.membership;
if (TextUtils.equals(membership, RoomMember.MEMBERSHIP_JOIN) ||
TextUtils.equals(membership, RoomMember.MEMBERSHIP_BAN) ||
TextUtils.equals(membership, RoomMember.MEMBERSHIP_LEAVE)) {
directChatRoomIdsList.add(r.getRoomId());
}
}
}
}
}
return directChatRoomIdsList;
}
/**
* Return the list of the direct chat room IDs for the user given in parameter.<br>
* Based on the account_data map content, the entry associated with aSearchedUserId is returned.
* @param aSearchedUserId user ID
* @return the list of the direct chat room Id
*/
public List<String> getDirectChatRoomIdsList(String aSearchedUserId) {
ArrayList<String> directChatRoomIdsList = new ArrayList<>();
IMXStore store = getDataHandler().getStore();
Room room;
HashMap<String, List<String>> params;
if(null != store.getDirectChatRoomsDict()) {
params = new HashMap<>(store.getDirectChatRoomsDict());
if (params.containsKey(aSearchedUserId)) {
directChatRoomIdsList = new ArrayList<>();
for(String roomId: params.get(aSearchedUserId)) {
room = store.getRoom(roomId);
if(null != room) { // skipp empty rooms
directChatRoomIdsList.add(roomId);
}
}
} else {
Log.w(LOG_TAG,"## getDirectChatRoomIdsList(): UserId "+aSearchedUserId+" has no entry in account_data");
}
} else {
Log.w(LOG_TAG,"## getDirectChatRoomIdsList(): failure - getDirectChatRoomsDict()=null");
}
return directChatRoomIdsList;
}
/**
* Toggles the direct chat status of a room.<br>
* Create a new direct chat room in the account data section if the room does not exist,
* otherwise the room is removed from the account data section.
* Direct chat room user ID choice algorithm:<br>
* 1- oldest joined room member
* 2- oldest invited room member
* 3- the user himself
* @param roomId the room roomId
* @param callback the asynchronous callback
*/
public void toggleDirectChatRoom(String roomId, String aParticipantUserId, ApiCallback<Void> callback) {
IMXStore store = getDataHandler().getStore();
Room room = store.getRoom(roomId);
if (null != room) {
HashMap<String, List<String>> params;
if (null != store.getDirectChatRoomsDict()) {
params = new HashMap<>(store.getDirectChatRoomsDict());
} else {
params = new HashMap<>();
}
// if the room was not yet seen as direct chat
if (getDirectChatRoomIdsList().indexOf(roomId) < 0) {
ArrayList<String> roomIdsList = new ArrayList<>();
RoomMember directChatMember = null;
String chosenUserId;
if(null == aParticipantUserId) {
ArrayList<RoomMember> members = new ArrayList<>(room.getActiveMembers());
if(members.size()>1) {
// sort algo: oldest join first, then oldest invited
Collections.sort(members, new Comparator<RoomMember>() {
@Override
public int compare(RoomMember r1, RoomMember r2) {
int res;
long diff;
if (RoomMember.MEMBERSHIP_JOIN.equals(r2.membership) && RoomMember.MEMBERSHIP_INVITE.equals(r1.membership)) {
res = 1;
} else if (r2.membership.equals(r1.membership)) {
diff = r1.getOriginServerTs() - r2.getOriginServerTs();
res = (0 == diff) ? 0 : ((diff > 0) ? 1 : -1);
} else {
res = -1;
}
return res;
}
});
int nextIndexSearch = 0;
// take the oldest join member
if (!TextUtils.equals(members.get(0).getUserId(), getMyUserId())) {
if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(0).membership)) {
directChatMember = members.get(0);
}
} else {
nextIndexSearch = 1;
if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(1).membership)) {
directChatMember = members.get(1);
}
}
// no join member found, test the oldest join member
if (null == directChatMember) {
if (RoomMember.MEMBERSHIP_INVITE.equals(members.get(nextIndexSearch).membership)) {
directChatMember = members.get(nextIndexSearch);
}
}
}
// last option: get the logged user
if (null == directChatMember) {
directChatMember = members.get(0);
}
chosenUserId = directChatMember.getUserId();
} else {
chosenUserId = aParticipantUserId;
}
// search if there is an entry with the same user
if (params.containsKey(chosenUserId)) {
roomIdsList = new ArrayList<>(params.get(chosenUserId));
}
roomIdsList.add(roomId); // update room list with the new room
params.put(chosenUserId, roomIdsList);
} else {
// remove the current room from the direct chat list rooms
if (null != store.getDirectChatRoomsDict()) {
Collection<List<String>> listOfList = store.getDirectChatRoomsDict().values();
for (List<String> list : listOfList) {
if (list.contains(roomId)) {
list.remove(roomId);
}
}
} else {
// should not happen: if the room has to be removed, it means the room has been
// previously detected as being part of the listOfList
Log.e(LOG_TAG, "## toggleDirectChatRoom(): failed to remove a direct chat room (not seen as direct chat room)");
return;
}
}
HashMap<String, Object> requestParams = new HashMap<>();
Collection<String> userIds = params.keySet();
for(String userId : userIds) {
requestParams.put(userId, params.get(userId));
}
mAccountDataRestClient.setAccountData(getMyUserId(), AccountDataRestClient.ACCOUNT_DATA_TYPE_DIRECT_MESSAGES, requestParams, callback);
}
}
/**
* Update the account password
*
* @param oldPassword the former account password
* @param newPassword the new account password
* @param callback the callback
*/
public void updatePassword(String oldPassword, String newPassword, ApiCallback<Void> callback) {
mProfileRestClient.updatePassword(getMyUserId(), oldPassword, newPassword, callback);
}
/**
* Reset the password to a new one.
*
* @param newPassword the new password
* @param threepid_creds the three pids.
* @param callback the callback
*/
public void resetPassword(final String newPassword, final Map<String, String> threepid_creds, final ApiCallback<Void> callback) {
mProfileRestClient.resetPassword(newPassword, threepid_creds, callback);
}
/**
* Triggers a request to update the userId to ignore
* @param userIds the userIds to ignoer
* @param callback the callback
*/
private void updateUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
HashMap<String, Object> ignoredUsersDict = new HashMap<>();
for (String userId : userIds) {
ignoredUsersDict.put(userId, new ArrayList<>());
}
HashMap<String, Object> params = new HashMap<>();
params.put(AccountDataRestClient.ACCOUNT_DATA_KEY_IGNORED_USERS, ignoredUsersDict);
mAccountDataRestClient.setAccountData(getMyUserId(), AccountDataRestClient.ACCOUNT_DATA_TYPE_IGNORED_USER_LIST, params, callback);
}
/**
* Tells if an user is in the ignored user ids list
* @param userId the user id to test
* @return true if the user is ignored
*/
public boolean isUserIgnored(String userId) {
if (null != userId) {
return getDataHandler().getIgnoredUserIds().indexOf(userId) >= 0;
}
return false;
}
/**
* Ignore a list of users.
* @param userIds the user ids list to ignore
* @param callback the result callback
*/
public void ignoreUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
List<String> curUserIdsToIgnore = getDataHandler().getIgnoredUserIds();
ArrayList<String> userIdsToIgnore = new ArrayList<>(getDataHandler().getIgnoredUserIds());
// something to add
if ((null != userIds) && (userIds.size() > 0)) {
// add the new one
for (String userId : userIds) {
if (userIdsToIgnore.indexOf(userId) < 0) {
userIdsToIgnore.add(userId);
}
}
// some items have been added
if (curUserIdsToIgnore.size() != userIdsToIgnore.size()) {
updateUsers(userIdsToIgnore, callback);
}
}
}
/**
* Unignore a list of users.
* @param userIds the user ids list to unignore
* @param callback the result callback
*/
public void unIgnoreUsers(ArrayList<String> userIds, ApiCallback<Void> callback) {
List<String> curUserIdsToIgnore = getDataHandler().getIgnoredUserIds();
ArrayList<String> userIdsToIgnore = new ArrayList<>(getDataHandler().getIgnoredUserIds());
// something to add
if ((null != userIds) && (userIds.size() > 0)) {
// add the new one
for (String userId : userIds) {
userIdsToIgnore.remove(userId);
}
// some items have been added
if (curUserIdsToIgnore.size() != userIdsToIgnore.size()) {
updateUsers(userIdsToIgnore, callback);
}
}
}
/**
* @return the network receiver.
*/
public NetworkConnectivityReceiver getNetworkConnectivityReceiver() {
return mNetworkConnectivityReceiver;
}
/**
* Invalidate the access token, so that it can no longer be used for authorization.
* @param context the application context
* @param callback the callback success and failure callback
*/
public void logout(final Context context, final ApiCallback<Void> callback) {
// Clear crypto data
// For security and because it will be no more useful as we will get a new device id
// on the next log in
enableCrypto(false, null);
mLoginRestClient.logout(new ApiCallback<JsonObject>() {
@Override
public void onSuccess(JsonObject info) {
clear(context);
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
clear(context);
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
clear(context);
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
clear(context);
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
//==============================================================================================================
// Crypto
//==============================================================================================================
/**
* The module that manages E2E encryption.
* Null if the feature is not enabled
*/
private MXCrypto mCrypto;
/**
* @return the crypto instance
*/
public MXCrypto getCrypto() {
return mCrypto;
}
/**
* @return true if the crypto is enabled
*/
public boolean isCryptoEnabled() {
return null != mCrypto;
}
/**
* enable encryption by default when launching the session
*/
private boolean mEnableCryptoWhenStartingMXSession = false;
/**
* Enable the crypto when initializing a new session.
*/
public void enableCryptoWhenStarting() {
mEnableCryptoWhenStartingMXSession = true;
}
/**
* When the encryption is toogled, the room summaries must be updated
* to display the right messages.
*/
private void decryptRoomSummaries() {
Collection<RoomSummary> summaries = getDataHandler().getStore().getSummaries();
for(RoomSummary summary :summaries) {
mDataHandler.decryptEvent(summary.getLatestReceivedEvent());
}
}
/**
* Enable / disable the crypto
* @param cryptoEnabled true to enable the crypto
*/
public void enableCrypto(boolean cryptoEnabled, final ApiCallback<Void> callback) {
if (cryptoEnabled != isCryptoEnabled()) {
if (cryptoEnabled) {
Log.d(LOG_TAG, "Crypto is enabled");
MXFileCryptoStore fileCryptoStore = new MXFileCryptoStore();
fileCryptoStore.initWithCredentials(mAppContent, mCredentials);
fileCryptoStore.open();
mCrypto = new MXCrypto(this, fileCryptoStore);
mCrypto.start(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
decryptRoomSummaries();
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} else if (null != mCrypto) {
Log.d(LOG_TAG, "Crypto is disabled");
IMXCryptoStore store = mCrypto.mCryptoStore;
mCrypto.close();
store.deleteStore();
mCrypto = null;
mDataHandler.setCrypto(null);
decryptRoomSummaries();
if (null != callback) {
callback.onSuccess(null);
}
}
mDataHandler.setCrypto(mCrypto);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Retrieves the devices list
* @param callback the asynchronous callback
*/
public void getDevicesList(ApiCallback<DevicesListResponse> callback) {
mCryptoRestClient.getDevices(callback);
}
/**
* Delete a device
* @param deviceId the device id
* @param session the session
* @param password the passwoerd
* @param callback the asynchronous callback.
*/
public void deleteDevice(final String deviceId, final String password, final ApiCallback<Void> callback) {
DeleteDeviceParams dummyparams = new DeleteDeviceParams();
mCryptoRestClient.deleteDevice(deviceId, dummyparams, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// should never happen
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError matrixError) {
Log.d(LOG_TAG, "## checkNameAvailability(): The registration continues");
RegistrationFlowResponse registrationFlowResponse = null;
// expected status code is 401
if ((null != matrixError.mStatus) && (matrixError.mStatus == 401)) {
try {
registrationFlowResponse = JsonUtils.toRegistrationFlowResponse(matrixError.mErrorBodyAsString);
} catch (Exception castExcept) {
Log.e(LOG_TAG, "## deleteDevice(): Received status 401 - Exception - JsonUtils.toRegistrationFlowResponse()");
}
} else {
Log.d(LOG_TAG, "## deleteDevice(): Received not expected status 401 ="+ matrixError.mStatus);
}
// check if the server response can be casted
if (null != registrationFlowResponse) {
DeleteDeviceParams params = new DeleteDeviceParams();
params.auth = new DeleteDeviceAuth();
params.auth.session = registrationFlowResponse.session;
params.auth.type = "m.login.password";
params.auth.user = mCredentials.userId;
params.auth.password = password;
mCryptoRestClient.deleteDevice(deviceId, params, callback);
} else {
if (null != callback) {
callback.onMatrixError(matrixError);
}
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
});
}
}
|
New API for direct message: createRoomDirectMessage()
|
matrix-sdk/src/main/java/org/matrix/androidsdk/MXSession.java
|
New API for direct message: createRoomDirectMessage()
|
|
Java
|
apache-2.0
|
715ea1907298b33661d0f2cf23b984b3b8b9c783
| 0
|
gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas
|
/*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.geneindex;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.inject.Inject;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class FindAutocompleteSuggestionsIT {
private static final String HOMO_SAPIENS_SPECIES = "homo sapiens";
private static final String MUS_MUSCULUS_SPECIES = "mus musculus";
@Inject
private SolrClient subject;
@Test
public void findGeneNameSuggestionsForPartialGeneNames() {
List<String> properties = subject.findGeneIdSuggestionsInName("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(2));
assertThat(properties, contains("mt-atp6", "mt-atp8"));
properties = subject.findGeneIdSuggestionsInIdentifier("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGenePropertySuggestions("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGeneNameSuggestionsForFullGeneNames() {
List<String> properties = subject.findGeneIdSuggestionsInName("mt-atp6", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("mt-atp6"));
properties = subject.findGeneIdSuggestionsInName("mt-atp8", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("mt-atp8"));
}
@Test
public void findSuggestionsForProteinCoding() {
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("protein_c", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("protein_coding"));
}
@Test
public void findSuggestionsForGOTerm() {
//GO:0016021
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("GO:0016", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("go:0016021", "go:0016020", "go:0016032"));
properties = subject.findGeneIdSuggestionsInIdentifier("GO:001602", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(5));
assertThat(properties, hasItems("go:0016021", "go:0016020", "go:0016028"));
properties = subject.findGeneIdSuggestionsInIdentifier("GO:0016021", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("go:0016021"));
}
@Test
public void findSuggestionsForDesignElement() {
//Hs2Affx.1.41.S1_3p_s_at
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("hs2affx.1.41.s1_3p_s_at", "hs2affx.1.43.s1_3p_x_at", "hs2affx.1.52.s1_3p_at"));
properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx.1.41", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(6));
assertThat(properties, hasItems("hs2affx.1.41.s1_3p_s_at", "hs2affx.1.413.s1_3p_at", "hs2affx.1.414.s1_3p_at"));
properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx.1.41.S1_3p_s", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("hs2affx.1.41.s1_3p_s_at"));
}
@Test
public void findSomethingStupidShouldReturnEmpty() {
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx>", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGeneIdSuggestionsInName("mt-at$", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGenePropertySuggestions("prot%", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGenePropertySuggestionsForPartialQuery() {
//"mitochondrial enco
List<String> properties = subject.findGenePropertySuggestions("mitochondrial enco", HOMO_SAPIENS_SPECIES);
assertThat(properties, hasItems("mitochondrially encoded"));
}
@Test
public void findGeneSynonymSuggestions() {
List<String> properties = subject.findGeneIdSuggestionsInSynonym("atpase-", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("atpase-6"));
properties = subject.findGeneIdSuggestionsInSynonym("mtatp", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("mtatp6", "mtatp8"));
properties = subject.findGeneIdSuggestionsInSynonym("su6", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("su6m"));
}
@Test
public void findGeneNameSuggestionsShouldSupportSingleTermQueries() {
List<String> properties = subject.findGeneIdSuggestionsInName("p", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("ppt2", "pbx2", "prrc2a"));
}
@Test
public void findGeneNameSuggestionsShouldNotContainSpeciesTerms() {
List<String> properties = subject.findGeneIdSuggestionsInName("mus", MUS_MUSCULUS_SPECIES);
assertThat(properties, containsInAnyOrder("musk", "mus81", "mustn1"));
}
@Test
public void findGeneNameSuggestionsShouldNotSupportMultitermQueries() {
List<String> properties = subject.findGeneIdSuggestionsInName("En p", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGenePropertySuggestionsShouldSupportMultiTermQueries() {
List<String> properties = subject.findGenePropertySuggestions("p b", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("p b", "p binding", "protein binding"));
}
}
|
web/src/test/java/uk/ac/ebi/atlas/geneindex/FindAutocompleteSuggestionsIT.java
|
/*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.geneindex;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.inject.Inject;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class FindAutocompleteSuggestionsIT {
private static final String HOMO_SAPIENS_SPECIES = "homo sapiens";
private static final String MUS_MUSCULUS_SPECIES = "mus musculus";
@Inject
private SolrClient subject;
@Test
public void findGeneNameSuggestionsForPartialGeneNames() {
List<String> properties = subject.findGeneIdSuggestionsInName("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(2));
assertThat(properties, contains("mt-atp6", "mt-atp8"));
properties = subject.findGeneIdSuggestionsInIdentifier("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGenePropertySuggestions("mt-at", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGeneNameSuggestionsForFullGeneNames() {
List<String> properties = subject.findGeneIdSuggestionsInName("mt-atp6", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("mt-atp6"));
properties = subject.findGeneIdSuggestionsInName("mt-atp8", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("mt-atp8"));
}
@Test
public void findSuggestionsForProteinCoding() {
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("protein_c", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("protein_coding"));
}
@Test
public void findSuggestionsForGOTerm() {
//GO:0016021
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("GO:0016", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("go:0016021", "go:0016020", "go:0016032"));
properties = subject.findGeneIdSuggestionsInIdentifier("GO:001602", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(5));
assertThat(properties, hasItems("go:0016021", "go:0016020", "go:0016028"));
properties = subject.findGeneIdSuggestionsInIdentifier("GO:0016021", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("go:0016021"));
}
@Test
public void findSuggestionsForDesignElement() {
//Hs2Affx.1.41.S1_3p_s_at
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("hs2affx.1.41.s1_3p_s_at", "hs2affx.1.43.s1_3p_x_at", "hs2affx.1.52.s1_3p_at"));
properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx.1.41", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(6));
assertThat(properties, hasItems("hs2affx.1.41.s1_3p_s_at", "hs2affx.1.413.s1_3p_at", "hs2affx.1.414.s1_3p_at"));
properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx.1.41.S1_3p_s", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(1));
assertThat(properties, contains("hs2affx.1.41.s1_3p_s_at"));
}
@Test
public void findSomethingStupidShouldReturnEmpty() {
List<String> properties = subject.findGeneIdSuggestionsInIdentifier("Hs2Affx>", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGeneIdSuggestionsInName("mt-at$", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
properties = subject.findGenePropertySuggestions("prot%", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGenePropertySuggestionsForPartialQuery() {
//"mitochondrial enco
List<String> properties = subject.findGenePropertySuggestions("mitochondrial enco", HOMO_SAPIENS_SPECIES);
assertThat(properties, hasItems("mitochondrially encoded"));
}
@Test
public void findGeneSynonymSuggestions() {
List<String> properties = subject.findGeneIdSuggestionsInSynonym("atpase-", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("atpase-6"));
properties = subject.findGeneIdSuggestionsInSynonym("mtatp", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("mtatp6", "mtatp8"));
properties = subject.findGeneIdSuggestionsInSynonym("su6", HOMO_SAPIENS_SPECIES);
assertThat(properties, contains("su6m"));
}
@Test
public void findGeneNameSuggestionsShouldSupportSingleTermQueries() {
List<String> properties = subject.findGeneIdSuggestionsInName("p", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("ppt2", "prpf31", "ptk2"));
}
@Test
public void findGeneNameSuggestionsShouldNotContainSpeciesTerms() {
List<String> properties = subject.findGeneIdSuggestionsInName("mus", MUS_MUSCULUS_SPECIES);
assertThat(properties, containsInAnyOrder("musk", "mus81", "mustn1"));
}
@Test
public void findGeneNameSuggestionsShouldNotSupportMultitermQueries() {
List<String> properties = subject.findGeneIdSuggestionsInName("En p", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(0));
}
@Test
public void findGenePropertySuggestionsShouldSupportMultiTermQueries() {
List<String> properties = subject.findGenePropertySuggestions("p b", HOMO_SAPIENS_SPECIES);
assertThat(properties.size(), is(15));
assertThat(properties, hasItems("p b", "p binding", "protein binding"));
}
}
|
fixed tests
|
web/src/test/java/uk/ac/ebi/atlas/geneindex/FindAutocompleteSuggestionsIT.java
|
fixed tests
|
|
Java
|
apache-2.0
|
c7bd5fd32f85159ebec082b02ef8031ec8bf8a0e
| 0
|
philliprower/cas,philliprower/cas,Jasig/cas,philliprower/cas,apereo/cas,philliprower/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,philliprower/cas,pdrados/cas,fogbeam/cas_mirror,rkorn86/cas,pdrados/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,apereo/cas,rkorn86/cas,leleuj/cas,pdrados/cas,leleuj/cas,leleuj/cas,rkorn86/cas,pdrados/cas,leleuj/cas,apereo/cas,pdrados/cas,leleuj/cas,philliprower/cas,apereo/cas,Jasig/cas,Jasig/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,apereo/cas,Jasig/cas,leleuj/cas,apereo/cas
|
package org.apereo.cas.configuration.support;
import com.google.common.base.Throwables;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apereo.cas.CipherExecutor;
import org.apereo.cas.authentication.handler.PrincipalNameTransformer;
import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalAttributesProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.model.core.util.CryptographyProperties;
import org.apereo.cas.configuration.model.support.ConnectionPoolingProperties;
import org.apereo.cas.configuration.model.support.jpa.AbstractJpaProperties;
import org.apereo.cas.configuration.model.support.jpa.DatabaseProperties;
import org.apereo.cas.configuration.model.support.jpa.JpaConfigDataHolder;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties;
import org.apereo.cas.configuration.model.support.mongo.AbstractMongoInstanceProperties;
import org.apereo.cas.util.cipher.DefaultTicketCipherExecutor;
import org.apereo.cas.util.cipher.NoOpCipherExecutor;
import org.apereo.cas.util.crypto.DefaultPasswordEncoder;
import org.apereo.cas.util.transforms.ConvertCasePrincipalNameTransformer;
import org.apereo.cas.util.transforms.PrefixSuffixPrincipalNameTransformer;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.apereo.services.persondir.support.NamedStubPersonAttributeDao;
import org.ldaptive.ActivePassiveConnectionStrategy;
import org.ldaptive.BindConnectionInitializer;
import org.ldaptive.CompareRequest;
import org.ldaptive.ConnectionConfig;
import org.ldaptive.Credential;
import org.ldaptive.DefaultConnectionFactory;
import org.ldaptive.DefaultConnectionStrategy;
import org.ldaptive.DnsSrvConnectionStrategy;
import org.ldaptive.LdapAttribute;
import org.ldaptive.RandomConnectionStrategy;
import org.ldaptive.ReturnAttributes;
import org.ldaptive.RoundRobinConnectionStrategy;
import org.ldaptive.SearchExecutor;
import org.ldaptive.SearchFilter;
import org.ldaptive.SearchRequest;
import org.ldaptive.SearchScope;
import org.ldaptive.ad.extended.FastBindOperation;
import org.ldaptive.ad.handler.ObjectGuidHandler;
import org.ldaptive.ad.handler.ObjectSidHandler;
import org.ldaptive.ad.handler.PrimaryGroupIdHandler;
import org.ldaptive.ad.handler.RangeEntryHandler;
import org.ldaptive.auth.EntryResolver;
import org.ldaptive.auth.PooledSearchEntryResolver;
import org.ldaptive.handler.CaseChangeEntryHandler;
import org.ldaptive.handler.DnAttributeEntryHandler;
import org.ldaptive.handler.MergeAttributeEntryHandler;
import org.ldaptive.handler.RecursiveEntryHandler;
import org.ldaptive.handler.SearchEntryHandler;
import org.ldaptive.pool.BlockingConnectionPool;
import org.ldaptive.pool.CompareValidator;
import org.ldaptive.pool.ConnectionPool;
import org.ldaptive.pool.IdlePruneStrategy;
import org.ldaptive.pool.PoolConfig;
import org.ldaptive.pool.PooledConnectionFactory;
import org.ldaptive.pool.SearchValidator;
import org.ldaptive.provider.Provider;
import org.ldaptive.referral.SearchReferralHandler;
import org.ldaptive.sasl.CramMd5Config;
import org.ldaptive.sasl.DigestMd5Config;
import org.ldaptive.sasl.ExternalConfig;
import org.ldaptive.sasl.GssApiConfig;
import org.ldaptive.sasl.SaslConfig;
import org.ldaptive.ssl.KeyStoreCredentialConfig;
import org.ldaptive.ssl.SslConfig;
import org.ldaptive.ssl.X509CredentialConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* A re-usable collection of utility methods for object instantiations and configurations used cross various
* <code>@Bean</code> creation methods throughout CAS server.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
public final class Beans {
/**
* Default parameter name in search filters for ldap.
*/
public static final String LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME = "user";
private static final Logger LOGGER = LoggerFactory.getLogger(Beans.class);
protected Beans() {
}
/**
* New hickari data source.
*
* @param jpaProperties the jpa properties
* @return the hikari data source
*/
public static HikariDataSource newHickariDataSource(final AbstractJpaProperties jpaProperties) {
try {
final HikariDataSource bean = new HikariDataSource();
bean.setDriverClassName(jpaProperties.getDriverClass());
bean.setJdbcUrl(jpaProperties.getUrl());
bean.setUsername(jpaProperties.getUser());
bean.setPassword(jpaProperties.getPassword());
bean.setMaximumPoolSize(jpaProperties.getPool().getMaxSize());
bean.setMinimumIdle(Long.valueOf(jpaProperties.getPool().getMaxIdleTime()).intValue());
bean.setIdleTimeout(jpaProperties.getIdleTimeout());
bean.setLeakDetectionThreshold(jpaProperties.getLeakThreshold());
bean.setInitializationFailFast(jpaProperties.isFailFast());
bean.setIsolateInternalQueries(jpaProperties.isIsolateInternalQueries());
bean.setConnectionTestQuery(jpaProperties.getHealthQuery());
bean.setAllowPoolSuspension(jpaProperties.getPool().isSuspension());
bean.setAutoCommit(jpaProperties.isAutocommit());
bean.setLoginTimeout(Long.valueOf(jpaProperties.getPool().getMaxWait()).intValue());
bean.setValidationTimeout(jpaProperties.getPool().getTimeoutMillis());
return bean;
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* New hibernate jpa vendor adapter.
*
* @param databaseProperties the database properties
* @return the hibernate jpa vendor adapter
*/
public static HibernateJpaVendorAdapter newHibernateJpaVendorAdapter(final DatabaseProperties databaseProperties) {
final HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
bean.setGenerateDdl(databaseProperties.isGenDdl());
bean.setShowSql(databaseProperties.isShowSql());
return bean;
}
/**
* New thread pool executor factory bean thread pool executor factory bean.
*
* @param config the config
* @return the thread pool executor factory bean
*/
public static ThreadPoolExecutorFactoryBean newThreadPoolExecutorFactoryBean(final ConnectionPoolingProperties config) {
final ThreadPoolExecutorFactoryBean bean = new ThreadPoolExecutorFactoryBean();
bean.setCorePoolSize(config.getMinSize());
bean.setMaxPoolSize(config.getMaxSize());
bean.setKeepAliveSeconds(Long.valueOf(config.getMaxWait()).intValue());
return bean;
}
/**
* New entity manager factory bean.
*
* @param config the config
* @param jpaProperties the jpa properties
* @return the local container entity manager factory bean
*/
public static LocalContainerEntityManagerFactoryBean newEntityManagerFactoryBean(final JpaConfigDataHolder config,
final AbstractJpaProperties jpaProperties) {
final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setJpaVendorAdapter(config.getJpaVendorAdapter());
if (StringUtils.isNotEmpty(config.getPersistenceUnitName())) {
bean.setPersistenceUnitName(config.getPersistenceUnitName());
}
bean.setPackagesToScan(config.getPackagesToScan());
bean.setDataSource(config.getDataSource());
final Properties properties = new Properties();
properties.put("hibernate.dialect", jpaProperties.getDialect());
properties.put("hibernate.hbm2ddl.auto", jpaProperties.getDdlAuto());
properties.put("hibernate.jdbc.batch_size", jpaProperties.getBatchSize());
if (StringUtils.isNotBlank(jpaProperties.getDefaultCatalog())) {
properties.put("hibernate.default_catalog", jpaProperties.getDefaultCatalog());
}
if (StringUtils.isNotBlank(jpaProperties.getDefaultSchema())) {
properties.put("hibernate.default_schema", jpaProperties.getDefaultSchema());
}
bean.setJpaProperties(properties);
return bean;
}
/**
* New attribute repository person attribute dao.
*
* @param p the properties
* @return the person attribute dao
*/
public static IPersonAttributeDao newStubAttributeRepository(final PrincipalAttributesProperties p) {
try {
final NamedStubPersonAttributeDao dao = new NamedStubPersonAttributeDao();
final Map<String, List<Object>> pdirMap = new HashMap<>();
p.getAttributes().entrySet().forEach(entry -> {
final String[] vals = org.springframework.util.StringUtils.commaDelimitedListToStringArray(entry.getValue());
pdirMap.put(entry.getKey(), Arrays.asList((Object[]) vals));
});
dao.setBackingMap(pdirMap);
return dao;
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
/**
* New password encoder password encoder.
*
* @param properties the properties
* @return the password encoder
*/
public static PasswordEncoder newPasswordEncoder(final PasswordEncoderProperties properties) {
final String type = properties.getType();
if (StringUtils.isBlank(type)) {
LOGGER.debug("No password encoder type is defined, and so none shall be created");
return NoOpPasswordEncoder.getInstance();
}
if (type.contains(".")) {
try {
LOGGER.debug("Configuration indicates use of a custom password encoder [{}]", type);
final Class<PasswordEncoder> clazz = (Class<PasswordEncoder>) Class.forName(type);
return clazz.newInstance();
} catch (final Exception e) {
LOGGER.error("Falling back to a no-op password encoder as CAS has failed to create "
+ "an instance of the custom password encoder class " + type, e);
return NoOpPasswordEncoder.getInstance();
}
}
final PasswordEncoderProperties.PasswordEncoderTypes encoderType = PasswordEncoderProperties.PasswordEncoderTypes.valueOf(type);
switch (encoderType) {
case DEFAULT:
LOGGER.debug("Creating default password encoder with encoding alg [{}] and character encoding [{}]",
properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
return new DefaultPasswordEncoder(properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
case STANDARD:
LOGGER.debug("Creating standard password encoder with the secret defined in the configuration");
return new StandardPasswordEncoder(properties.getSecret());
case BCRYPT:
LOGGER.debug("Creating BCRYPT password encoder given the strength [{}] and secret in the configuration",
properties.getStrength());
if (StringUtils.isBlank(properties.getSecret())) {
LOGGER.debug("Creating BCRYPT encoder without secret");
return new BCryptPasswordEncoder(properties.getStrength());
}
LOGGER.debug("Creating BCRYPT encoder with secret");
return new BCryptPasswordEncoder(properties.getStrength(),
new SecureRandom(properties.getSecret().getBytes(StandardCharsets.UTF_8)));
case NONE:
default:
LOGGER.debug("No password encoder shall be created given the requested encoder type [{}]", type);
return NoOpPasswordEncoder.getInstance();
}
}
/**
* New principal name transformer.
*
* @param p the p
* @return the principal name transformer
*/
public static PrincipalNameTransformer newPrincipalNameTransformer(final PrincipalTransformationProperties p) {
final PrincipalNameTransformer res;
if (StringUtils.isNotBlank(p.getPrefix()) || StringUtils.isNotBlank(p.getSuffix())) {
final PrefixSuffixPrincipalNameTransformer t = new PrefixSuffixPrincipalNameTransformer();
t.setPrefix(p.getPrefix());
t.setSuffix(p.getSuffix());
res = t;
} else {
res = formUserId -> formUserId;
}
switch (p.getCaseConversion()) {
case UPPERCASE:
final ConvertCasePrincipalNameTransformer t = new ConvertCasePrincipalNameTransformer(res);
t.setToUpperCase(true);
return t;
case LOWERCASE:
final ConvertCasePrincipalNameTransformer t1 = new ConvertCasePrincipalNameTransformer(res);
t1.setToUpperCase(false);
return t1;
default:
//nothing
}
return res;
}
/**
* New dn resolver entry resolver.
* Creates the necessary search entry resolver.
* @param l the ldap settings
* @param factory the factory
* @return the entry resolver
*/
public static EntryResolver newSearchEntryResolver(final LdapAuthenticationProperties l,
final PooledConnectionFactory factory) {
final PooledSearchEntryResolver entryResolver = new PooledSearchEntryResolver();
entryResolver.setBaseDn(l.getBaseDn());
entryResolver.setUserFilter(l.getUserFilter());
entryResolver.setSubtreeSearch(l.isSubtreeSearch());
entryResolver.setConnectionFactory(factory);
final List<SearchEntryHandler> handlers = new ArrayList<>();
l.getSearchEntryHandlers().forEach(h -> {
switch (h.getType()) {
case CASE_CHANGE:
final CaseChangeEntryHandler eh = new CaseChangeEntryHandler();
eh.setAttributeNameCaseChange(h.getCasChange().getAttributeNameCaseChange());
eh.setAttributeNames(h.getCasChange().getAttributeNames());
eh.setAttributeValueCaseChange(h.getCasChange().getAttributeValueCaseChange());
eh.setDnCaseChange(h.getCasChange().getDnCaseChange());
handlers.add(eh);
break;
case DN_ATTRIBUTE_ENTRY:
final DnAttributeEntryHandler ehd = new DnAttributeEntryHandler();
ehd.setAddIfExists(h.getDnAttribute().isAddIfExists());
ehd.setDnAttributeName(h.getDnAttribute().getDnAttributeName());
handlers.add(ehd);
break;
case MERGE:
final MergeAttributeEntryHandler ehm = new MergeAttributeEntryHandler();
ehm.setAttributeNames(h.getMergeAttribute().getAttributeNames());
ehm.setMergeAttributeName(h.getMergeAttribute().getMergeAttributeName());
handlers.add(ehm);
break;
case OBJECT_GUID:
handlers.add(new ObjectGuidHandler());
break;
case OBJECT_SID:
handlers.add(new ObjectSidHandler());
break;
case PRIMARY_GROUP:
final PrimaryGroupIdHandler ehp = new PrimaryGroupIdHandler();
ehp.setBaseDn(h.getPrimaryGroupId().getBaseDn());
ehp.setGroupFilter(h.getPrimaryGroupId().getGroupFilter());
handlers.add(ehp);
break;
case RANGE_ENTRY:
handlers.add(new RangeEntryHandler());
break;
case RECURSIVE_ENTRY:
handlers.add(new RecursiveEntryHandler(h.getRecursive().getSearchAttribute(), h.getRecursive().getMergeAttributes()));
break;
default:
break;
}
});
if (!handlers.isEmpty()) {
LOGGER.debug("Search entry handlers defined for the entry resolver of [{}] are [{}]", l.getLdapUrl(), handlers);
entryResolver.setSearchEntryHandlers(handlers.toArray(new SearchEntryHandler[]{}));
}
return entryResolver;
}
/**
* New connection config connection config.
*
* @param l the ldap properties
* @return the connection config
*/
public static ConnectionConfig newConnectionConfig(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection configuration for [{}]", l.getLdapUrl());
final ConnectionConfig cc = new ConnectionConfig();
cc.setLdapUrl(l.getLdapUrl());
cc.setUseSSL(l.isUseSsl());
cc.setUseStartTLS(l.isUseStartTls());
cc.setConnectTimeout(newDuration(l.getConnectTimeout()));
cc.setResponseTimeout(newDuration(l.getResponseTimeout()));
if (StringUtils.isNotBlank(l.getConnectionStrategy())) {
final AbstractLdapProperties.LdapConnectionStrategy strategy =
AbstractLdapProperties.LdapConnectionStrategy.valueOf(l.getConnectionStrategy());
switch (strategy) {
case RANDOM:
cc.setConnectionStrategy(new RandomConnectionStrategy());
break;
case DNS_SRV:
cc.setConnectionStrategy(new DnsSrvConnectionStrategy());
break;
case ACTIVE_PASSIVE:
cc.setConnectionStrategy(new ActivePassiveConnectionStrategy());
break;
case ROUND_ROBIN:
cc.setConnectionStrategy(new RoundRobinConnectionStrategy());
break;
case DEFAULT:
default:
cc.setConnectionStrategy(new DefaultConnectionStrategy());
break;
}
}
if (l.getTrustCertificates() != null) {
final X509CredentialConfig cfg = new X509CredentialConfig();
cfg.setTrustCertificates(l.getTrustCertificates());
cc.setSslConfig(new SslConfig(cfg));
} else if (l.getKeystore() != null) {
final KeyStoreCredentialConfig cfg = new KeyStoreCredentialConfig();
cfg.setKeyStore(l.getKeystore());
cfg.setKeyStorePassword(l.getKeystorePassword());
cfg.setKeyStoreType(l.getKeystoreType());
cc.setSslConfig(new SslConfig(cfg));
} else {
cc.setSslConfig(new SslConfig());
}
if (l.getSaslMechanism() != null) {
final BindConnectionInitializer bc = new BindConnectionInitializer();
final SaslConfig sc;
switch (l.getSaslMechanism()) {
case DIGEST_MD5:
sc = new DigestMd5Config();
((DigestMd5Config) sc).setRealm(l.getSaslRealm());
break;
case CRAM_MD5:
sc = new CramMd5Config();
break;
case EXTERNAL:
sc = new ExternalConfig();
break;
case GSSAPI:
sc = new GssApiConfig();
((GssApiConfig) sc).setRealm(l.getSaslRealm());
break;
default:
throw new IllegalArgumentException("Unknown SASL mechanism " + l.getSaslMechanism().name());
}
sc.setAuthorizationId(l.getSaslAuthorizationId());
sc.setMutualAuthentication(l.getSaslMutualAuth());
sc.setQualityOfProtection(l.getSaslQualityOfProtection());
sc.setSecurityStrength(l.getSaslSecurityStrength());
bc.setBindSaslConfig(sc);
cc.setConnectionInitializer(bc);
} else if (StringUtils.equals(l.getBindCredential(), "*") && StringUtils.equals(l.getBindDn(), "*")) {
cc.setConnectionInitializer(new FastBindOperation.FastBindConnectionInitializer());
} else if (StringUtils.isNotBlank(l.getBindDn()) && StringUtils.isNotBlank(l.getBindCredential())) {
cc.setConnectionInitializer(new BindConnectionInitializer(l.getBindDn(), new Credential(l.getBindCredential())));
}
return cc;
}
/**
* New pool config pool config.
*
* @param l the ldap properties
* @return the pool config
*/
public static PoolConfig newPoolConfig(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection pool configuration for [{}]", l.getLdapUrl());
final PoolConfig pc = new PoolConfig();
pc.setMinPoolSize(l.getMinPoolSize());
pc.setMaxPoolSize(l.getMaxPoolSize());
pc.setValidateOnCheckOut(l.isValidateOnCheckout());
pc.setValidatePeriodically(l.isValidatePeriodically());
pc.setValidatePeriod(newDuration(l.getValidatePeriod()));
return pc;
}
/**
* New connection factory connection factory.
*
* @param l the l
* @return the connection factory
*/
public static DefaultConnectionFactory newConnectionFactory(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection factory for [{}]", l.getLdapUrl());
final ConnectionConfig cc = newConnectionConfig(l);
final DefaultConnectionFactory bindCf = new DefaultConnectionFactory(cc);
if (l.getProviderClass() != null) {
try {
final Class clazz = ClassUtils.getClass(l.getProviderClass());
bindCf.setProvider(Provider.class.cast(clazz.newInstance()));
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return bindCf;
}
/**
* New blocking connection pool connection pool.
*
* @param l the l
* @return the connection pool
*/
public static ConnectionPool newBlockingConnectionPool(final AbstractLdapProperties l) {
final DefaultConnectionFactory bindCf = newConnectionFactory(l);
final PoolConfig pc = newPoolConfig(l);
final BlockingConnectionPool cp = new BlockingConnectionPool(pc, bindCf);
cp.setBlockWaitTime(newDuration(l.getBlockWaitTime()));
cp.setPoolConfig(pc);
final IdlePruneStrategy strategy = new IdlePruneStrategy();
strategy.setIdleTime(newDuration(l.getIdleTime()));
strategy.setPrunePeriod(newDuration(l.getPrunePeriod()));
cp.setPruneStrategy(strategy);
switch (l.getValidator().getType().trim().toLowerCase()) {
case "compare":
final CompareRequest compareRequest = new CompareRequest();
compareRequest.setDn(l.getValidator().getDn());
compareRequest.setAttribute(new LdapAttribute(l.getValidator().getAttributeName(),
l.getValidator().getAttributeValues().toArray(new String[]{})));
compareRequest.setReferralHandler(new SearchReferralHandler());
cp.setValidator(new CompareValidator(compareRequest));
break;
case "none":
LOGGER.debug("No validator is configured for the LDAP connection pool of [{}]", l.getLdapUrl());
break;
case "search":
default:
final SearchRequest searchRequest = new SearchRequest();
searchRequest.setBaseDn(l.getValidator().getBaseDn());
searchRequest.setSearchFilter(new SearchFilter(l.getValidator().getSearchFilter()));
searchRequest.setReturnAttributes(ReturnAttributes.NONE.value());
searchRequest.setSearchScope(l.getValidator().getScope());
searchRequest.setSizeLimit(1L);
searchRequest.setReferralHandler(new SearchReferralHandler());
cp.setValidator(new SearchValidator(searchRequest));
break;
}
cp.setFailFastInitialize(l.isFailFast());
LOGGER.debug("Initializing ldap connection pool for [{}] and bindDn [{}]", l.getLdapUrl(), l.getBindDn());
cp.initialize();
return cp;
}
/**
* New pooled connection factory pooled connection factory.
*
* @param l the ldap properties
* @return the pooled connection factory
*/
public static PooledConnectionFactory newPooledConnectionFactory(final AbstractLdapProperties l) {
final ConnectionPool cp = newBlockingConnectionPool(l);
return new PooledConnectionFactory(cp);
}
/**
* New duration. If the provided length is duration,
* it will be parsed accordingly, or if it's a numeric value
* it will be pared as a duration assuming it's provided as seconds.
*
* @param length the length in seconds.
* @return the duration
*/
public static Duration newDuration(final String length) {
try {
if (NumberUtils.isCreatable(length)) {
return Duration.ofSeconds(Long.valueOf(length));
}
return Duration.parse(length);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
/**
* New ticket registry cipher executor cipher executor.
*
* @param registry the registry
* @return the cipher executor
*/
public static CipherExecutor newTicketRegistryCipherExecutor(final CryptographyProperties registry) {
return newTicketRegistryCipherExecutor(registry, false);
}
/**
* New ticket registry cipher executor cipher executor.
*
* @param registry the registry
* @param forceIfBlankKeys the force if blank keys
* @return the cipher executor
*/
public static CipherExecutor newTicketRegistryCipherExecutor(final CryptographyProperties registry, final boolean forceIfBlankKeys) {
if ((StringUtils.isNotBlank(registry.getEncryption().getKey())
&& StringUtils.isNotBlank(registry.getEncryption().getKey()))
|| forceIfBlankKeys) {
return new DefaultTicketCipherExecutor(
registry.getEncryption().getKey(),
registry.getSigning().getKey(),
registry.getAlg(),
registry.getSigning().getKeySize(),
registry.getEncryption().getKeySize());
}
LOGGER.debug("Ticket registry encryption/signing is turned off. This MAY NOT be safe in a "
+ "clustered production environment. "
+ "Consider using other choices to handle encryption, signing and verification of "
+ "ticket registry tickets, and verify the chosen ticket registry does support this behavior.");
return NoOpCipherExecutor.getInstance();
}
/**
* Builds a new request.
*
* @param baseDn the base dn
* @param filter the filter
* @return the search request
*/
public static SearchRequest newSearchRequest(final String baseDn, final SearchFilter filter) {
final SearchRequest sr = new SearchRequest(baseDn, filter);
sr.setBinaryAttributes(ReturnAttributes.ALL_USER.value());
sr.setReturnAttributes(ReturnAttributes.ALL_USER.value());
sr.setSearchScope(SearchScope.SUBTREE);
return sr;
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery) {
return newSearchFilter(filterQuery, Collections.emptyList());
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @param params the username
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery, final List<String> params) {
return newSearchFilter(filterQuery, LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, params);
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @param paramName the param name
* @param params the username
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery, final String paramName, final List<String> params) {
final SearchFilter filter = new SearchFilter();
filter.setFilter(filterQuery);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
if (filter.getFilter().contains("{" + i + '}')) {
filter.setParameter(i, params.get(i));
} else {
filter.setParameter(paramName, params.get(i));
}
}
}
LOGGER.debug("Constructed LDAP search filter [{}]", filter.format());
return filter;
}
/**
* New search executor search executor.
*
* @param baseDn the base dn
* @param filterQuery the filter query
* @param params the params
* @return the search executor
*/
public static SearchExecutor newSearchExecutor(final String baseDn, final String filterQuery, final List<String> params) {
final SearchExecutor executor = new SearchExecutor();
executor.setBaseDn(baseDn);
executor.setSearchFilter(newSearchFilter(filterQuery, params));
executor.setReturnAttributes(ReturnAttributes.ALL.value());
executor.setSearchScope(SearchScope.SUBTREE);
return executor;
}
/**
* New search executor search executor.
*
* @param baseDn the base dn
* @param filterQuery the filter query
* @return the search executor
*/
public static SearchExecutor newSearchExecutor(final String baseDn, final String filterQuery) {
return newSearchExecutor(baseDn, filterQuery, Collections.emptyList());
}
/**
* New mongo db client options factory bean.
*
* @param mongo the mongo properties.
* @return the mongo client options factory bean
*/
public static MongoClientOptionsFactoryBean newMongoDbClientOptionsFactoryBean(final AbstractMongoInstanceProperties mongo) {
try {
final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
bean.setWriteConcern(WriteConcern.valueOf(mongo.getWriteConcern()));
bean.setHeartbeatConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setHeartbeatSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setMaxConnectionLifeTime(mongo.getConns().getLifetime());
bean.setSocketKeepAlive(mongo.isSocketKeepAlive());
bean.setMaxConnectionIdleTime(Long.valueOf(mongo.getIdleTimeout()).intValue());
bean.setConnectionsPerHost(mongo.getConns().getPerHost());
bean.setSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.afterPropertiesSet();
return bean;
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
/**
* New mongo db client options.
*
* @param mongo the mongo
* @return the mongo client options
*/
public static MongoClientOptions newMongoDbClientOptions(final AbstractMongoInstanceProperties mongo) {
try {
return newMongoDbClientOptionsFactoryBean(mongo).getObject();
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
/**
* New mongo db client.
*
* @param mongo the mongo
* @return the mongo
*/
public static Mongo newMongoDbClient(final AbstractMongoInstanceProperties mongo) {
return new MongoClient(new ServerAddress(
mongo.getHost(),
mongo.getPort()),
Collections.singletonList(
MongoCredential.createCredential(
mongo.getUserId(),
mongo.getDatabaseName(),
mongo.getPassword().toCharArray())),
newMongoDbClientOptions(mongo));
}
}
|
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/support/Beans.java
|
package org.apereo.cas.configuration.support;
import com.google.common.base.Throwables;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apereo.cas.CipherExecutor;
import org.apereo.cas.authentication.handler.PrincipalNameTransformer;
import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalAttributesProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.model.core.util.CryptographyProperties;
import org.apereo.cas.configuration.model.support.ConnectionPoolingProperties;
import org.apereo.cas.configuration.model.support.jpa.AbstractJpaProperties;
import org.apereo.cas.configuration.model.support.jpa.DatabaseProperties;
import org.apereo.cas.configuration.model.support.jpa.JpaConfigDataHolder;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties;
import org.apereo.cas.configuration.model.support.mongo.AbstractMongoInstanceProperties;
import org.apereo.cas.util.cipher.DefaultTicketCipherExecutor;
import org.apereo.cas.util.cipher.NoOpCipherExecutor;
import org.apereo.cas.util.crypto.DefaultPasswordEncoder;
import org.apereo.cas.util.transforms.ConvertCasePrincipalNameTransformer;
import org.apereo.cas.util.transforms.PrefixSuffixPrincipalNameTransformer;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.apereo.services.persondir.support.NamedStubPersonAttributeDao;
import org.ldaptive.ActivePassiveConnectionStrategy;
import org.ldaptive.BindConnectionInitializer;
import org.ldaptive.CompareRequest;
import org.ldaptive.ConnectionConfig;
import org.ldaptive.Credential;
import org.ldaptive.DefaultConnectionFactory;
import org.ldaptive.DefaultConnectionStrategy;
import org.ldaptive.DnsSrvConnectionStrategy;
import org.ldaptive.LdapAttribute;
import org.ldaptive.RandomConnectionStrategy;
import org.ldaptive.ReturnAttributes;
import org.ldaptive.RoundRobinConnectionStrategy;
import org.ldaptive.SearchExecutor;
import org.ldaptive.SearchFilter;
import org.ldaptive.SearchRequest;
import org.ldaptive.SearchScope;
import org.ldaptive.ad.extended.FastBindOperation;
import org.ldaptive.ad.handler.ObjectGuidHandler;
import org.ldaptive.ad.handler.ObjectSidHandler;
import org.ldaptive.ad.handler.PrimaryGroupIdHandler;
import org.ldaptive.ad.handler.RangeEntryHandler;
import org.ldaptive.auth.EntryResolver;
import org.ldaptive.auth.PooledSearchEntryResolver;
import org.ldaptive.handler.CaseChangeEntryHandler;
import org.ldaptive.handler.DnAttributeEntryHandler;
import org.ldaptive.handler.MergeAttributeEntryHandler;
import org.ldaptive.handler.RecursiveEntryHandler;
import org.ldaptive.handler.SearchEntryHandler;
import org.ldaptive.pool.BlockingConnectionPool;
import org.ldaptive.pool.CompareValidator;
import org.ldaptive.pool.ConnectionPool;
import org.ldaptive.pool.IdlePruneStrategy;
import org.ldaptive.pool.PoolConfig;
import org.ldaptive.pool.PooledConnectionFactory;
import org.ldaptive.pool.SearchValidator;
import org.ldaptive.provider.Provider;
import org.ldaptive.referral.SearchReferralHandler;
import org.ldaptive.sasl.CramMd5Config;
import org.ldaptive.sasl.DigestMd5Config;
import org.ldaptive.sasl.ExternalConfig;
import org.ldaptive.sasl.GssApiConfig;
import org.ldaptive.sasl.SaslConfig;
import org.ldaptive.ssl.KeyStoreCredentialConfig;
import org.ldaptive.ssl.SslConfig;
import org.ldaptive.ssl.X509CredentialConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* A re-usable collection of utility methods for object instantiations and configurations used cross various
* <code>@Bean</code> creation methods throughout CAS server.
*
* @author Dmitriy Kopylenko
* @since 5.0.0
*/
public final class Beans {
/**
* Default parameter name in search filters for ldap.
*/
public static final String LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME = "user";
private static final Logger LOGGER = LoggerFactory.getLogger(Beans.class);
protected Beans() {
}
/**
* New hickari data source.
*
* @param jpaProperties the jpa properties
* @return the hikari data source
*/
public static HikariDataSource newHickariDataSource(final AbstractJpaProperties jpaProperties) {
try {
final HikariDataSource bean = new HikariDataSource();
bean.setDriverClassName(jpaProperties.getDriverClass());
bean.setJdbcUrl(jpaProperties.getUrl());
bean.setUsername(jpaProperties.getUser());
bean.setPassword(jpaProperties.getPassword());
bean.setMaximumPoolSize(jpaProperties.getPool().getMaxSize());
bean.setMinimumIdle(Long.valueOf(jpaProperties.getPool().getMaxIdleTime()).intValue());
bean.setIdleTimeout(jpaProperties.getIdleTimeout());
bean.setLeakDetectionThreshold(jpaProperties.getLeakThreshold());
bean.setInitializationFailFast(jpaProperties.isFailFast());
bean.setIsolateInternalQueries(jpaProperties.isIsolateInternalQueries());
bean.setConnectionTestQuery(jpaProperties.getHealthQuery());
bean.setAllowPoolSuspension(jpaProperties.getPool().isSuspension());
bean.setAutoCommit(jpaProperties.isAutocommit());
bean.setLoginTimeout(Long.valueOf(jpaProperties.getPool().getMaxWait()).intValue());
bean.setValidationTimeout(jpaProperties.getPool().getMaxWait());
return bean;
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* New hibernate jpa vendor adapter.
*
* @param databaseProperties the database properties
* @return the hibernate jpa vendor adapter
*/
public static HibernateJpaVendorAdapter newHibernateJpaVendorAdapter(final DatabaseProperties databaseProperties) {
final HibernateJpaVendorAdapter bean = new HibernateJpaVendorAdapter();
bean.setGenerateDdl(databaseProperties.isGenDdl());
bean.setShowSql(databaseProperties.isShowSql());
return bean;
}
/**
* New thread pool executor factory bean thread pool executor factory bean.
*
* @param config the config
* @return the thread pool executor factory bean
*/
public static ThreadPoolExecutorFactoryBean newThreadPoolExecutorFactoryBean(final ConnectionPoolingProperties config) {
final ThreadPoolExecutorFactoryBean bean = new ThreadPoolExecutorFactoryBean();
bean.setCorePoolSize(config.getMinSize());
bean.setMaxPoolSize(config.getMaxSize());
bean.setKeepAliveSeconds(Long.valueOf(config.getMaxWait()).intValue());
return bean;
}
/**
* New entity manager factory bean.
*
* @param config the config
* @param jpaProperties the jpa properties
* @return the local container entity manager factory bean
*/
public static LocalContainerEntityManagerFactoryBean newEntityManagerFactoryBean(final JpaConfigDataHolder config,
final AbstractJpaProperties jpaProperties) {
final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setJpaVendorAdapter(config.getJpaVendorAdapter());
if (StringUtils.isNotEmpty(config.getPersistenceUnitName())) {
bean.setPersistenceUnitName(config.getPersistenceUnitName());
}
bean.setPackagesToScan(config.getPackagesToScan());
bean.setDataSource(config.getDataSource());
final Properties properties = new Properties();
properties.put("hibernate.dialect", jpaProperties.getDialect());
properties.put("hibernate.hbm2ddl.auto", jpaProperties.getDdlAuto());
properties.put("hibernate.jdbc.batch_size", jpaProperties.getBatchSize());
if (StringUtils.isNotBlank(jpaProperties.getDefaultCatalog())) {
properties.put("hibernate.default_catalog", jpaProperties.getDefaultCatalog());
}
if (StringUtils.isNotBlank(jpaProperties.getDefaultSchema())) {
properties.put("hibernate.default_schema", jpaProperties.getDefaultSchema());
}
bean.setJpaProperties(properties);
return bean;
}
/**
* New attribute repository person attribute dao.
*
* @param p the properties
* @return the person attribute dao
*/
public static IPersonAttributeDao newStubAttributeRepository(final PrincipalAttributesProperties p) {
try {
final NamedStubPersonAttributeDao dao = new NamedStubPersonAttributeDao();
final Map<String, List<Object>> pdirMap = new HashMap<>();
p.getAttributes().entrySet().forEach(entry -> {
final String[] vals = org.springframework.util.StringUtils.commaDelimitedListToStringArray(entry.getValue());
pdirMap.put(entry.getKey(), Arrays.asList((Object[]) vals));
});
dao.setBackingMap(pdirMap);
return dao;
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
/**
* New password encoder password encoder.
*
* @param properties the properties
* @return the password encoder
*/
public static PasswordEncoder newPasswordEncoder(final PasswordEncoderProperties properties) {
final String type = properties.getType();
if (StringUtils.isBlank(type)) {
LOGGER.debug("No password encoder type is defined, and so none shall be created");
return NoOpPasswordEncoder.getInstance();
}
if (type.contains(".")) {
try {
LOGGER.debug("Configuration indicates use of a custom password encoder [{}]", type);
final Class<PasswordEncoder> clazz = (Class<PasswordEncoder>) Class.forName(type);
return clazz.newInstance();
} catch (final Exception e) {
LOGGER.error("Falling back to a no-op password encoder as CAS has failed to create "
+ "an instance of the custom password encoder class " + type, e);
return NoOpPasswordEncoder.getInstance();
}
}
final PasswordEncoderProperties.PasswordEncoderTypes encoderType = PasswordEncoderProperties.PasswordEncoderTypes.valueOf(type);
switch (encoderType) {
case DEFAULT:
LOGGER.debug("Creating default password encoder with encoding alg [{}] and character encoding [{}]",
properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
return new DefaultPasswordEncoder(properties.getEncodingAlgorithm(), properties.getCharacterEncoding());
case STANDARD:
LOGGER.debug("Creating standard password encoder with the secret defined in the configuration");
return new StandardPasswordEncoder(properties.getSecret());
case BCRYPT:
LOGGER.debug("Creating BCRYPT password encoder given the strength [{}] and secret in the configuration",
properties.getStrength());
if (StringUtils.isBlank(properties.getSecret())) {
LOGGER.debug("Creating BCRYPT encoder without secret");
return new BCryptPasswordEncoder(properties.getStrength());
}
LOGGER.debug("Creating BCRYPT encoder with secret");
return new BCryptPasswordEncoder(properties.getStrength(),
new SecureRandom(properties.getSecret().getBytes(StandardCharsets.UTF_8)));
case NONE:
default:
LOGGER.debug("No password encoder shall be created given the requested encoder type [{}]", type);
return NoOpPasswordEncoder.getInstance();
}
}
/**
* New principal name transformer.
*
* @param p the p
* @return the principal name transformer
*/
public static PrincipalNameTransformer newPrincipalNameTransformer(final PrincipalTransformationProperties p) {
final PrincipalNameTransformer res;
if (StringUtils.isNotBlank(p.getPrefix()) || StringUtils.isNotBlank(p.getSuffix())) {
final PrefixSuffixPrincipalNameTransformer t = new PrefixSuffixPrincipalNameTransformer();
t.setPrefix(p.getPrefix());
t.setSuffix(p.getSuffix());
res = t;
} else {
res = formUserId -> formUserId;
}
switch (p.getCaseConversion()) {
case UPPERCASE:
final ConvertCasePrincipalNameTransformer t = new ConvertCasePrincipalNameTransformer(res);
t.setToUpperCase(true);
return t;
case LOWERCASE:
final ConvertCasePrincipalNameTransformer t1 = new ConvertCasePrincipalNameTransformer(res);
t1.setToUpperCase(false);
return t1;
default:
//nothing
}
return res;
}
/**
* New dn resolver entry resolver.
* Creates the necessary search entry resolver.
* @param l the ldap settings
* @param factory the factory
* @return the entry resolver
*/
public static EntryResolver newSearchEntryResolver(final LdapAuthenticationProperties l,
final PooledConnectionFactory factory) {
final PooledSearchEntryResolver entryResolver = new PooledSearchEntryResolver();
entryResolver.setBaseDn(l.getBaseDn());
entryResolver.setUserFilter(l.getUserFilter());
entryResolver.setSubtreeSearch(l.isSubtreeSearch());
entryResolver.setConnectionFactory(factory);
final List<SearchEntryHandler> handlers = new ArrayList<>();
l.getSearchEntryHandlers().forEach(h -> {
switch (h.getType()) {
case CASE_CHANGE:
final CaseChangeEntryHandler eh = new CaseChangeEntryHandler();
eh.setAttributeNameCaseChange(h.getCasChange().getAttributeNameCaseChange());
eh.setAttributeNames(h.getCasChange().getAttributeNames());
eh.setAttributeValueCaseChange(h.getCasChange().getAttributeValueCaseChange());
eh.setDnCaseChange(h.getCasChange().getDnCaseChange());
handlers.add(eh);
break;
case DN_ATTRIBUTE_ENTRY:
final DnAttributeEntryHandler ehd = new DnAttributeEntryHandler();
ehd.setAddIfExists(h.getDnAttribute().isAddIfExists());
ehd.setDnAttributeName(h.getDnAttribute().getDnAttributeName());
handlers.add(ehd);
break;
case MERGE:
final MergeAttributeEntryHandler ehm = new MergeAttributeEntryHandler();
ehm.setAttributeNames(h.getMergeAttribute().getAttributeNames());
ehm.setMergeAttributeName(h.getMergeAttribute().getMergeAttributeName());
handlers.add(ehm);
break;
case OBJECT_GUID:
handlers.add(new ObjectGuidHandler());
break;
case OBJECT_SID:
handlers.add(new ObjectSidHandler());
break;
case PRIMARY_GROUP:
final PrimaryGroupIdHandler ehp = new PrimaryGroupIdHandler();
ehp.setBaseDn(h.getPrimaryGroupId().getBaseDn());
ehp.setGroupFilter(h.getPrimaryGroupId().getGroupFilter());
handlers.add(ehp);
break;
case RANGE_ENTRY:
handlers.add(new RangeEntryHandler());
break;
case RECURSIVE_ENTRY:
handlers.add(new RecursiveEntryHandler(h.getRecursive().getSearchAttribute(), h.getRecursive().getMergeAttributes()));
break;
default:
break;
}
});
if (!handlers.isEmpty()) {
LOGGER.debug("Search entry handlers defined for the entry resolver of [{}] are [{}]", l.getLdapUrl(), handlers);
entryResolver.setSearchEntryHandlers(handlers.toArray(new SearchEntryHandler[]{}));
}
return entryResolver;
}
/**
* New connection config connection config.
*
* @param l the ldap properties
* @return the connection config
*/
public static ConnectionConfig newConnectionConfig(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection configuration for [{}]", l.getLdapUrl());
final ConnectionConfig cc = new ConnectionConfig();
cc.setLdapUrl(l.getLdapUrl());
cc.setUseSSL(l.isUseSsl());
cc.setUseStartTLS(l.isUseStartTls());
cc.setConnectTimeout(newDuration(l.getConnectTimeout()));
cc.setResponseTimeout(newDuration(l.getResponseTimeout()));
if (StringUtils.isNotBlank(l.getConnectionStrategy())) {
final AbstractLdapProperties.LdapConnectionStrategy strategy =
AbstractLdapProperties.LdapConnectionStrategy.valueOf(l.getConnectionStrategy());
switch (strategy) {
case RANDOM:
cc.setConnectionStrategy(new RandomConnectionStrategy());
break;
case DNS_SRV:
cc.setConnectionStrategy(new DnsSrvConnectionStrategy());
break;
case ACTIVE_PASSIVE:
cc.setConnectionStrategy(new ActivePassiveConnectionStrategy());
break;
case ROUND_ROBIN:
cc.setConnectionStrategy(new RoundRobinConnectionStrategy());
break;
case DEFAULT:
default:
cc.setConnectionStrategy(new DefaultConnectionStrategy());
break;
}
}
if (l.getTrustCertificates() != null) {
final X509CredentialConfig cfg = new X509CredentialConfig();
cfg.setTrustCertificates(l.getTrustCertificates());
cc.setSslConfig(new SslConfig(cfg));
} else if (l.getKeystore() != null) {
final KeyStoreCredentialConfig cfg = new KeyStoreCredentialConfig();
cfg.setKeyStore(l.getKeystore());
cfg.setKeyStorePassword(l.getKeystorePassword());
cfg.setKeyStoreType(l.getKeystoreType());
cc.setSslConfig(new SslConfig(cfg));
} else {
cc.setSslConfig(new SslConfig());
}
if (l.getSaslMechanism() != null) {
final BindConnectionInitializer bc = new BindConnectionInitializer();
final SaslConfig sc;
switch (l.getSaslMechanism()) {
case DIGEST_MD5:
sc = new DigestMd5Config();
((DigestMd5Config) sc).setRealm(l.getSaslRealm());
break;
case CRAM_MD5:
sc = new CramMd5Config();
break;
case EXTERNAL:
sc = new ExternalConfig();
break;
case GSSAPI:
sc = new GssApiConfig();
((GssApiConfig) sc).setRealm(l.getSaslRealm());
break;
default:
throw new IllegalArgumentException("Unknown SASL mechanism " + l.getSaslMechanism().name());
}
sc.setAuthorizationId(l.getSaslAuthorizationId());
sc.setMutualAuthentication(l.getSaslMutualAuth());
sc.setQualityOfProtection(l.getSaslQualityOfProtection());
sc.setSecurityStrength(l.getSaslSecurityStrength());
bc.setBindSaslConfig(sc);
cc.setConnectionInitializer(bc);
} else if (StringUtils.equals(l.getBindCredential(), "*") && StringUtils.equals(l.getBindDn(), "*")) {
cc.setConnectionInitializer(new FastBindOperation.FastBindConnectionInitializer());
} else if (StringUtils.isNotBlank(l.getBindDn()) && StringUtils.isNotBlank(l.getBindCredential())) {
cc.setConnectionInitializer(new BindConnectionInitializer(l.getBindDn(), new Credential(l.getBindCredential())));
}
return cc;
}
/**
* New pool config pool config.
*
* @param l the ldap properties
* @return the pool config
*/
public static PoolConfig newPoolConfig(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection pool configuration for [{}]", l.getLdapUrl());
final PoolConfig pc = new PoolConfig();
pc.setMinPoolSize(l.getMinPoolSize());
pc.setMaxPoolSize(l.getMaxPoolSize());
pc.setValidateOnCheckOut(l.isValidateOnCheckout());
pc.setValidatePeriodically(l.isValidatePeriodically());
pc.setValidatePeriod(newDuration(l.getValidatePeriod()));
return pc;
}
/**
* New connection factory connection factory.
*
* @param l the l
* @return the connection factory
*/
public static DefaultConnectionFactory newConnectionFactory(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection factory for [{}]", l.getLdapUrl());
final ConnectionConfig cc = newConnectionConfig(l);
final DefaultConnectionFactory bindCf = new DefaultConnectionFactory(cc);
if (l.getProviderClass() != null) {
try {
final Class clazz = ClassUtils.getClass(l.getProviderClass());
bindCf.setProvider(Provider.class.cast(clazz.newInstance()));
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return bindCf;
}
/**
* New blocking connection pool connection pool.
*
* @param l the l
* @return the connection pool
*/
public static ConnectionPool newBlockingConnectionPool(final AbstractLdapProperties l) {
final DefaultConnectionFactory bindCf = newConnectionFactory(l);
final PoolConfig pc = newPoolConfig(l);
final BlockingConnectionPool cp = new BlockingConnectionPool(pc, bindCf);
cp.setBlockWaitTime(newDuration(l.getBlockWaitTime()));
cp.setPoolConfig(pc);
final IdlePruneStrategy strategy = new IdlePruneStrategy();
strategy.setIdleTime(newDuration(l.getIdleTime()));
strategy.setPrunePeriod(newDuration(l.getPrunePeriod()));
cp.setPruneStrategy(strategy);
switch (l.getValidator().getType().trim().toLowerCase()) {
case "compare":
final CompareRequest compareRequest = new CompareRequest();
compareRequest.setDn(l.getValidator().getDn());
compareRequest.setAttribute(new LdapAttribute(l.getValidator().getAttributeName(),
l.getValidator().getAttributeValues().toArray(new String[]{})));
compareRequest.setReferralHandler(new SearchReferralHandler());
cp.setValidator(new CompareValidator(compareRequest));
break;
case "none":
LOGGER.debug("No validator is configured for the LDAP connection pool of [{}]", l.getLdapUrl());
break;
case "search":
default:
final SearchRequest searchRequest = new SearchRequest();
searchRequest.setBaseDn(l.getValidator().getBaseDn());
searchRequest.setSearchFilter(new SearchFilter(l.getValidator().getSearchFilter()));
searchRequest.setReturnAttributes(ReturnAttributes.NONE.value());
searchRequest.setSearchScope(l.getValidator().getScope());
searchRequest.setSizeLimit(1L);
searchRequest.setReferralHandler(new SearchReferralHandler());
cp.setValidator(new SearchValidator(searchRequest));
break;
}
cp.setFailFastInitialize(l.isFailFast());
LOGGER.debug("Initializing ldap connection pool for [{}] and bindDn [{}]", l.getLdapUrl(), l.getBindDn());
cp.initialize();
return cp;
}
/**
* New pooled connection factory pooled connection factory.
*
* @param l the ldap properties
* @return the pooled connection factory
*/
public static PooledConnectionFactory newPooledConnectionFactory(final AbstractLdapProperties l) {
final ConnectionPool cp = newBlockingConnectionPool(l);
return new PooledConnectionFactory(cp);
}
/**
* New duration. If the provided length is duration,
* it will be parsed accordingly, or if it's a numeric value
* it will be pared as a duration assuming it's provided as seconds.
*
* @param length the length in seconds.
* @return the duration
*/
public static Duration newDuration(final String length) {
try {
if (NumberUtils.isCreatable(length)) {
return Duration.ofSeconds(Long.valueOf(length));
}
return Duration.parse(length);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
/**
* New ticket registry cipher executor cipher executor.
*
* @param registry the registry
* @return the cipher executor
*/
public static CipherExecutor newTicketRegistryCipherExecutor(final CryptographyProperties registry) {
return newTicketRegistryCipherExecutor(registry, false);
}
/**
* New ticket registry cipher executor cipher executor.
*
* @param registry the registry
* @param forceIfBlankKeys the force if blank keys
* @return the cipher executor
*/
public static CipherExecutor newTicketRegistryCipherExecutor(final CryptographyProperties registry, final boolean forceIfBlankKeys) {
if ((StringUtils.isNotBlank(registry.getEncryption().getKey())
&& StringUtils.isNotBlank(registry.getEncryption().getKey()))
|| forceIfBlankKeys) {
return new DefaultTicketCipherExecutor(
registry.getEncryption().getKey(),
registry.getSigning().getKey(),
registry.getAlg(),
registry.getSigning().getKeySize(),
registry.getEncryption().getKeySize());
}
LOGGER.debug("Ticket registry encryption/signing is turned off. This MAY NOT be safe in a "
+ "clustered production environment. "
+ "Consider using other choices to handle encryption, signing and verification of "
+ "ticket registry tickets, and verify the chosen ticket registry does support this behavior.");
return NoOpCipherExecutor.getInstance();
}
/**
* Builds a new request.
*
* @param baseDn the base dn
* @param filter the filter
* @return the search request
*/
public static SearchRequest newSearchRequest(final String baseDn, final SearchFilter filter) {
final SearchRequest sr = new SearchRequest(baseDn, filter);
sr.setBinaryAttributes(ReturnAttributes.ALL_USER.value());
sr.setReturnAttributes(ReturnAttributes.ALL_USER.value());
sr.setSearchScope(SearchScope.SUBTREE);
return sr;
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery) {
return newSearchFilter(filterQuery, Collections.emptyList());
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @param params the username
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery, final List<String> params) {
return newSearchFilter(filterQuery, LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, params);
}
/**
* Constructs a new search filter using {@link SearchExecutor#searchFilter} as a template and
* the username as a parameter.
*
* @param filterQuery the query filter
* @param paramName the param name
* @param params the username
* @return Search filter with parameters applied.
*/
public static SearchFilter newSearchFilter(final String filterQuery, final String paramName, final List<String> params) {
final SearchFilter filter = new SearchFilter();
filter.setFilter(filterQuery);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
if (filter.getFilter().contains("{" + i + '}')) {
filter.setParameter(i, params.get(i));
} else {
filter.setParameter(paramName, params.get(i));
}
}
}
LOGGER.debug("Constructed LDAP search filter [{}]", filter.format());
return filter;
}
/**
* New search executor search executor.
*
* @param baseDn the base dn
* @param filterQuery the filter query
* @param params the params
* @return the search executor
*/
public static SearchExecutor newSearchExecutor(final String baseDn, final String filterQuery, final List<String> params) {
final SearchExecutor executor = new SearchExecutor();
executor.setBaseDn(baseDn);
executor.setSearchFilter(newSearchFilter(filterQuery, params));
executor.setReturnAttributes(ReturnAttributes.ALL.value());
executor.setSearchScope(SearchScope.SUBTREE);
return executor;
}
/**
* New search executor search executor.
*
* @param baseDn the base dn
* @param filterQuery the filter query
* @return the search executor
*/
public static SearchExecutor newSearchExecutor(final String baseDn, final String filterQuery) {
return newSearchExecutor(baseDn, filterQuery, Collections.emptyList());
}
/**
* New mongo db client options factory bean.
*
* @param mongo the mongo properties.
* @return the mongo client options factory bean
*/
public static MongoClientOptionsFactoryBean newMongoDbClientOptionsFactoryBean(final AbstractMongoInstanceProperties mongo) {
try {
final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
bean.setWriteConcern(WriteConcern.valueOf(mongo.getWriteConcern()));
bean.setHeartbeatConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setHeartbeatSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setMaxConnectionLifeTime(mongo.getConns().getLifetime());
bean.setSocketKeepAlive(mongo.isSocketKeepAlive());
bean.setMaxConnectionIdleTime(Long.valueOf(mongo.getIdleTimeout()).intValue());
bean.setConnectionsPerHost(mongo.getConns().getPerHost());
bean.setSocketTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.setConnectTimeout(Long.valueOf(mongo.getTimeout()).intValue());
bean.afterPropertiesSet();
return bean;
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
/**
* New mongo db client options.
*
* @param mongo the mongo
* @return the mongo client options
*/
public static MongoClientOptions newMongoDbClientOptions(final AbstractMongoInstanceProperties mongo) {
try {
return newMongoDbClientOptionsFactoryBean(mongo).getObject();
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
/**
* New mongo db client.
*
* @param mongo the mongo
* @return the mongo
*/
public static Mongo newMongoDbClient(final AbstractMongoInstanceProperties mongo) {
return new MongoClient(new ServerAddress(
mongo.getHost(),
mongo.getPort()),
Collections.singletonList(
MongoCredential.createCredential(
mongo.getUserId(),
mongo.getDatabaseName(),
mongo.getPassword().toCharArray())),
newMongoDbClientOptions(mongo));
}
}
|
Update Beans.java
timeout millis
|
core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/support/Beans.java
|
Update Beans.java
|
|
Java
|
apache-2.0
|
08186bc948113942170943b3f25ea9bc2e6db2c9
| 0
|
rhdunn/xquery-intellij-plugin,rhdunn/xquery-intellij-plugin
|
/*
* Copyright (C) 2016 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.tests.lexer;
import com.intellij.lexer.Lexer;
import com.intellij.psi.tree.IElementType;
import junit.framework.TestCase;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryLexer;
import uk.co.reecedunn.intellij.plugin.xquery.tests.Specification;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.expectThrows;
public class XQueryLexerTest extends TestCase {
// region Lexer Test Helpers
private void matchToken(Lexer lexer, String text, int state, int start, int end, IElementType type) {
assertThat(lexer.getTokenText(), is(text));
assertThat(lexer.getState(), is(state));
assertThat(lexer.getTokenStart(), is(start));
assertThat(lexer.getTokenEnd(), is(end));
assertThat(lexer.getTokenType(), is(type));
if (lexer.getTokenType() == null) {
assertThat(lexer.getBufferEnd(), is(start));
assertThat(lexer.getBufferEnd(), is(end));
}
lexer.advance();
}
private void matchSingleToken(Lexer lexer, String text, int state, IElementType type) {
final int length = text.length();
lexer.start(text);
matchToken(lexer, text, 0, 0, length, type);
matchToken(lexer, "", state, length, length, null);
}
private void matchSingleToken(Lexer lexer, String text, IElementType type) {
matchSingleToken(lexer, text, 0, type);
}
// endregion
// region Lexer :: Invalid State
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void testInvalidState() {
Lexer lexer = new XQueryLexer();
AssertionError e = expectThrows(AssertionError.class, () -> lexer.start("123", 0, 3, -1));
assertThat(e.getMessage(), is("Invalid state: -1"));
}
// endregion
// region Lexer :: Empty Stack In Advance
public void testEmptyStackInAdvance() {
Lexer lexer = new XQueryLexer();
lexer.start("\"Hello World\"");
lexer.advance();
assertThat(lexer.getState(), is(1));
lexer.start("} {\"");
matchToken(lexer, "}", 0, 0, 1, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 1, 2, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "{", 0, 2, 3, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "\"", 0, 3, 4, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 4, 4, null);
}
// endregion
// region Lexer :: Empty Stack In Pop State
public void testEmptyStackInPopState() {
Lexer lexer = new XQueryLexer();
lexer.start("} } ");
matchToken(lexer, "}", 0, 0, 1, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 1, 2, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "}", 0, 2, 3, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region Lexer :: Empty Buffer
public void testEmptyBuffer() {
Lexer lexer = new XQueryLexer();
lexer.start("");
matchToken(lexer, "", 0, 0, 0, null);
}
// endregion
// region Lexer :: Bad Characters
public void testBadCharacters() {
Lexer lexer = new XQueryLexer();
lexer.start("~\uFFFE\u0000\uFFFF");
matchToken(lexer, "~", 0, 0, 1, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\uFFFE", 0, 1, 2, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\u0000", 0, 2, 3, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\uFFFF", 0, 3, 4, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: VersionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VersionDecl")
public void testVersionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "xquery", XQueryTokenType.K_XQUERY);
matchSingleToken(lexer, "version", XQueryTokenType.K_VERSION);
matchSingleToken(lexer, "encoding", XQueryTokenType.K_ENCODING);
}
// endregion
// region XQuery 1.0 :: ModuleDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ModuleDecl")
public void testModuleDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "module", XQueryTokenType.K_MODULE);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: Separator
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Separator")
public void testSeparator() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ";", XQueryTokenType.SEPARATOR);
}
// endregion
// region XQuery 1.0 :: NamespaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-NamespaceDecl")
public void testNamespaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: BoundarySpaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-BoundarySpaceDecl")
public void testBoundarySpaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "boundary-space", XQueryTokenType.K_BOUNDARY_SPACE);
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
matchSingleToken(lexer, "strip", XQueryTokenType.K_STRIP);
}
// endregion
// region XQuery 1.0 :: DefaultNamespaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DefaultNamespaceDecl")
public void testDefaultNamespaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: OptionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OptionDecl")
public void testOptionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "option", XQueryTokenType.K_OPTION);
}
// endregion
// region XQuery 1.0 :: OrderingModeDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderingModeDecl")
public void testOrderingModeDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "ordering", XQueryTokenType.K_ORDERING);
matchSingleToken(lexer, "ordered", XQueryTokenType.K_ORDERED);
matchSingleToken(lexer, "unordered", XQueryTokenType.K_UNORDERED);
}
// endregion
// region XQuery 1.0 :: EmptyOrderDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-EmptyOrderDecl")
public void testEmptyOrderDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "order", XQueryTokenType.K_ORDER);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
matchSingleToken(lexer, "greatest", XQueryTokenType.K_GREATEST);
matchSingleToken(lexer, "least", XQueryTokenType.K_LEAST);
}
// endregion
// region XQuery 1.0 :: CopyNamespacesDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CopyNamespacesDecl")
public void testCopyNamespacesDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "copy-namespaces", XQueryTokenType.K_COPY_NAMESPACES);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: PreserveMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PreserveMode")
public void testPreserveMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
matchSingleToken(lexer, "no-preserve", XQueryTokenType.K_NO_PRESERVE);
}
// endregion
// region XQuery 1.0 :: InheritMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-InheritMode")
public void testInheritMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "inherit", XQueryTokenType.K_INHERIT);
matchSingleToken(lexer, "no-inherit", XQueryTokenType.K_NO_INHERIT);
}
// endregion
// region XQuery 1.0 :: DefaultCollationDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DefaultCollationDecl")
public void testDefaultCollationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 1.0 :: BaseURIDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-BaseURIDecl")
public void testBaseURIDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "base-uri", XQueryTokenType.K_BASE_URI);
}
// endregion
// region XQuery 1.0 :: SchemaImport
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaImport")
public void testSchemaImport() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "import", XQueryTokenType.K_IMPORT);
matchSingleToken(lexer, "schema", XQueryTokenType.K_SCHEMA);
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: SchemaPrefix
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaPrefix")
public void testSchemaPrefix() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
}
// endregion
// region XQuery 1.0 :: ModuleImport
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ModuleImport")
public void testModuleImport() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "import", XQueryTokenType.K_IMPORT);
matchSingleToken(lexer, "module", XQueryTokenType.K_MODULE);
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: VarDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VarDecl")
public void testVarDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "variable", XQueryTokenType.K_VARIABLE);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region XQuery 1.0 :: ConstructionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ConstructionDecl")
public void testConstructionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "construction", XQueryTokenType.K_CONSTRUCTION);
matchSingleToken(lexer, "strip", XQueryTokenType.K_STRIP);
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
}
// endregion
// region XQuery 1.0 :: FunctionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FunctionDecl")
public void testFunctionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region XQuery 1.0 :: ParamList
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ParamList")
public void testParamList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: Param
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Param")
public void testParam() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-EnclosedExpr")
public void testEnclosedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: Expr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Expr")
public void testExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: FLWORExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FLWORExpr")
public void testFLWORExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: ForClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ForClause")
public void testForClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "for", XQueryTokenType.K_FOR);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: PositionalVar
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PositionalVar")
public void testPositionalVar() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: LetClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-LetClause")
public void testLetClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "let", XQueryTokenType.K_LET);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: WhereClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-WhereClause")
public void testWhereClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "where", XQueryTokenType.K_WHERE);
}
// endregion
// region XQuery 1.0 :: OrderByClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderByClause")
public void testOrderByClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "stable", XQueryTokenType.K_STABLE);
matchSingleToken(lexer, "order", XQueryTokenType.K_ORDER);
matchSingleToken(lexer, "by", XQueryTokenType.K_BY);
}
// endregion
// region XQuery 1.0 :: OrderSpecList
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderSpecList")
public void testOrderSpecList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: OrderModifier
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderModifier")
public void testOrderModifier() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "ascending", XQueryTokenType.K_ASCENDING);
matchSingleToken(lexer, "descending", XQueryTokenType.K_DESCENDING);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
matchSingleToken(lexer, "greatest", XQueryTokenType.K_GREATEST);
matchSingleToken(lexer, "least", XQueryTokenType.K_LEAST);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 1.0 :: QuantifiedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-QuantifiedExpr")
public void testQuantifiedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "some", XQueryTokenType.K_SOME);
matchSingleToken(lexer, "every", XQueryTokenType.K_EVERY);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "satisfies", XQueryTokenType.K_SATISFIES);
}
// endregion
// region XQuery 1.0 :: TypeswitchExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TypeswitchExpr")
public void testTypeswitchExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "typeswitch", XQueryTokenType.K_TYPESWITCH);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: CaseClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CaseClause")
public void testCaseClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "case", XQueryTokenType.K_CASE);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: IfExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-IfExpr")
public void testIfExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "if", XQueryTokenType.K_IF);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "then", XQueryTokenType.K_THEN);
matchSingleToken(lexer, "else", XQueryTokenType.K_ELSE);
}
// endregion
// region XQuery 1.0 :: OrExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrExpr")
public void testOrExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "or", XQueryTokenType.K_OR);
}
// endregion
// region XQuery 1.0 :: AndExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AndExpr")
public void testAndExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "and", XQueryTokenType.K_AND);
}
// endregion
// region XQuery 1.0 :: RangeExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-RangeExpr")
public void testRangeExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "to", XQueryTokenType.K_TO);
}
// endregion
// region XQuery 1.0 :: AdditiveExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AdditiveExpr")
public void testAdditiveExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
matchSingleToken(lexer, "-", XQueryTokenType.MINUS);
}
// endregion
// region XQuery 1.0 :: MultiplicativeExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-MultiplicativeExpr")
public void testMultiplicativeExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, "div", XQueryTokenType.K_DIV);
matchSingleToken(lexer, "idiv", XQueryTokenType.K_IDIV);
matchSingleToken(lexer, "mod", XQueryTokenType.K_MOD);
}
// endregion
// region XQuery 1.0 :: UnionExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnionExpr")
public void testUnionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "union", XQueryTokenType.K_UNION);
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 1.0 :: IntersectExceptExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-IntersectExceptExpr")
public void testIntersectExceptExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "intersect", XQueryTokenType.K_INTERSECT);
matchSingleToken(lexer, "except", XQueryTokenType.K_EXCEPT);
}
// endregion
// region XQuery 1.0 :: InstanceofExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-InstanceofExpr")
public void testInstanceofExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "instance", XQueryTokenType.K_INSTANCE);
matchSingleToken(lexer, "of", XQueryTokenType.K_OF);
}
// endregion
// region XQuery 1.0 :: TreatExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TreatExpr")
public void testTreatExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "treat", XQueryTokenType.K_TREAT);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: CastableExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CastableExpr")
public void testCastableExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "castable", XQueryTokenType.K_CASTABLE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: CastExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CastExpr")
public void testCastExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "cast", XQueryTokenType.K_CAST);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: UnaryExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnaryExpr")
public void testUnaryExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
matchSingleToken(lexer, "-", XQueryTokenType.MINUS);
lexer.start("++");
matchToken(lexer, "+", 0, 0, 1, XQueryTokenType.PLUS);
matchToken(lexer, "+", 0, 1, 2, XQueryTokenType.PLUS);
matchToken(lexer, "", 0, 2, 2, null);
lexer.start("--");
matchToken(lexer, "-", 0, 0, 1, XQueryTokenType.MINUS);
matchToken(lexer, "-", 0, 1, 2, XQueryTokenType.MINUS);
matchToken(lexer, "", 0, 2, 2, null);
}
// endregion
// region XQuery 1.0 :: GeneralComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-GeneralComp")
public void testGeneralComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
matchSingleToken(lexer, "!=", XQueryTokenType.NOT_EQUAL);
matchSingleToken(lexer, "<", XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<=", XQueryTokenType.LESS_THAN_OR_EQUAL);
matchSingleToken(lexer, ">", XQueryTokenType.GREATER_THAN);
matchSingleToken(lexer, ">=", XQueryTokenType.GREATER_THAN_OR_EQUAL);
}
// endregion
// region XQuery 1.0 :: ValueComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValueComp")
public void testValueComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "eq", XQueryTokenType.K_EQ);
matchSingleToken(lexer, "ne", XQueryTokenType.K_NE);
matchSingleToken(lexer, "lt", XQueryTokenType.K_LT);
matchSingleToken(lexer, "le", XQueryTokenType.K_LE);
matchSingleToken(lexer, "gt", XQueryTokenType.K_GT);
matchSingleToken(lexer, "ge", XQueryTokenType.K_GE);
}
// endregion
// region XQuery 1.0 :: NodeComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-NodeComp")
public void testNodeComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "is", XQueryTokenType.K_IS);
matchSingleToken(lexer, "<<", XQueryTokenType.NODE_BEFORE);
matchSingleToken(lexer, ">>", XQueryTokenType.NODE_AFTER);
}
// endregion
// region XQuery 1.0 :: ValidateExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidateExpr")
public void testValidateExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: ValidationMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidationMode")
public void testValidationMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "lax", XQueryTokenType.K_LAX);
matchSingleToken(lexer, "strict", XQueryTokenType.K_STRICT);
}
// endregion
// region XQuery 1.0 :: ExtensionExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ExtensionExpr")
public void testExtensionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: Pragma + PragmaContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Pragma")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PragmaContents")
public void testPragma() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(#", 8, XQueryTokenType.PRAGMA_BEGIN);
matchSingleToken(lexer, "#)", 0, XQueryTokenType.PRAGMA_END);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, "#", XQueryTokenType.FUNCTION_REF_OPERATOR);
lexer.start("(# let:for 6^gkgw~*#g#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, " ", 8, 2, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "let", 8, 4, 7, XQueryTokenType.NCNAME);
matchToken(lexer, ":", 9, 7, 8, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "for", 9, 8, 11, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 11, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*#g", 10, 13, 23, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 23, 25, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 25, 25, null);
lexer.start("(#let ##)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "#", 10, 6, 7, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 7, 9, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(#let 2");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2", 10, 6, 7, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 7, 7, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("(#let ");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 10, 6, 6, null);
lexer.start("(#let~~~#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "~~~", 9, 5, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 8, 10, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(#let~~~");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "~~~", 9, 5, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 8, 8, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("(#:let 2#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, ":", 8, 2, 3, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "let", 9, 3, 6, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2", 10, 7, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 8, 10, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(#~~~#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "~~~", 8, 2, 5, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 5, 7, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("(#~~~");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "~~~", 8, 2, 5, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
}
// endregion
// region XQuery 1.0 :: PathExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PathExpr")
public void testPathExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "/", XQueryTokenType.DIRECT_DESCENDANTS_PATH);
matchSingleToken(lexer, "//", XQueryTokenType.ALL_DESCENDANTS_PATH);
}
// endregion
// region XQuery 1.0 :: RelativePathExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-RelativePathExpr")
public void testRelativePathExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "/", XQueryTokenType.DIRECT_DESCENDANTS_PATH);
matchSingleToken(lexer, "//", XQueryTokenType.ALL_DESCENDANTS_PATH);
}
// endregion
// region XQuery 1.0 :: ForwardAxis
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ForwardAxis")
public void testForwardAxis() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "child", XQueryTokenType.K_CHILD);
matchSingleToken(lexer, "descendant", XQueryTokenType.K_DESCENDANT);
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "self", XQueryTokenType.K_SELF);
matchSingleToken(lexer, "descendant-or-self", XQueryTokenType.K_DESCENDANT_OR_SELF);
matchSingleToken(lexer, "following-sibling", XQueryTokenType.K_FOLLOWING_SIBLING);
matchSingleToken(lexer, "following", XQueryTokenType.K_FOLLOWING);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: AbbrevForwardStep
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AbbrevForwardStep")
public void testAbbrevForwardStep() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "@", XQueryTokenType.ATTRIBUTE_SELECTOR);
}
// endregion
// region XQuery 1.0 :: ReverseAxis
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ReverseAxis")
public void testReverseAxis() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "parent", XQueryTokenType.K_PARENT);
matchSingleToken(lexer, "ancestor", XQueryTokenType.K_ANCESTOR);
matchSingleToken(lexer, "preceding-sibling", XQueryTokenType.K_PRECEDING_SIBLING);
matchSingleToken(lexer, "preceding", XQueryTokenType.K_PRECEDING);
matchSingleToken(lexer, "ancestor-or-self", XQueryTokenType.K_ANCESTOR_OR_SELF);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: AbbrevReverseStep
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AbbrevReverseStep")
public void testAbbrevReverseStep() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "..", XQueryTokenType.PARENT_SELECTOR);
}
// endregion
// region XQuery 1.0 :: Wildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Wildcard")
public void testWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, ":", XQueryTokenType.QNAME_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: Predicate
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Predicate")
public void testPredicate() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "[", XQueryTokenType.PREDICATE_BEGIN);
matchSingleToken(lexer, "]", XQueryTokenType.PREDICATE_END);
}
// endregion
// region XQuery 1.0 :: VarRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VarRef")
public void testVarRef() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: ParenthesizedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ParenthesizedExpr")
public void testParenthesizedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: ContextItemExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ContextItemExpr")
public void testContextItemExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ".", XQueryTokenType.DOT);
}
// endregion
// region XQuery 1.0 :: OrderedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderedExpr")
public void testOrderedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "ordered", XQueryTokenType.K_ORDERED);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: UnorderedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnorderedExpr")
public void testUnorderedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "unordered", XQueryTokenType.K_UNORDERED);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: FunctionCall
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FunctionCall")
public void testFunctionCall() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: DirElemConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemConstructor")
public void testDirElemConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, ">", XQueryTokenType.GREATER_THAN);
matchSingleToken(lexer, "</", XQueryTokenType.CLOSE_XML_TAG);
matchSingleToken(lexer, "/>", XQueryTokenType.SELF_CLOSING_XML_TAG);
lexer.start("<one:two/>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, "/>", 11, 8, 10, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<one:two></one:two >");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "</", 17, 9, 11, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "one", 12, 11, 14, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 12, 14, 15, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 12, 15, 18, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 12, 18, 20, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, ">", 12, 20, 21, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 21, 21, null);
lexer.start("<one:two ></one:two>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 11, 8, 10, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, ">", 25, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "</", 17, 11, 13, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "one", 12, 13, 16, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 12, 16, 17, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 12, 17, 20, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 20, 21, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 21, 21, null);
lexer.start("<one:two//*/>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, "/", 11, 8, 9, XQueryTokenType.INVALID);
matchToken(lexer, "/", 11, 9, 10, XQueryTokenType.INVALID);
matchToken(lexer, "*", 11, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "/>", 11, 11, 13, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeList + DirAttributeValue
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirAttributeList")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirAttributeValue")
public void testDirAttributeList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
lexer.start("<one:two a:b = \"One\" c:d = 'Two' />");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 11, 8, 10, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "a", 25, 10, 11, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, ":", 25, 11, 12, XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR);
matchToken(lexer, "b", 25, 12, 13, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, " ", 25, 13, 15, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "=", 25, 15, 16, XQueryTokenType.XML_EQUAL);
matchToken(lexer, " ", 25, 16, 18, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "\"", 25, 18, 19, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 19, 22, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 22, 23, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, " ", 25, 23, 25, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "c", 25, 25, 26, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, ":", 25, 26, 27, XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR);
matchToken(lexer, "d", 25, 27, 28, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, " ", 25, 28, 30, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "=", 25, 30, 31, XQueryTokenType.XML_EQUAL);
matchToken(lexer, " ", 25, 31, 33, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "'", 25, 33, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "Two", 14, 34, 37, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 37, 38, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, " ", 25, 38, 40, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "/>", 25, 40, 42, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 42, 42, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + QuotAttrValueContent + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-QuotAttrValueContent")
public void testDirAttributeValue_QuotAttrValueContent() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One {2}<& \u3053\u3093\u3070\u3093\u306F.\"", 0, 18, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One ", 13, 1, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "{", 13, 5, 6, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 15, 6, 7, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 15, 7, 8, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 13, 8, 9, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 13, 9, 10, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 13, 10, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 17, 18, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 18, 18, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + AposAttrValueContent + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-AposAttrValueContent")
public void testDirAttributeValue_AposAttrValueContent() {
Lexer lexer = new XQueryLexer();
lexer.start("'One {2}<& \u3053\u3093\u3070\u3093\u306F.}'", 0, 19, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One ", 14, 1, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "{", 14, 5, 6, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 16, 6, 7, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 16, 7, 8, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 14, 8, 9, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 14, 9, 10, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 14, 10, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "}", 14, 17, 18, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "'", 14, 18, 19, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 19, 19, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + CommonContent
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommonContent")
public void testDirAttributeValue_CommonContent() {
Lexer lexer = new XQueryLexer();
lexer.start("\"{{}}\"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "{{", 13, 1, 3, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "}}", 13, 3, 5, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "\"", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
lexer.start("'{{}}'", 0, 6, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "{{", 14, 1, 3, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "}}", 14, 3, 5, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "'", 14, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testDirAttributeValue_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("\"One&abc;&aBc;&Abc;&ABC;&a4;&a;Two\"", 0, 35, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&abc;", 13, 4, 9, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 13, 9, 14, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 13, 14, 19, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 13, 19, 24, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 13, 24, 28, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 13, 28, 31, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 13, 31, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 34, 35, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 35, 35, null);
lexer.start("'One&abc;&aBc;&Abc;&ABC;&a4;&a;Two'", 0, 35, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&abc;", 14, 4, 9, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 14, 9, 14, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 14, 14, 19, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 14, 19, 24, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 14, 24, 28, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 14, 28, 31, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 14, 31, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 34, 35, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 35, 35, null);
lexer.start("\"&\"", 0, 3, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 2, 3, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 3, 3, null);
lexer.start("\"&abc!\"", 0, 7, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&abc", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 6, 7, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 7, 7, null);
lexer.start("\"& \"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 2, 3, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
lexer.start("\"&", 0, 2, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 2, 2, null);
lexer.start("\"&abc", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&abc", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 5, null);
lexer.start("\"&;\"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&;", 13, 1, 3, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + EscapeQuot
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeQuot")
public void testDirAttributeValue_EscapeQuot() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One\"\"Two\"", 0, 10, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"\"", 13, 4, 6, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "Two", 13, 6, 9, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 9, 10, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + EscapeApos
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeApos")
public void testDirAttributeValue_EscapeApos() {
Lexer lexer = new XQueryLexer();
lexer.start("'One''Two'", 0, 10, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "''", 14, 4, 6, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "Two", 14, 6, 9, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 9, 10, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirAttributeValue_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"OneTwo\"", 0, 13, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 13, 4, 9, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 13, 9, 12, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 12, 13, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 13, 13, null);
lexer.start("'OneTwo'", 0, 13, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 14, 4, 9, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 14, 9, 12, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 12, 13, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 13, 13, null);
lexer.start("\"&#\"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
lexer.start("\"&# \"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
lexer.start("\"&#", 0, 3, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 3, 3, null);
lexer.start("\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 5, null);
lexer.start("\"&#;\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#;", 13, 1, 4, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirAttributeValue_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One ®ÜTwo\"", 0, 26, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, " ", 13, 4, 10, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "®", 13, 10, 16, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 13, 16, 22, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 13, 22, 25, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 25, 26, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 26, 26, null);
lexer.start("'One ®ÜTwo'", 0, 26, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, " ", 14, 4, 10, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "®", 14, 10, 16, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 14, 16, 22, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 14, 22, 25, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 25, 26, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 26, 26, null);
lexer.start("\"&#x\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
lexer.start("\"&#x \"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
lexer.start("\"&#x", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 4, 4, null);
lexer.start("\"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "", 13, 1, 6, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 6, 6, null);
lexer.start("\"&#x;G;g;&#xg2;\"", 0, 24, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x;", 13, 1, 5, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 9, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 13, 9, 11, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 13, 11, 15, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 13, 15, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&#x", 13, 17, 20, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 13, 20, 23, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 23, 24, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + ElementContentChar + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementContentChar")
public void testDirElemContent_ElementContentChar() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One {2}<& \u3053\u3093\u3070\u3093\u306F.}</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "{", 17, 7, 8, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 18, 8, 9, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 18, 9, 10, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 17, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 17, 11, 12, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 17, 12, 19, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "}", 17, 19, 20, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "</", 17, 20, 22, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 22, 23, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 23, 24, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirElemConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemConstructor")
public void testDirElemContent_DirElemConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One <b>Two</b> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<", 17, 7, 8, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "b", 11, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "Two", 17, 10, 13, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 13, 15, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "b", 12, 15, 16, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 16, 17, XQueryTokenType.END_XML_TAG);
matchToken(lexer, " Three", 17, 17, 23, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 23, 25, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 25, 26, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 26, 27, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 27, 27, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirCommentConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirCommentConstructor")
public void testDirElemContent_DirCommentConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<!<!-", 0, 5, 17);
matchToken(lexer, "<!", 17, 0, 2, XQueryTokenType.INVALID);
matchToken(lexer, "<!-", 17, 2, 5, XQueryTokenType.INVALID);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<a>One <!-- 2 --> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<!--", 17, 7, 11, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " 2 ", 19, 11, 14, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 19, 14, 17, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, " Three", 17, 17, 23, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 23, 25, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 25, 26, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 26, 27, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 27, 27, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CDataSection (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CDataSection")
public void testDirElemContent_CDataSection() {
Lexer lexer = new XQueryLexer();
lexer.start("<!<![<![C<![CD<![CDA<![CDAT<![CDATA", 0, 35, 17);
matchToken(lexer, "<!", 17, 0, 2, XQueryTokenType.INVALID);
matchToken(lexer, "<![", 17, 2, 5, XQueryTokenType.INVALID);
matchToken(lexer, "<![C", 17, 5, 9, XQueryTokenType.INVALID);
matchToken(lexer, "<![CD", 17, 9, 14, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDA", 17, 14, 20, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDAT", 17, 20, 27, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDATA", 17, 27, 35, XQueryTokenType.INVALID);
matchToken(lexer, "", 17, 35, 35, null);
lexer.start("<a>One <![CDATA[ 2 ]]> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<![CDATA[", 17, 7, 16, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " 2 ", 20, 16, 19, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 20, 19, 22, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, " Three", 17, 22, 28, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 28, 30, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 30, 31, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 31, 32, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 32, 32, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirPIConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIConstructor")
public void testDirElemContent_DirPIConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<a><?for 6^gkgw~*?g?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 23, 5, 8, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 8, 10, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*?g", 24, 10, 20, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "?>", 24, 20, 22, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 22, 24, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 24, 25, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 25, 26, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("<a><?for?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 23, 5, 8, XQueryTokenType.NCNAME);
matchToken(lexer, "?>", 23, 8, 10, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 10, 12, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 12, 13, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 13, 14, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<a><?*?$?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "*", 23, 5, 6, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?", 23, 6, 7, XQueryTokenType.INVALID);
matchToken(lexer, "$", 23, 7, 8, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?>", 23, 8, 10, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 10, 12, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 12, 13, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 13, 14, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<?a ?", 0, 5, 17);
matchToken(lexer, "<?", 17, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 23, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "?", 24, 4, 5, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<?a ", 0, 4, 17);
matchToken(lexer, "<?", 17, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 23, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 24, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CommonContent
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommonContent")
public void testDirElemContent_CommonContent() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>{{}}</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "{{", 17, 3, 5, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "}}", 17, 5, 7, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "</", 17, 7, 9, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 9, 10, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 11, 11, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PredefinedEntityRef")
public void testDirElemContent_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("<a>One&abc;&aBc;&Abc;&ABC;&a4;&a;Two</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "&abc;", 17, 6, 11, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 17, 11, 16, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 17, 16, 21, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 17, 21, 26, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 17, 26, 30, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 17, 30, 33, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 17, 33, 36, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 36, 38, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 38, 39, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 39, 40, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 40, 40, null);
lexer.start("<a>&</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 4, 6, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 6, 7, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 7, 8, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("<a>&abc!</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&abc", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 17, 7, 8, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 8, 10, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 10, 11, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 11, 12, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 12, 12, null);
lexer.start("<a>&</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 4, 6, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 6, 7, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 7, 8, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("<a>&");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 4, 4, null);
lexer.start("<a>&abc");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&abc", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 7, null);
lexer.start("<a>&;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&;", 17, 3, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 5, 7, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 7, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 9, 9, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirElemContent_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>OneTwo</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "", 17, 6, 11, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 17, 11, 14, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 14, 16, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 16, 17, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 17, 18, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 18, 18, null);
lexer.start("<a>&#</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 5, 7, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 7, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<a>&# </a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 17, 5, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<a>&#");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 7, null);
lexer.start("<a>&#;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#;", 17, 3, 6, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirElemContent_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One ®ÜTwo</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, " ", 17, 6, 12, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 17, 12, 18, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 17, 18, 24, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 17, 24, 27, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 27, 29, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 29, 30, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 30, 31, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 31, 31, null);
lexer.start("<a>&#x</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<a>&#x </a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 17, 6, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 7, 9, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 9, 10, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 11, 11, null);
lexer.start("<a>&#x");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 6, 6, null);
lexer.start("<a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 17, 3, 8, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 8, 8, null);
lexer.start("<a>&#x;G;g;&#xg2;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x;", 17, 3, 7, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 11, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 17, 11, 13, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "", 17, 13, 17, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 17, 17, 19, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "&#x", 17, 19, 22, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 17, 22, 25, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 25, 27, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 27, 28, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 28, 29, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 29, 29, null);
}
// endregion
// region XQuery 1.0 :: DirCommentConstructor + DirCommentContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentContents")
public void testDirCommentConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", 0, XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<!", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<!-", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<!--", 5, XQueryTokenType.XML_COMMENT_START_TAG);
// Unary Minus
lexer.start("--");
matchToken(lexer, "-", 0, 0, 1, XQueryTokenType.MINUS);
matchToken(lexer, "-", 0, 1, 2, XQueryTokenType.MINUS);
matchToken(lexer, "", 0, 2, 2, null);
matchSingleToken(lexer, "-->", XQueryTokenType.XML_COMMENT_END_TAG);
lexer.start("<!-- Test");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test", 5, 4, 9, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<!-- Test --");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test --", 5, 4, 12, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 12, 12, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 12, 12, null);
lexer.start("<!-- Test -->");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test ", 5, 4, 10, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 10, 13, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("<!--\nMultiline\nComment\n-->");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 5, 4, 23, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 23, 26, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("<!---");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "-", 5, 4, 5, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("<!----");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "--", 5, 4, 6, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 6, 6, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 6, 6, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentContents")
public void testDirCommentConstructor_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("<!-- Test", 4, 9, 5);
matchToken(lexer, " Test", 5, 4, 9, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<!-- Test -->", 4, 13, 5);
matchToken(lexer, " Test ", 5, 4, 10, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 10, 13, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: DirPIConstructor + DirPIContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIContents")
public void testDirPIConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<?", 21, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchSingleToken(lexer, "?>", 0, XQueryTokenType.PROCESSING_INSTRUCTION_END);
lexer.start("<?for 6^gkgw~*?g?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 21, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 5, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*?g", 22, 7, 17, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "?>", 22, 17, 19, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("<?for?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 21, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "?>", 21, 5, 7, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("<?*?$?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "*", 21, 2, 3, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?", 21, 3, 4, XQueryTokenType.INVALID);
matchToken(lexer, "$", 21, 4, 5, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?>", 21, 5, 7, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("<?a ?");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 21, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "?", 22, 4, 5, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("<?a ");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 21, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 22, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: CDataSection + CDataSectionContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSection")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSectionContents")
public void testCDataSection() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", 0, XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<!", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![C", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CD", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDA", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDAT", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDATA", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDATA[", 7, XQueryTokenType.CDATA_SECTION_START_TAG);
matchSingleToken(lexer, "]", XQueryTokenType.PREDICATE_END);
lexer.start("]]");
matchToken(lexer, "]", 0, 0, 1, XQueryTokenType.PREDICATE_END);
matchToken(lexer, "]", 0, 1, 2, XQueryTokenType.PREDICATE_END);
matchToken(lexer, "", 0, 2, 2, null);
matchSingleToken(lexer, "]]>", XQueryTokenType.CDATA_SECTION_END_TAG);
lexer.start("<![CDATA[ Test");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test", 7, 9, 14, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 14, 14, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<![CDATA[ Test ]]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test ]]", 7, 9, 17, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 17, 17, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 17, 17, null);
lexer.start("<![CDATA[ Test ]]>");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test ", 7, 9, 15, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 15, 18, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 18, 18, null);
lexer.start("<![CDATA[\nMultiline\nComment\n]]>");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 7, 9, 28, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 28, 31, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 31, 31, null);
lexer.start("<![CDATA[]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "]", 7, 9, 10, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 10, 10, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<![CDATA[]]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "]]", 7, 9, 11, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 11, 11, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 11, 11, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSection")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSectionContents")
public void testCDataSection_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("<![CDATA[ Test", 9, 14, 7);
matchToken(lexer, " Test", 7, 9, 14, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 14, 14, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<![CDATA[ Test ]]>", 9, 18, 7);
matchToken(lexer, " Test ", 7, 9, 15, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 15, 18, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 18, 18, null);
}
// endregion
// region XQuery 1.0 :: CompDocConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompDocConstructor")
public void testCompDocConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "document", XQueryTokenType.K_DOCUMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompElemConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompElemConstructor")
public void testCompElemConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompAttrConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompAttrConstructor")
public void testCompAttrConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompTextConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompTextConstructor")
public void testCompTextConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "text", XQueryTokenType.K_TEXT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompCommentConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompCommentConstructor")
public void testCompCommentConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "comment", XQueryTokenType.K_COMMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompPIConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompPIConstructor")
public void testCompPIConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "processing-instruction", XQueryTokenType.K_PROCESSING_INSTRUCTION);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: TypeDeclaration
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TypeDeclaration")
public void testTypeDeclaration() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: SequenceType
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SequenceType")
public void testSequenceType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "empty-sequence", XQueryTokenType.K_EMPTY_SEQUENCE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: OccurrenceIndicator
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OccurrenceIndicator")
public void testOccurrenceIndicator() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
}
// endregion
// region XQuery 1.0 :: ItemType
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ItemType")
public void testItemType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "item", XQueryTokenType.K_ITEM);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AnyKindTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AnyKindTest")
public void testAnyKindTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: DocumentTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DocumentTest")
public void testDocumentTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "document-node", XQueryTokenType.K_DOCUMENT_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: TextTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TextTest")
public void testTextTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "text", XQueryTokenType.K_TEXT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: CommentTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CommentTest")
public void testCommentTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "comment", XQueryTokenType.K_COMMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: PITest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PITest")
public void testPITest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "processing-instruction", XQueryTokenType.K_PROCESSING_INSTRUCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AttributeTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AttributeTest")
public void testAttributeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AttribNameOrWildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AttribNameOrWildcard")
public void testAttribNameOrWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
}
// endregion
// region XQuery 1.0 :: SchemaAttributeTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaAttributeTest")
public void testSchemaAttributeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "schema-attribute", XQueryTokenType.K_SCHEMA_ATTRIBUTE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: ElementTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementTest")
public void testElementTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
}
// endregion
// region XQuery 1.0 :: ElementNameOrWildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementNameOrWildcard")
public void testElementNameOrWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
}
// endregion
// region XQuery 1.0 :: SchemaElementTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaElementTest")
public void testSchemaElementTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "schema-element", XQueryTokenType.K_SCHEMA_ELEMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: IntegerLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-IntegerLiteral")
public void testIntegerLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("1234");
matchToken(lexer, "1234", 0, 0, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DecimalLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DecimalLiteral")
public void testDecimalLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("47.");
matchToken(lexer, "47.", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start("1.234");
matchToken(lexer, "1.234", 0, 0, 5, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start(".25");
matchToken(lexer, ".25", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start(".1.2");
matchToken(lexer, ".1", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, ".2", 0, 2, 4, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DoubleLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DoubleLiteral")
public void testDoubleLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("3e7 3e+7 3e-7");
matchToken(lexer, "3e7", 0, 0, 3, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "3e+7", 0, 4, 8, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "3e-7", 0, 9, 13, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("43E22 43E+22 43E-22");
matchToken(lexer, "43E22", 0, 0, 5, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "43E+22", 0, 6, 12, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 12, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "43E-22", 0, 13, 19, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("2.1e3 2.1e+3 2.1e-3");
matchToken(lexer, "2.1e3", 0, 0, 5, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2.1e+3", 0, 6, 12, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 12, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2.1e-3", 0, 13, 19, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("1.7E99 1.7E+99 1.7E-99");
matchToken(lexer, "1.7E99", 0, 0, 6, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1.7E+99", 0, 7, 14, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1.7E-99", 0, 15, 22, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 22, 22, null);
lexer.start(".22e42 .22e+42 .22e-42");
matchToken(lexer, ".22e42", 0, 0, 6, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".22e+42", 0, 7, 14, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".22e-42", 0, 15, 22, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 22, 22, null);
lexer.start(".8E2 .8E+2 .8E-2");
matchToken(lexer, ".8E2", 0, 0, 4, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".8E+2", 0, 5, 10, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".8E-2", 0, 11, 16, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start("1e 1e+ 1e-");
matchToken(lexer, "1", 0, 0, 1, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 2, 3, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 3, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e+", 3, 4, 6, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 7, 8, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e-", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("1E 1E+ 1E-");
matchToken(lexer, "1", 0, 0, 1, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 2, 3, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 3, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E+", 3, 4, 6, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 7, 8, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E-", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("8.9e 8.9e+ 8.9e-");
matchToken(lexer, "8.9", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e", 3, 3, 4, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 5, 8, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e+", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 11, 14, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e-", 3, 14, 16, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start("8.9E 8.9E+ 8.9E-");
matchToken(lexer, "8.9", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E", 3, 3, 4, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 5, 8, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E+", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 11, 14, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E-", 3, 14, 16, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start(".4e .4e+ .4e-");
matchToken(lexer, ".4", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e", 3, 2, 3, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 4, 6, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e+", 3, 6, 8, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 9, 11, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e-", 3, 11, 13, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start(".4E .4E+ .4E-");
matchToken(lexer, ".4", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E", 3, 2, 3, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 4, 6, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E+", 3, 6, 8, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 9, 11, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E-", 3, 11, 13, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 13, 13, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DoubleLiteral")
public void testDoubleLiteral_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("1e", 1, 2, 3);
matchToken(lexer, "e", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 2, 2, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
public void testStringLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 1, null);
lexer.start("\"Hello World\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "Hello World", 1, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 2, 1, 1, null);
lexer.start("'Hello World'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "Hello World", 2, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
public void testStringLiteral_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("\"Hello World\"", 1, 13, 1);
matchToken(lexer, "Hello World", 1, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'Hello World'", 1, 13, 2);
matchToken(lexer, "Hello World", 2, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testStringLiteral_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("\"One&abc;&aBc;&Abc;&ABC;&a4;&a;Two\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 1, 4, 9, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 1, 9, 14, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 1, 14, 19, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 1, 19, 24, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 1, 24, 28, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 1, 28, 31, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 1, 31, 34, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 34, 35, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 35, 35, null);
lexer.start("'One&abc;&aBc;&Abc;&ABC;&a4;&a;Two'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 2, 4, 9, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 2, 9, 14, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 2, 14, 19, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 2, 19, 24, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 2, 24, 28, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 2, 28, 31, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 2, 31, 34, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 34, 35, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 35, 35, null);
lexer.start("\"&\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 2, 3, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start("\"&abc!\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&abc", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 1, 5, 6, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 6, 7, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("\"& \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 2, 3, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("\"&");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 2, 2, null);
lexer.start("\"&abc");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&abc", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 5, null);
lexer.start("\"&;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&;", 1, 1, 3, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("&");
matchToken(lexer, "&", 0, 0, 1, XQueryTokenType.ENTITY_REFERENCE_NOT_IN_STRING);
matchToken(lexer, "", 0, 1, 1, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + EscapeQuot
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeQuot")
public void testStringLiteral_EscapeQuot() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One\"\"Two\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"\"", 1, 4, 6, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "Two", 1, 6, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 9, 10, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + EscapeApos
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeApos")
public void testStringLiteral_EscapeApos() {
Lexer lexer = new XQueryLexer();
lexer.start("'One''Two'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "''", 2, 4, 6, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "Two", 2, 6, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 9, 10, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testStringLiteral_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"OneTwo\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 1, 4, 9, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 1, 9, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'OneTwo'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 2, 4, 9, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 2, 9, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("\"&#\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("\"&# \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 3, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("\"&#");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 3, 3, null);
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 5, null);
lexer.start("\"&#;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#;", 1, 1, 4, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testStringLiteral_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One ®ÜTwo\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 1, 4, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 1, 10, 16, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 1, 16, 22, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 1, 22, 25, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 25, 26, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("'One ®ÜTwo'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 2, 4, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 2, 10, 16, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 2, 16, 22, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 2, 22, 25, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 25, 26, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("\"&#x\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("\"&#x \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 4, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 5, 6, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("\"&#x");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 4, 4, null);
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 6, 6, null);
lexer.start("\"&#x;G;g;&#xg2;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x;", 1, 1, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 9, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 1, 9, 11, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 1, 11, 15, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 1, 15, 17, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&#x", 1, 17, 20, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 1, 20, 23, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 23, 24, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: Comment + CommentContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-Comment")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommentContents")
public void testComment() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(:", 4, XQueryTokenType.COMMENT_START_TAG);
matchSingleToken(lexer, ":)", 0, XQueryTokenType.COMMENT_END_TAG);
lexer.start("(: Test :");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Test :", 4, 2, 9, XQueryTokenType.COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(: Test :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Test ", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(::Test::)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, ":Test:", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(:\nMultiline\nComment\n:)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 4, 2, 21, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 21, 23, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 23, 23, null);
lexer.start("(: Outer (: Inner :) Outer :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Outer (: Inner :) Outer ", 4, 2, 27, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 27, 29, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 29, 29, null);
lexer.start("(: Outer ( : Inner :) Outer :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Outer ( : Inner ", 4, 2, 19, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 19, 21, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, " ", 0, 21, 22, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "Outer", 0, 22, 27, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 27, 28, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ":)", 0, 28, 30, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 30, 30, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-Comment")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommentContents")
public void testComment_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("(: Test :", 2, 9, 4);
matchToken(lexer, " Test :", 4, 2, 9, XQueryTokenType.COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(: Test :)", 2, 10, 4);
matchToken(lexer, " Test ", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: QName
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-QName")
@Specification(name="Namespaces in XML 1.0 3ed", reference="https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-QName")
public void testQName() {
Lexer lexer = new XQueryLexer();
lexer.start("one:two");
matchToken(lexer, "one", 0, 0, 3, XQueryTokenType.NCNAME);
matchToken(lexer, ":", 0, 3, 4, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "two", 0, 4, 7, XQueryTokenType.NCNAME);
matchToken(lexer, "", 0, 7, 7, null);
}
// endregion
// region XQuery 1.0 :: NCName
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-NCName")
@Specification(name="Namespaces in XML 1.0 3ed", reference="https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName")
public void testNCName() {
Lexer lexer = new XQueryLexer();
lexer.start("test x b2b F.G a-b g\u0330d");
matchToken(lexer, "test", 0, 0, 4, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "x", 0, 5, 6, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "b2b", 0, 7, 10, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "F.G", 0, 11, 14, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "a-b", 0, 15, 18, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 18, 19, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "g\u0330d", 0, 19, 22, XQueryTokenType.NCNAME);
matchToken(lexer, "", 0, 22, 22, null);
}
// endregion
// region XQuery 1.0 :: S
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-S")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-S")
public void testS() {
Lexer lexer = new XQueryLexer();
lexer.start(" ");
matchToken(lexer, " ", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\t");
matchToken(lexer, "\t", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\r");
matchToken(lexer, "\r", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\n");
matchToken(lexer, "\n", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start(" \t \r\n ");
matchToken(lexer, " \t \r\n ", 0, 0, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 9, 9, null);
}
// endregion
// region XQuery 3.0 :: DecimalFormatDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-DecimalFormatDecl")
public void testDecimalFormatDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "decimal-format", XQueryTokenType.K_DECIMAL_FORMAT);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 3.0 :: DFPropertyName
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-DFPropertyName")
public void testDFPropertyName() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "decimal-separator", XQueryTokenType.K_DECIMAL_SEPARATOR);
matchSingleToken(lexer, "grouping-separator", XQueryTokenType.K_GROUPING_SEPARATOR);
matchSingleToken(lexer, "infinity", XQueryTokenType.K_INFINITY);
matchSingleToken(lexer, "minus-sign", XQueryTokenType.K_MINUS_SIGN);
matchSingleToken(lexer, "NaN", XQueryTokenType.K_NAN);
matchSingleToken(lexer, "percent", XQueryTokenType.K_PERCENT);
matchSingleToken(lexer, "per-mille", XQueryTokenType.K_PER_MILLE);
matchSingleToken(lexer, "zero-digit", XQueryTokenType.K_ZERO_DIGIT);
matchSingleToken(lexer, "digit", XQueryTokenType.K_DIGIT);
matchSingleToken(lexer, "pattern-separator", XQueryTokenType.K_PATTERN_SEPARATOR);
}
// endregion
// region XQuery 3.0 :: AnnotationDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AnnotationDecl")
public void testAnnotationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
}
// endregion
// region XQuery 3.0 :: Annotation
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-Annotation")
public void testAnnotation() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "%", XQueryTokenType.ANNOTATION_INDICATOR);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: ContextItemDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ContextItemDecl")
public void testContextItemDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "context", XQueryTokenType.K_CONTEXT);
matchSingleToken(lexer, "item", XQueryTokenType.K_ITEM);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
}
// endregion
// region XQuery 3.0 :: AllowingEmpty
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AllowingEmpty")
public void testAllowingEmpty() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "allowing", XQueryTokenType.K_ALLOWING);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
}
// endregion
// region XQuery 3.0 :: WindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowClause")
public void testWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "for", XQueryTokenType.K_FOR);
}
// endregion
// region XQuery 3.0 :: TumblingWindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TumblingWindowClause")
public void testTumblingWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "tumbling", XQueryTokenType.K_TUMBLING);
matchSingleToken(lexer, "window", XQueryTokenType.K_WINDOW);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
}
// endregion
// region XQuery 3.0 :: SlidingWindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SlidingWindowClause")
public void testSlidingWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "sliding", XQueryTokenType.K_SLIDING);
matchSingleToken(lexer, "window", XQueryTokenType.K_WINDOW);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
}
// endregion
// region XQuery 3.0 :: WindowStartCondition
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowStartCondition")
public void testWindowStartCondition() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "start", XQueryTokenType.K_START);
matchSingleToken(lexer, "when", XQueryTokenType.K_WHEN);
}
// endregion
// region XQuery 3.0 :: WindowEndCondition
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowEndCondition")
public void testWindowEndCondition() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "only", XQueryTokenType.K_ONLY);
matchSingleToken(lexer, "end", XQueryTokenType.K_END);
matchSingleToken(lexer, "when", XQueryTokenType.K_WHEN);
}
// endregion
// region XQuery 3.0 :: WindowVars
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowVars")
public void testWindowVars() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "previous", XQueryTokenType.K_PREVIOUS);
matchSingleToken(lexer, "next", XQueryTokenType.K_NEXT);
}
// endregion
// region XQuery 3.0 :: CountClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CountClause")
public void testCountClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "count", XQueryTokenType.K_COUNT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 3.0 :: GroupByClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupByClause")
public void testGroupByClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "group", XQueryTokenType.K_GROUP);
matchSingleToken(lexer, "by", XQueryTokenType.K_BY);
}
// endregion
// region XQuery 3.0 :: GroupingSpecList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingSpecList")
public void testGroupingSpecList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 3.0 :: GroupingSpec
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingSpec")
public void testGroupingSpec() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 3.0 :: GroupingVariable
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingVariable")
public void testGroupingVariable() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 3.0 :: ReturnClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ReturnClause")
public void testReturnClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SwitchExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SwitchExpr")
public void testSwitchExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "switch", XQueryTokenType.K_SWITCH);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SwitchCaseClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SwitchCaseClause")
public void testSwitchCaseClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "case", XQueryTokenType.K_CASE);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SequenceTypeUnion
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SequenceTypeUnion")
public void testSequenceTypeUnion() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 3.0 :: TryClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TryClause")
public void testTryClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "try", XQueryTokenType.K_TRY);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: CatchClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CatchClause")
public void testCatchClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "catch", XQueryTokenType.K_CATCH);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: CatchErrorList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CatchErrorList")
public void testCatchErrorList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 3.0 :: StringConcatExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-StringConcatExpr")
public void testStringConcatExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "||", XQueryTokenType.CONCATENATION);
}
// endregion
// region XQuery 3.0 :: ValidateExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidateExpr")
public void testValidateExpr_Type() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "type", XQueryTokenType.K_TYPE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: SimpleMapExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SimpleMapExpr")
public void testSimpleMapExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "!", XQueryTokenType.MAP_OPERATOR);
}
// endregion
// region XQuery 3.0 :: ArgumentList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ArgumentList")
public void testArgumentList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: ArgumentPlaceholder
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ArgumentPlaceholder")
public void testArgumentPlaceholder() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
}
// endregion
// region XQuery 3.0 :: CompNamespaceConstructor
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CompNamespaceConstructor")
public void testCompNamespaceConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: NamedFunctionRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-NamedFunctionRef")
public void testNamedFunctionRef() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "#", XQueryTokenType.FUNCTION_REF_OPERATOR);
}
// endregion
// region XQuery 3.0 :: InlineFunctionExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-InlineFunctionExpr")
public void testInlineFunctionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 3.0 :: NamespaceNodeTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-NamespaceNodeTest")
public void testNamespaceNodeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace-node", XQueryTokenType.K_NAMESPACE_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: AnyFunctionTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AnyFunctionTest")
public void testAnyFunctionTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: TypedFunctionTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TypedFunctionTest")
public void testTypedFunctionTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 3.0 :: ParenthesizedItemType
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ParenthesizedItemType")
public void testParenthesizedItemType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
public void testBracedURILiteral() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "Q", XQueryTokenType.NCNAME);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 2, null);
lexer.start("Q{Hello World}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "Hello World", 26, 2, 13, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 13, 14, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 14, 14, null);
// NOTE: "", '', {{ and }} are used as escaped characters in string and attribute literals.
lexer.start("Q{A\"\"B''C{{D}}E}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "A\"\"B''C", 26, 2, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "{", 26, 9, 10, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "{", 26, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "D", 26, 11, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 12, 13, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "}", 0, 13, 14, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "E", 0, 14, 15, XQueryTokenType.NCNAME);
matchToken(lexer, "}", 0, 15, 16, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "", 0, 16, 16, null);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral + PredefinedEntityRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testBracedURILiteral_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("Q{One&abc;&aBc;&Abc;&ABC;&a4;&a;Two}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 26, 5, 10, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 26, 10, 15, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 26, 15, 20, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 26, 20, 25, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 26, 25, 29, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 26, 29, 32, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 26, 32, 35, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 35, 36, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 36, 36, null);
lexer.start("Q{&}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 3, 4, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("Q{&abc!}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&abc", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 26, 6, 7, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 7, 8, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("Q{& }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 3, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("Q{&");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 3, 3, null);
lexer.start("Q{&abc");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&abc", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 6, null);
lexer.start("Q{&;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&;", 26, 2, 4, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral + CharRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testBracedURILiteral_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("Q{OneTwo}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 26, 5, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 26, 10, 13, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 13, 14, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("Q{&#}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("Q{&# }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 4, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("Q{&#");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 4, 4, null);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 6, null);
lexer.start("Q{&#;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#;", 26, 2, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
}
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testBracedURILiteral_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("Q{One ®ÜTwo}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 26, 5, 11, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 26, 11, 17, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 26, 17, 23, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 26, 23, 26, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 26, 27, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 27, 27, null);
lexer.start("Q{&#x}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("Q{&#x }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 5, 6, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 6, 7, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("Q{&#x");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 5, 5, null);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 7, 7, null);
lexer.start("Q{&#x;G;g;&#xg2;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x;", 26, 2, 6, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 10, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 26, 10, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 26, 12, 16, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 26, 16, 18, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&#x", 26, 18, 21, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 26, 21, 24, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 24, 25, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 25, 25, null);
}
// endregion
// region Update Facility 1.0 :: FunctionDecl
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-FunctionDecl")
public void testFunctionDecl_UpdateFacility10() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "updating", XQueryTokenType.K_UPDATING);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region Update Facility 1.0 :: RevalidationDecl
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-RevalidationDecl")
public void testRevalidationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "revalidation", XQueryTokenType.K_REVALIDATION);
matchSingleToken(lexer, "strict", XQueryTokenType.K_STRICT);
matchSingleToken(lexer, "lax", XQueryTokenType.K_LAX);
matchSingleToken(lexer, "skip", XQueryTokenType.K_SKIP);
}
// endregion
// region Update Facility 1.0 :: InsertExprTargetChoice
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-InsertExprTargetChoice")
public void testInsertExprTargetChoice() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "first", XQueryTokenType.K_FIRST);
matchSingleToken(lexer, "last", XQueryTokenType.K_LAST);
matchSingleToken(lexer, "into", XQueryTokenType.K_INTO);
matchSingleToken(lexer, "after", XQueryTokenType.K_AFTER);
matchSingleToken(lexer, "before", XQueryTokenType.K_BEFORE);
}
// endregion
// region Update Facility 1.0 :: InsertExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-InsertExpr")
public void testInsertExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "insert", XQueryTokenType.K_INSERT);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "nodes", XQueryTokenType.K_NODES);
}
// endregion
// region Update Facility 1.0 :: DeleteExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-DeleteExpr")
public void testDeleteExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "delete", XQueryTokenType.K_DELETE);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "nodes", XQueryTokenType.K_NODES);
}
// endregion
// region Update Facility 1.0 :: ReplaceExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-ReplaceExpr")
public void testReplaceExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "replace", XQueryTokenType.K_REPLACE);
matchSingleToken(lexer, "value", XQueryTokenType.K_VALUE);
matchSingleToken(lexer, "of", XQueryTokenType.K_OF);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "with", XQueryTokenType.K_WITH);
}
// endregion
// region Update Facility 1.0 :: RenameExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-RenameExpr")
public void testRenameExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "rename", XQueryTokenType.K_RENAME);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region Update Facility 1.0 :: TransformExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-TransformExpr")
public void testTransformExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "copy", XQueryTokenType.K_COPY);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "modify", XQueryTokenType.K_MODIFY);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region Update Facility 3.0 :: CompatibilityAnnotation
@Specification(name="XQuery Update Facility 3.0", reference="https://www.w3.org/TR/2015/WD-xquery-update-30-20150219/#prod-xquery30-CompatibilityAnnotation")
public void testCompatibilityAnnotation() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "updating", XQueryTokenType.K_UPDATING);
}
// endregion
// region MarkLogic 6.0 :: CompatibilityAnnotation
public void testCompatibilityAnnotation_MarkLogic() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "private", XQueryTokenType.K_PRIVATE);
}
// endregion
// region MarkLogic 6.0 :: ValidateExpr
public void testValidateExpr_ValidateAs() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region MarkLogic 6.0 :: ForwardAxis
public void testForwardAxis_MarkLogic() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "property", XQueryTokenType.K_PROPERTY);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region MarkLogic 6.0 :: CompBinaryConstructor
public void testCompBinaryConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "binary", XQueryTokenType.K_BINARY);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region MarkLogic 6.0 :: BinaryKindTest
public void testBinaryKindTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "binary", XQueryTokenType.K_BINARY);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
}
|
src/test/java/uk/co/reecedunn/intellij/plugin/xquery/tests/lexer/XQueryLexerTest.java
|
/*
* Copyright (C) 2016 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.tests.lexer;
import com.intellij.lexer.Lexer;
import com.intellij.psi.tree.IElementType;
import junit.framework.TestCase;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryLexer;
import uk.co.reecedunn.intellij.plugin.xquery.tests.Specification;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.expectThrows;
public class XQueryLexerTest extends TestCase {
// region Lexer Test Helpers
private void matchToken(Lexer lexer, String text, int state, int start, int end, IElementType type) {
assertThat(lexer.getTokenText(), is(text));
assertThat(lexer.getState(), is(state));
assertThat(lexer.getTokenStart(), is(start));
assertThat(lexer.getTokenEnd(), is(end));
assertThat(lexer.getTokenType(), is(type));
if (lexer.getTokenType() == null) {
assertThat(lexer.getBufferEnd(), is(start));
assertThat(lexer.getBufferEnd(), is(end));
}
lexer.advance();
}
private void matchSingleToken(Lexer lexer, String text, int state, IElementType type) {
final int length = text.length();
lexer.start(text);
matchToken(lexer, text, 0, 0, length, type);
matchToken(lexer, "", state, length, length, null);
}
private void matchSingleToken(Lexer lexer, String text, IElementType type) {
matchSingleToken(lexer, text, 0, type);
}
// endregion
// region Lexer :: Invalid State
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void testInvalidState() {
Lexer lexer = new XQueryLexer();
AssertionError e = expectThrows(AssertionError.class, () -> lexer.start("123", 0, 3, -1));
assertThat(e.getMessage(), is("Invalid state: -1"));
}
// endregion
// region Lexer :: Empty Stack In Advance
public void testEmptyStackInAdvance() {
Lexer lexer = new XQueryLexer();
lexer.start("\"Hello World\"");
lexer.advance();
assertThat(lexer.getState(), is(1));
lexer.start("} {\"");
matchToken(lexer, "}", 0, 0, 1, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 1, 2, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "{", 0, 2, 3, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "\"", 0, 3, 4, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 4, 4, null);
}
// endregion
// region Lexer :: Empty Stack In Pop State
public void testEmptyStackInPopState() {
Lexer lexer = new XQueryLexer();
lexer.start("} } ");
matchToken(lexer, "}", 0, 0, 1, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 1, 2, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "}", 0, 2, 3, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region Lexer :: Empty Buffer
public void testEmptyBuffer() {
Lexer lexer = new XQueryLexer();
lexer.start("");
matchToken(lexer, "", 0, 0, 0, null);
}
// endregion
// region Lexer :: Bad Characters
public void testBadCharacters() {
Lexer lexer = new XQueryLexer();
lexer.start("~\uFFFE\u0000\uFFFF");
matchToken(lexer, "~", 0, 0, 1, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\uFFFE", 0, 1, 2, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\u0000", 0, 2, 3, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "\uFFFF", 0, 3, 4, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: VersionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VersionDecl")
public void testVersionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "xquery", XQueryTokenType.K_XQUERY);
matchSingleToken(lexer, "version", XQueryTokenType.K_VERSION);
matchSingleToken(lexer, "encoding", XQueryTokenType.K_ENCODING);
}
// endregion
// region XQuery 1.0 :: ModuleDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ModuleDecl")
public void testModuleDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "module", XQueryTokenType.K_MODULE);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: Separator
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Separator")
public void testSeparator() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ";", XQueryTokenType.SEPARATOR);
}
// endregion
// region XQuery 1.0 :: NamespaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-NamespaceDecl")
public void testNamespaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: BoundarySpaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-BoundarySpaceDecl")
public void testBoundarySpaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "boundary-space", XQueryTokenType.K_BOUNDARY_SPACE);
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
matchSingleToken(lexer, "strip", XQueryTokenType.K_STRIP);
}
// endregion
// region XQuery 1.0 :: DefaultNamespaceDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DefaultNamespaceDecl")
public void testDefaultNamespaceDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: OptionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OptionDecl")
public void testOptionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "option", XQueryTokenType.K_OPTION);
}
// endregion
// region XQuery 1.0 :: OrderingModeDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderingModeDecl")
public void testOrderingModeDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "ordering", XQueryTokenType.K_ORDERING);
matchSingleToken(lexer, "ordered", XQueryTokenType.K_ORDERED);
matchSingleToken(lexer, "unordered", XQueryTokenType.K_UNORDERED);
}
// endregion
// region XQuery 1.0 :: EmptyOrderDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-EmptyOrderDecl")
public void testEmptyOrderDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "order", XQueryTokenType.K_ORDER);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
matchSingleToken(lexer, "greatest", XQueryTokenType.K_GREATEST);
matchSingleToken(lexer, "least", XQueryTokenType.K_LEAST);
}
// endregion
// region XQuery 1.0 :: CopyNamespacesDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CopyNamespacesDecl")
public void testCopyNamespacesDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "copy-namespaces", XQueryTokenType.K_COPY_NAMESPACES);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: PreserveMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PreserveMode")
public void testPreserveMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
matchSingleToken(lexer, "no-preserve", XQueryTokenType.K_NO_PRESERVE);
}
// endregion
// region XQuery 1.0 :: InheritMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-InheritMode")
public void testInheritMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "inherit", XQueryTokenType.K_INHERIT);
matchSingleToken(lexer, "no-inherit", XQueryTokenType.K_NO_INHERIT);
}
// endregion
// region XQuery 1.0 :: DefaultCollationDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DefaultCollationDecl")
public void testDefaultCollationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 1.0 :: BaseURIDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-BaseURIDecl")
public void testBaseURIDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "base-uri", XQueryTokenType.K_BASE_URI);
}
// endregion
// region XQuery 1.0 :: SchemaImport
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaImport")
public void testSchemaImport() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "import", XQueryTokenType.K_IMPORT);
matchSingleToken(lexer, "schema", XQueryTokenType.K_SCHEMA);
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: SchemaPrefix
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaPrefix")
public void testSchemaPrefix() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
}
// endregion
// region XQuery 1.0 :: ModuleImport
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ModuleImport")
public void testModuleImport() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "import", XQueryTokenType.K_IMPORT);
matchSingleToken(lexer, "module", XQueryTokenType.K_MODULE);
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 1.0 :: VarDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VarDecl")
public void testVarDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "variable", XQueryTokenType.K_VARIABLE);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region XQuery 1.0 :: ConstructionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ConstructionDecl")
public void testConstructionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "construction", XQueryTokenType.K_CONSTRUCTION);
matchSingleToken(lexer, "strip", XQueryTokenType.K_STRIP);
matchSingleToken(lexer, "preserve", XQueryTokenType.K_PRESERVE);
}
// endregion
// region XQuery 1.0 :: FunctionDecl
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FunctionDecl")
public void testFunctionDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region XQuery 1.0 :: ParamList
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ParamList")
public void testParamList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: Param
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Param")
public void testParam() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-EnclosedExpr")
public void testEnclosedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: Expr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Expr")
public void testExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: FLWORExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FLWORExpr")
public void testFLWORExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: ForClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ForClause")
public void testForClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "for", XQueryTokenType.K_FOR);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: PositionalVar
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PositionalVar")
public void testPositionalVar() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "at", XQueryTokenType.K_AT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: LetClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-LetClause")
public void testLetClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "let", XQueryTokenType.K_LET);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: WhereClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-WhereClause")
public void testWhereClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "where", XQueryTokenType.K_WHERE);
}
// endregion
// region XQuery 1.0 :: OrderByClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderByClause")
public void testOrderByClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "stable", XQueryTokenType.K_STABLE);
matchSingleToken(lexer, "order", XQueryTokenType.K_ORDER);
matchSingleToken(lexer, "by", XQueryTokenType.K_BY);
}
// endregion
// region XQuery 1.0 :: OrderSpecList
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderSpecList")
public void testOrderSpecList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 1.0 :: OrderModifier
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderModifier")
public void testOrderModifier() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "ascending", XQueryTokenType.K_ASCENDING);
matchSingleToken(lexer, "descending", XQueryTokenType.K_DESCENDING);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
matchSingleToken(lexer, "greatest", XQueryTokenType.K_GREATEST);
matchSingleToken(lexer, "least", XQueryTokenType.K_LEAST);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 1.0 :: QuantifiedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-QuantifiedExpr")
public void testQuantifiedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "some", XQueryTokenType.K_SOME);
matchSingleToken(lexer, "every", XQueryTokenType.K_EVERY);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "satisfies", XQueryTokenType.K_SATISFIES);
}
// endregion
// region XQuery 1.0 :: TypeswitchExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TypeswitchExpr")
public void testTypeswitchExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "typeswitch", XQueryTokenType.K_TYPESWITCH);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: CaseClause
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CaseClause")
public void testCaseClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "case", XQueryTokenType.K_CASE);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 1.0 :: IfExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-IfExpr")
public void testIfExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "if", XQueryTokenType.K_IF);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "then", XQueryTokenType.K_THEN);
matchSingleToken(lexer, "else", XQueryTokenType.K_ELSE);
}
// endregion
// region XQuery 1.0 :: OrExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrExpr")
public void testOrExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "or", XQueryTokenType.K_OR);
}
// endregion
// region XQuery 1.0 :: AndExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AndExpr")
public void testAndExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "and", XQueryTokenType.K_AND);
}
// endregion
// region XQuery 1.0 :: RangeExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-RangeExpr")
public void testRangeExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "to", XQueryTokenType.K_TO);
}
// endregion
// region XQuery 1.0 :: AdditiveExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AdditiveExpr")
public void testAdditiveExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
matchSingleToken(lexer, "-", XQueryTokenType.MINUS);
}
// endregion
// region XQuery 1.0 :: MultiplicativeExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-MultiplicativeExpr")
public void testMultiplicativeExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, "div", XQueryTokenType.K_DIV);
matchSingleToken(lexer, "idiv", XQueryTokenType.K_IDIV);
matchSingleToken(lexer, "mod", XQueryTokenType.K_MOD);
}
// endregion
// region XQuery 1.0 :: UnionExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnionExpr")
public void testUnionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "union", XQueryTokenType.K_UNION);
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 1.0 :: IntersectExceptExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-IntersectExceptExpr")
public void testIntersectExceptExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "intersect", XQueryTokenType.K_INTERSECT);
matchSingleToken(lexer, "except", XQueryTokenType.K_EXCEPT);
}
// endregion
// region XQuery 1.0 :: InstanceofExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-InstanceofExpr")
public void testInstanceofExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "instance", XQueryTokenType.K_INSTANCE);
matchSingleToken(lexer, "of", XQueryTokenType.K_OF);
}
// endregion
// region XQuery 1.0 :: TreatExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TreatExpr")
public void testTreatExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "treat", XQueryTokenType.K_TREAT);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: CastableExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CastableExpr")
public void testCastableExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "castable", XQueryTokenType.K_CASTABLE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: CastExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CastExpr")
public void testCastExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "cast", XQueryTokenType.K_CAST);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: UnaryExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnaryExpr")
public void testUnaryExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
matchSingleToken(lexer, "-", XQueryTokenType.MINUS);
lexer.start("++");
matchToken(lexer, "+", 0, 0, 1, XQueryTokenType.PLUS);
matchToken(lexer, "+", 0, 1, 2, XQueryTokenType.PLUS);
matchToken(lexer, "", 0, 2, 2, null);
lexer.start("--");
matchToken(lexer, "-", 0, 0, 1, XQueryTokenType.MINUS);
matchToken(lexer, "-", 0, 1, 2, XQueryTokenType.MINUS);
matchToken(lexer, "", 0, 2, 2, null);
}
// endregion
// region XQuery 1.0 :: GeneralComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-GeneralComp")
public void testGeneralComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
matchSingleToken(lexer, "!=", XQueryTokenType.NOT_EQUAL);
matchSingleToken(lexer, "<", XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<=", XQueryTokenType.LESS_THAN_OR_EQUAL);
matchSingleToken(lexer, ">", XQueryTokenType.GREATER_THAN);
matchSingleToken(lexer, ">=", XQueryTokenType.GREATER_THAN_OR_EQUAL);
}
// endregion
// region XQuery 1.0 :: ValueComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValueComp")
public void testValueComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "eq", XQueryTokenType.K_EQ);
matchSingleToken(lexer, "ne", XQueryTokenType.K_NE);
matchSingleToken(lexer, "lt", XQueryTokenType.K_LT);
matchSingleToken(lexer, "le", XQueryTokenType.K_LE);
matchSingleToken(lexer, "gt", XQueryTokenType.K_GT);
matchSingleToken(lexer, "ge", XQueryTokenType.K_GE);
}
// endregion
// region XQuery 1.0 :: NodeComp
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-NodeComp")
public void testNodeComp() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "is", XQueryTokenType.K_IS);
matchSingleToken(lexer, "<<", XQueryTokenType.NODE_BEFORE);
matchSingleToken(lexer, ">>", XQueryTokenType.NODE_AFTER);
}
// endregion
// region XQuery 1.0 :: ValidateExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidateExpr")
public void testValidateExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: ValidationMode
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidationMode")
public void testValidationMode() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "lax", XQueryTokenType.K_LAX);
matchSingleToken(lexer, "strict", XQueryTokenType.K_STRICT);
}
// endregion
// region XQuery 1.0 :: ExtensionExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ExtensionExpr")
public void testExtensionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: Pragma + PragmaContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Pragma")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PragmaContents")
public void testPragma() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(#", 8, XQueryTokenType.PRAGMA_BEGIN);
matchSingleToken(lexer, "#)", 0, XQueryTokenType.PRAGMA_END);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, "#", XQueryTokenType.FUNCTION_REF_OPERATOR);
lexer.start("(# let:for 6^gkgw~*#g#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, " ", 8, 2, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "let", 8, 4, 7, XQueryTokenType.NCNAME);
matchToken(lexer, ":", 9, 7, 8, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "for", 9, 8, 11, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 11, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*#g", 10, 13, 23, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 23, 25, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 25, 25, null);
lexer.start("(#let ##)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "#", 10, 6, 7, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 7, 9, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(#let 2");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2", 10, 6, 7, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 7, 7, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("(#let ");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 10, 6, 6, null);
lexer.start("(#let~~~#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "~~~", 9, 5, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 8, 10, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(#let~~~");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "let", 8, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "~~~", 9, 5, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 8, 8, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("(#:let 2#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, ":", 8, 2, 3, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "let", 9, 3, 6, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 9, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2", 10, 7, 8, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 8, 10, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(#~~~#)");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "~~~", 8, 2, 5, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "#)", 10, 5, 7, XQueryTokenType.PRAGMA_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("(#~~~");
matchToken(lexer, "(#", 0, 0, 2, XQueryTokenType.PRAGMA_BEGIN);
matchToken(lexer, "~~~", 8, 2, 5, XQueryTokenType.PRAGMA_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
}
// endregion
// region XQuery 1.0 :: PathExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PathExpr")
public void testPathExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "/", XQueryTokenType.DIRECT_DESCENDANTS_PATH);
matchSingleToken(lexer, "//", XQueryTokenType.ALL_DESCENDANTS_PATH);
}
// endregion
// region XQuery 1.0 :: RelativePathExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-RelativePathExpr")
public void testRelativePathExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "/", XQueryTokenType.DIRECT_DESCENDANTS_PATH);
matchSingleToken(lexer, "//", XQueryTokenType.ALL_DESCENDANTS_PATH);
}
// endregion
// region XQuery 1.0 :: ForwardAxis
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ForwardAxis")
public void testForwardAxis() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "child", XQueryTokenType.K_CHILD);
matchSingleToken(lexer, "descendant", XQueryTokenType.K_DESCENDANT);
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "self", XQueryTokenType.K_SELF);
matchSingleToken(lexer, "descendant-or-self", XQueryTokenType.K_DESCENDANT_OR_SELF);
matchSingleToken(lexer, "following-sibling", XQueryTokenType.K_FOLLOWING_SIBLING);
matchSingleToken(lexer, "following", XQueryTokenType.K_FOLLOWING);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: AbbrevForwardStep
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AbbrevForwardStep")
public void testAbbrevForwardStep() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "@", XQueryTokenType.ATTRIBUTE_SELECTOR);
}
// endregion
// region XQuery 1.0 :: ReverseAxis
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ReverseAxis")
public void testReverseAxis() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "parent", XQueryTokenType.K_PARENT);
matchSingleToken(lexer, "ancestor", XQueryTokenType.K_ANCESTOR);
matchSingleToken(lexer, "preceding-sibling", XQueryTokenType.K_PRECEDING_SIBLING);
matchSingleToken(lexer, "preceding", XQueryTokenType.K_PRECEDING);
matchSingleToken(lexer, "ancestor-or-self", XQueryTokenType.K_ANCESTOR_OR_SELF);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: AbbrevReverseStep
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AbbrevReverseStep")
public void testAbbrevReverseStep() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "..", XQueryTokenType.PARENT_SELECTOR);
}
// endregion
// region XQuery 1.0 :: Wildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Wildcard")
public void testWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, ":", XQueryTokenType.QNAME_SEPARATOR);
}
// endregion
// region XQuery 1.0 :: Predicate
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-Predicate")
public void testPredicate() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "[", XQueryTokenType.PREDICATE_BEGIN);
matchSingleToken(lexer, "]", XQueryTokenType.PREDICATE_END);
}
// endregion
// region XQuery 1.0 :: VarRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-VarRef")
public void testVarRef() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 1.0 :: ParenthesizedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ParenthesizedExpr")
public void testParenthesizedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: ContextItemExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ContextItemExpr")
public void testContextItemExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ".", XQueryTokenType.DOT);
}
// endregion
// region XQuery 1.0 :: OrderedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OrderedExpr")
public void testOrderedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "ordered", XQueryTokenType.K_ORDERED);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: UnorderedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-UnorderedExpr")
public void testUnorderedExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "unordered", XQueryTokenType.K_UNORDERED);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: FunctionCall
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-FunctionCall")
public void testFunctionCall() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: DirElemConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemConstructor")
public void testDirElemConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, ">", XQueryTokenType.GREATER_THAN);
matchSingleToken(lexer, "</", XQueryTokenType.CLOSE_XML_TAG);
matchSingleToken(lexer, "/>", XQueryTokenType.SELF_CLOSING_XML_TAG);
lexer.start("<one:two/>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, "/>", 11, 8, 10, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<one:two></one:two >");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "</", 17, 9, 11, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "one", 12, 11, 14, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 12, 14, 15, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 12, 15, 18, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 12, 18, 20, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, ">", 12, 20, 21, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 21, 21, null);
lexer.start("<one:two ></one:two>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 11, 8, 10, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, ">", 25, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "</", 17, 11, 13, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "one", 12, 13, 16, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 12, 16, 17, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 12, 17, 20, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 20, 21, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 21, 21, null);
lexer.start("<one:two//*/>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, "/", 11, 8, 9, XQueryTokenType.INVALID);
matchToken(lexer, "/", 11, 9, 10, XQueryTokenType.INVALID);
matchToken(lexer, "*", 11, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "/>", 11, 11, 13, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeList + DirAttributeValue
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirAttributeList")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirAttributeValue")
public void testDirAttributeList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
lexer.start("<one:two a:b = \"One\" c:d = 'Two' />");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "one", 11, 1, 4, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ":", 11, 4, 5, XQueryTokenType.XML_TAG_QNAME_SEPARATOR);
matchToken(lexer, "two", 11, 5, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, " ", 11, 8, 10, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "a", 25, 10, 11, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, ":", 25, 11, 12, XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR);
matchToken(lexer, "b", 25, 12, 13, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, " ", 25, 13, 15, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "=", 25, 15, 16, XQueryTokenType.XML_EQUAL);
matchToken(lexer, " ", 25, 16, 18, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "\"", 25, 18, 19, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 19, 22, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 22, 23, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, " ", 25, 23, 25, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "c", 25, 25, 26, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, ":", 25, 26, 27, XQueryTokenType.XML_ATTRIBUTE_QNAME_SEPARATOR);
matchToken(lexer, "d", 25, 27, 28, XQueryTokenType.XML_ATTRIBUTE_NCNAME);
matchToken(lexer, " ", 25, 28, 30, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "=", 25, 30, 31, XQueryTokenType.XML_EQUAL);
matchToken(lexer, " ", 25, 31, 33, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "'", 25, 33, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "Two", 14, 34, 37, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 37, 38, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, " ", 25, 38, 40, XQueryTokenType.XML_WHITE_SPACE);
matchToken(lexer, "/>", 25, 40, 42, XQueryTokenType.SELF_CLOSING_XML_TAG);
matchToken(lexer, "", 0, 42, 42, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + QuotAttrValueContent + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-QuotAttrValueContent")
public void testDirAttributeValue_QuotAttrValueContent() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One {2}<& \u3053\u3093\u3070\u3093\u306F.\"", 0, 18, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One ", 13, 1, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "{", 13, 5, 6, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 15, 6, 7, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 15, 7, 8, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 13, 8, 9, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 13, 9, 10, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 13, 10, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 17, 18, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 18, 18, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + AposAttrValueContent + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-AposAttrValueContent")
public void testDirAttributeValue_AposAttrValueContent() {
Lexer lexer = new XQueryLexer();
lexer.start("'One {2}<& \u3053\u3093\u3070\u3093\u306F.}'", 0, 19, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One ", 14, 1, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "{", 14, 5, 6, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 16, 6, 7, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 16, 7, 8, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 14, 8, 9, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 14, 9, 10, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 14, 10, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "}", 14, 17, 18, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "'", 14, 18, 19, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 19, 19, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + CommonContent
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommonContent")
public void testDirAttributeValue_CommonContent() {
Lexer lexer = new XQueryLexer();
lexer.start("\"{{}}\"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "{{", 13, 1, 3, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "}}", 13, 3, 5, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "\"", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
lexer.start("'{{}}'", 0, 6, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "{{", 14, 1, 3, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "}}", 14, 3, 5, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "'", 14, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testDirAttributeValue_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("\"One&abc;&aBc;&Abc;&ABC;&a4;&a;Two\"", 0, 35, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&abc;", 13, 4, 9, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 13, 9, 14, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 13, 14, 19, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 13, 19, 24, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 13, 24, 28, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 13, 28, 31, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 13, 31, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 34, 35, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 35, 35, null);
lexer.start("'One&abc;&aBc;&Abc;&ABC;&a4;&a;Two'", 0, 35, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&abc;", 14, 4, 9, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 14, 9, 14, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 14, 14, 19, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 14, 19, 24, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 14, 24, 28, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 14, 28, 31, XQueryTokenType.XML_PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 14, 31, 34, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 34, 35, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 35, 35, null);
lexer.start("\"&\"", 0, 3, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 2, 3, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 3, 3, null);
lexer.start("\"&abc!\"", 0, 7, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&abc", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 6, 7, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 7, 7, null);
lexer.start("\"& \"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 2, 3, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
lexer.start("\"&", 0, 2, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&", 13, 1, 2, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 2, 2, null);
lexer.start("\"&abc", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&abc", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 5, null);
lexer.start("\"&;\"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&;", 13, 1, 3, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + EscapeQuot
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeQuot")
public void testDirAttributeValue_EscapeQuot() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One\"\"Two\"", 0, 10, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"\"", 13, 4, 6, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "Two", 13, 6, 9, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 9, 10, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + EscapeApos
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeApos")
public void testDirAttributeValue_EscapeApos() {
Lexer lexer = new XQueryLexer();
lexer.start("'One''Two'", 0, 10, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "''", 14, 4, 6, XQueryTokenType.XML_ESCAPED_CHARACTER);
matchToken(lexer, "Two", 14, 6, 9, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 9, 10, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: DirAttributeValue + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirAttributeValue_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"OneTwo\"", 0, 13, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 13, 4, 9, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 13, 9, 12, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 12, 13, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 13, 13, null);
lexer.start("'OneTwo'", 0, 13, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 14, 4, 9, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 14, 9, 12, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 12, 13, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 13, 13, null);
lexer.start("\"&#\"", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 4, 4, null);
lexer.start("\"&# \"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 3, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
lexer.start("\"&#", 0, 3, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#", 13, 1, 3, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 3, 3, null);
lexer.start("\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "", 13, 1, 5, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 5, null);
lexer.start("\"&#;\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#;", 13, 1, 4, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirAttributeValue")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirAttributeValue_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One ®ÜTwo\"", 0, 26, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 13, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, " ", 13, 4, 10, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "®", 13, 10, 16, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 13, 16, 22, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 13, 22, 25, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 25, 26, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 26, 26, null);
lexer.start("'One ®ÜTwo'", 0, 26, 11);
matchToken(lexer, "'", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "One", 14, 1, 4, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, " ", 14, 4, 10, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "®", 14, 10, 16, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 14, 16, 22, XQueryTokenType.XML_CHARACTER_REFERENCE);
matchToken(lexer, "Two", 14, 22, 25, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "'", 14, 25, 26, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 26, 26, null);
lexer.start("\"&#x\"", 0, 5, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 5, 5, null);
lexer.start("\"&#x \"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 13, 4, 5, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 5, 6, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 6, 6, null);
lexer.start("\"&#x", 0, 4, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x", 13, 1, 4, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 4, 4, null);
lexer.start("\"", 0, 6, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "", 13, 1, 6, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 6, 6, null);
lexer.start("\"&#x;G;g;&#xg2;\"", 0, 24, 11);
matchToken(lexer, "\"", 11, 0, 1, XQueryTokenType.XML_ATTRIBUTE_VALUE_START);
matchToken(lexer, "&#x;", 13, 1, 5, XQueryTokenType.XML_EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 13, 5, 9, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 13, 9, 11, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "", 13, 11, 15, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 13, 15, 17, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "&#x", 13, 17, 20, XQueryTokenType.XML_PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 13, 20, 23, XQueryTokenType.XML_ATTRIBUTE_VALUE_CONTENTS);
matchToken(lexer, "\"", 13, 23, 24, XQueryTokenType.XML_ATTRIBUTE_VALUE_END);
matchToken(lexer, "", 11, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + ElementContentChar + EnclosedExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementContentChar")
public void testDirElemContent_ElementContentChar() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One {2}<& \u3053\u3093\u3070\u3093\u306F.}</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "{", 17, 7, 8, XQueryTokenType.BLOCK_OPEN);
matchToken(lexer, "2", 18, 8, 9, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "}", 18, 9, 10, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "<", 17, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "&", 17, 11, 12, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " \u3053\u3093\u3070\u3093\u306F.", 17, 12, 19, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "}", 17, 19, 20, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "</", 17, 20, 22, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 22, 23, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 23, 24, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirElemConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemConstructor")
public void testDirElemContent_DirElemConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One <b>Two</b> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<", 17, 7, 8, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "b", 11, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "Two", 17, 10, 13, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 13, 15, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "b", 12, 15, 16, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 16, 17, XQueryTokenType.END_XML_TAG);
matchToken(lexer, " Three", 17, 17, 23, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 23, 25, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 25, 26, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 26, 27, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 27, 27, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirCommentConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirCommentConstructor")
public void testDirElemContent_DirCommentConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<!<!-", 0, 5, 17);
matchToken(lexer, "<!", 17, 0, 2, XQueryTokenType.INVALID);
matchToken(lexer, "<!-", 17, 2, 5, XQueryTokenType.INVALID);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<a>One <!-- 2 --> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<!--", 17, 7, 11, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " 2 ", 19, 11, 14, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 19, 14, 17, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, " Three", 17, 17, 23, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 23, 25, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 25, 26, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 26, 27, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 27, 27, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CDataSection (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CDataSection")
public void testDirElemContent_CDataSection() {
Lexer lexer = new XQueryLexer();
lexer.start("<!<![<![C<![CD<![CDA<![CDAT<![CDATA", 0, 35, 17);
matchToken(lexer, "<!", 17, 0, 2, XQueryTokenType.INVALID);
matchToken(lexer, "<![", 17, 2, 5, XQueryTokenType.INVALID);
matchToken(lexer, "<![C", 17, 5, 9, XQueryTokenType.INVALID);
matchToken(lexer, "<![CD", 17, 9, 14, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDA", 17, 14, 20, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDAT", 17, 20, 27, XQueryTokenType.INVALID);
matchToken(lexer, "<![CDATA", 17, 27, 35, XQueryTokenType.INVALID);
matchToken(lexer, "", 17, 35, 35, null);
lexer.start("<a>One <![CDATA[ 2 ]]> Three</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One ", 17, 3, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "<![CDATA[", 17, 7, 16, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " 2 ", 20, 16, 19, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 20, 19, 22, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, " Three", 17, 22, 28, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 28, 30, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 30, 31, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 31, 32, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 32, 32, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + DirPIConstructor (DirectConstructor)
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIConstructor")
public void testDirElemContent_DirPIConstructor() {
Lexer lexer = new XQueryLexer();
lexer.start("<a><?for 6^gkgw~*?g?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 23, 5, 8, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 8, 10, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*?g", 24, 10, 20, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "?>", 24, 20, 22, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 22, 24, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 24, 25, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 25, 26, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("<a><?for?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 23, 5, 8, XQueryTokenType.NCNAME);
matchToken(lexer, "?>", 23, 8, 10, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 10, 12, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 12, 13, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 13, 14, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<a><?*?$?></a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "<?", 17, 3, 5, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "*", 23, 5, 6, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?", 23, 6, 7, XQueryTokenType.INVALID);
matchToken(lexer, "$", 23, 7, 8, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?>", 23, 8, 10, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "</", 17, 10, 12, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 12, 13, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 13, 14, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<?a ?", 0, 5, 17);
matchToken(lexer, "<?", 17, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 23, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "?", 24, 4, 5, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<?a ", 0, 4, 17);
matchToken(lexer, "<?", 17, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 23, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 23, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 24, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CommonContent
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommonContent")
public void testDirElemContent_CommonContent() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>{{}}</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "{{", 17, 3, 5, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "}}", 17, 5, 7, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "</", 17, 7, 9, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 9, 10, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 11, 11, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PredefinedEntityRef")
public void testDirElemContent_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("<a>One&abc;&aBc;&Abc;&ABC;&a4;&a;Two</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "&abc;", 17, 6, 11, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 17, 11, 16, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 17, 16, 21, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 17, 21, 26, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 17, 26, 30, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 17, 30, 33, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 17, 33, 36, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 36, 38, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 38, 39, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 39, 40, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 40, 40, null);
lexer.start("<a>&</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 4, 6, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 6, 7, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 7, 8, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("<a>&abc!</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&abc", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 17, 7, 8, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 8, 10, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 10, 11, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 11, 12, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 12, 12, null);
lexer.start("<a>&</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 4, 6, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 6, 7, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 7, 8, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("<a>&");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&", 17, 3, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 4, 4, null);
lexer.start("<a>&abc");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&abc", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 7, null);
lexer.start("<a>&;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&;", 17, 3, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 5, 7, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 7, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 9, 9, null);
}
// endregion
// region XQuery 1.0 :: DirElemContent + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirElemContent_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>OneTwo</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "", 17, 6, 11, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 17, 11, 14, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 14, 16, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 16, 17, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 17, 18, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 18, 18, null);
lexer.start("<a>&#</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 5, 7, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 7, 8, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 8, 9, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<a>&# </a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 17, 5, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<a>&#");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#", 17, 3, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 5, 5, null);
lexer.start("<a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 17, 3, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 7, null);
lexer.start("<a>&#;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#;", 17, 3, 6, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirElemContent")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testDirElemContent_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("<a>One ®ÜTwo</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "One", 17, 3, 6, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, " ", 17, 6, 12, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 17, 12, 18, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 17, 18, 24, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 17, 24, 27, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 27, 29, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 29, 30, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 30, 31, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 31, 31, null);
lexer.start("<a>&#x</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "</", 17, 6, 8, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 8, 9, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 9, 10, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<a>&#x </a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 17, 6, 7, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 7, 9, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 9, 10, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 10, 11, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 11, 11, null);
lexer.start("<a>&#x");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x", 17, 3, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 6, 6, null);
lexer.start("<a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 17, 3, 8, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 8, 8, null);
lexer.start("<a>&#x;G;g;&#xg2;</a>");
matchToken(lexer, "<", 0, 0, 1, XQueryTokenType.OPEN_XML_TAG);
matchToken(lexer, "a", 11, 1, 2, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 11, 2, 3, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "&#x;", 17, 3, 7, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 17, 7, 11, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 17, 11, 13, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "", 17, 13, 17, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 17, 17, 19, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "&#x", 17, 19, 22, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 17, 22, 25, XQueryTokenType.XML_ELEMENT_CONTENTS);
matchToken(lexer, "</", 17, 25, 27, XQueryTokenType.CLOSE_XML_TAG);
matchToken(lexer, "a", 12, 27, 28, XQueryTokenType.XML_TAG_NCNAME);
matchToken(lexer, ">", 12, 28, 29, XQueryTokenType.END_XML_TAG);
matchToken(lexer, "", 0, 29, 29, null);
}
// endregion
// region XQuery 1.0 :: DirCommentConstructor + DirCommentContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentContents")
public void testDirCommentConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", 0, XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<!", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<!-", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<!--", 5, XQueryTokenType.XML_COMMENT_START_TAG);
// Unary Minus
lexer.start("--");
matchToken(lexer, "-", 0, 0, 1, XQueryTokenType.MINUS);
matchToken(lexer, "-", 0, 1, 2, XQueryTokenType.MINUS);
matchToken(lexer, "", 0, 2, 2, null);
matchSingleToken(lexer, "-->", XQueryTokenType.XML_COMMENT_END_TAG);
lexer.start("<!-- Test");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test", 5, 4, 9, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<!-- Test --");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test --", 5, 4, 12, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 12, 12, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 12, 12, null);
lexer.start("<!-- Test -->");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, " Test ", 5, 4, 10, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 10, 13, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("<!--\nMultiline\nComment\n-->");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 5, 4, 23, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 23, 26, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("<!---");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "-", 5, 4, 5, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("<!----");
matchToken(lexer, "<!--", 0, 0, 4, XQueryTokenType.XML_COMMENT_START_TAG);
matchToken(lexer, "--", 5, 4, 6, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 6, 6, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 6, 6, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DirCommentContents")
public void testDirCommentConstructor_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("<!-- Test", 4, 9, 5);
matchToken(lexer, " Test", 5, 4, 9, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("<!-- Test -->", 4, 13, 5);
matchToken(lexer, " Test ", 5, 4, 10, XQueryTokenType.XML_COMMENT);
matchToken(lexer, "-->", 5, 10, 13, XQueryTokenType.XML_COMMENT_END_TAG);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: DirPIConstructor + DirPIContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIConstructor")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DirPIContents")
public void testDirPIConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<?", 21, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchSingleToken(lexer, "?>", 0, XQueryTokenType.PROCESSING_INSTRUCTION_END);
lexer.start("<?for 6^gkgw~*?g?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 21, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 5, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "6^gkgw~*?g", 22, 7, 17, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "?>", 22, 17, 19, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("<?for?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "for", 21, 2, 5, XQueryTokenType.NCNAME);
matchToken(lexer, "?>", 21, 5, 7, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("<?*?$?>");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "*", 21, 2, 3, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?", 21, 3, 4, XQueryTokenType.INVALID);
matchToken(lexer, "$", 21, 4, 5, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "?>", 21, 5, 7, XQueryTokenType.PROCESSING_INSTRUCTION_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("<?a ?");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 21, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "?", 22, 4, 5, XQueryTokenType.PROCESSING_INSTRUCTION_CONTENTS);
matchToken(lexer, "", 6, 5, 5, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("<?a ");
matchToken(lexer, "<?", 0, 0, 2, XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN);
matchToken(lexer, "a", 21, 2, 3, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 21, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 22, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: CDataSection + CDataSectionContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSection")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSectionContents")
public void testCDataSection() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "<", 0, XQueryTokenType.LESS_THAN);
matchSingleToken(lexer, "<!", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![C", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CD", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDA", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDAT", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDATA", 0, XQueryTokenType.INVALID);
matchSingleToken(lexer, "<![CDATA[", 7, XQueryTokenType.CDATA_SECTION_START_TAG);
matchSingleToken(lexer, "]", XQueryTokenType.PREDICATE_END);
lexer.start("]]");
matchToken(lexer, "]", 0, 0, 1, XQueryTokenType.PREDICATE_END);
matchToken(lexer, "]", 0, 1, 2, XQueryTokenType.PREDICATE_END);
matchToken(lexer, "", 0, 2, 2, null);
matchSingleToken(lexer, "]]>", XQueryTokenType.CDATA_SECTION_END_TAG);
lexer.start("<![CDATA[ Test");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test", 7, 9, 14, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 14, 14, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<![CDATA[ Test ]]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test ]]", 7, 9, 17, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 17, 17, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 17, 17, null);
lexer.start("<![CDATA[ Test ]]>");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, " Test ", 7, 9, 15, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 15, 18, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 18, 18, null);
lexer.start("<![CDATA[\nMultiline\nComment\n]]>");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 7, 9, 28, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 28, 31, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 31, 31, null);
lexer.start("<![CDATA[]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "]", 7, 9, 10, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 10, 10, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("<![CDATA[]]");
matchToken(lexer, "<![CDATA[", 0, 0, 9, XQueryTokenType.CDATA_SECTION_START_TAG);
matchToken(lexer, "]]", 7, 9, 11, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 11, 11, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 11, 11, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSection")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CDataSectionContents")
public void testCDataSection_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("<![CDATA[ Test", 9, 14, 7);
matchToken(lexer, " Test", 7, 9, 14, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "", 6, 14, 14, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("<![CDATA[ Test ]]>", 9, 18, 7);
matchToken(lexer, " Test ", 7, 9, 15, XQueryTokenType.CDATA_SECTION);
matchToken(lexer, "]]>", 7, 15, 18, XQueryTokenType.CDATA_SECTION_END_TAG);
matchToken(lexer, "", 0, 18, 18, null);
}
// endregion
// region XQuery 1.0 :: CompDocConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompDocConstructor")
public void testCompDocConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "document", XQueryTokenType.K_DOCUMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompElemConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompElemConstructor")
public void testCompElemConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompAttrConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompAttrConstructor")
public void testCompAttrConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompTextConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompTextConstructor")
public void testCompTextConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "text", XQueryTokenType.K_TEXT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompCommentConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompCommentConstructor")
public void testCompCommentConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "comment", XQueryTokenType.K_COMMENT);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: CompPIConstructor
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CompPIConstructor")
public void testCompPIConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "processing-instruction", XQueryTokenType.K_PROCESSING_INSTRUCTION);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 1.0 :: TypeDeclaration
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TypeDeclaration")
public void testTypeDeclaration() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 1.0 :: SequenceType
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SequenceType")
public void testSequenceType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "empty-sequence", XQueryTokenType.K_EMPTY_SEQUENCE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: OccurrenceIndicator
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-OccurrenceIndicator")
public void testOccurrenceIndicator() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, "+", XQueryTokenType.PLUS);
}
// endregion
// region XQuery 1.0 :: ItemType
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ItemType")
public void testItemType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "item", XQueryTokenType.K_ITEM);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AnyKindTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AnyKindTest")
public void testAnyKindTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: DocumentTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-DocumentTest")
public void testDocumentTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "document-node", XQueryTokenType.K_DOCUMENT_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: TextTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-TextTest")
public void testTextTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "text", XQueryTokenType.K_TEXT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: CommentTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-CommentTest")
public void testCommentTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "comment", XQueryTokenType.K_COMMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: PITest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-PITest")
public void testPITest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "processing-instruction", XQueryTokenType.K_PROCESSING_INSTRUCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AttributeTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AttributeTest")
public void testAttributeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "attribute", XQueryTokenType.K_ATTRIBUTE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: AttribNameOrWildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-AttribNameOrWildcard")
public void testAttribNameOrWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
}
// endregion
// region XQuery 1.0 :: SchemaAttributeTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaAttributeTest")
public void testSchemaAttributeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "schema-attribute", XQueryTokenType.K_SCHEMA_ATTRIBUTE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: ElementTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementTest")
public void testElementTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "element", XQueryTokenType.K_ELEMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
}
// endregion
// region XQuery 1.0 :: ElementNameOrWildcard
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ElementNameOrWildcard")
public void testElementNameOrWildcard() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
}
// endregion
// region XQuery 1.0 :: SchemaElementTest
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-SchemaElementTest")
public void testSchemaElementTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "schema-element", XQueryTokenType.K_SCHEMA_ELEMENT);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 1.0 :: IntegerLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-IntegerLiteral")
public void testIntegerLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("1234");
matchToken(lexer, "1234", 0, 0, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DecimalLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DecimalLiteral")
public void testDecimalLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("47.");
matchToken(lexer, "47.", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start("1.234");
matchToken(lexer, "1.234", 0, 0, 5, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start(".25");
matchToken(lexer, ".25", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start(".1.2");
matchToken(lexer, ".1", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, ".2", 0, 2, 4, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "", 0, 4, 4, null);
}
// endregion
// region XQuery 1.0 :: DoubleLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DoubleLiteral")
public void testDoubleLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("3e7 3e+7 3e-7");
matchToken(lexer, "3e7", 0, 0, 3, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "3e+7", 0, 4, 8, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "3e-7", 0, 9, 13, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("43E22 43E+22 43E-22");
matchToken(lexer, "43E22", 0, 0, 5, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "43E+22", 0, 6, 12, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 12, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "43E-22", 0, 13, 19, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("2.1e3 2.1e+3 2.1e-3");
matchToken(lexer, "2.1e3", 0, 0, 5, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 5, 6, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2.1e+3", 0, 6, 12, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 12, 13, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "2.1e-3", 0, 13, 19, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 19, 19, null);
lexer.start("1.7E99 1.7E+99 1.7E-99");
matchToken(lexer, "1.7E99", 0, 0, 6, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1.7E+99", 0, 7, 14, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1.7E-99", 0, 15, 22, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 22, 22, null);
lexer.start(".22e42 .22e+42 .22e-42");
matchToken(lexer, ".22e42", 0, 0, 6, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".22e+42", 0, 7, 14, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".22e-42", 0, 15, 22, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 22, 22, null);
lexer.start(".8E2 .8E+2 .8E-2");
matchToken(lexer, ".8E2", 0, 0, 4, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".8E+2", 0, 5, 10, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".8E-2", 0, 11, 16, XQueryTokenType.DOUBLE_LITERAL);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start("1e 1e+ 1e-");
matchToken(lexer, "1", 0, 0, 1, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 2, 3, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 3, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e+", 3, 4, 6, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 7, 8, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "e-", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("1E 1E+ 1E-");
matchToken(lexer, "1", 0, 0, 1, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 2, 3, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 3, 4, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E+", 3, 4, 6, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "1", 0, 7, 8, XQueryTokenType.INTEGER_LITERAL);
matchToken(lexer, "E-", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("8.9e 8.9e+ 8.9e-");
matchToken(lexer, "8.9", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e", 3, 3, 4, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 5, 8, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e+", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 11, 14, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e-", 3, 14, 16, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start("8.9E 8.9E+ 8.9E-");
matchToken(lexer, "8.9", 0, 0, 3, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E", 3, 3, 4, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 5, 8, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E+", 3, 8, 10, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "8.9", 0, 11, 14, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E-", 3, 14, 16, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 16, 16, null);
lexer.start(".4e .4e+ .4e-");
matchToken(lexer, ".4", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e", 3, 2, 3, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 4, 6, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e+", 3, 6, 8, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 9, 11, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "e-", 3, 11, 13, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start(".4E .4E+ .4E-");
matchToken(lexer, ".4", 0, 0, 2, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E", 3, 2, 3, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 3, 4, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 4, 6, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E+", 3, 6, 8, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, " ", 0, 8, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ".4", 0, 9, 11, XQueryTokenType.DECIMAL_LITERAL);
matchToken(lexer, "E-", 3, 11, 13, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 13, 13, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-DoubleLiteral")
public void testDoubleLiteral_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("1e", 1, 2, 3);
matchToken(lexer, "e", 3, 1, 2, XQueryTokenType.PARTIAL_DOUBLE_LITERAL_EXPONENT);
matchToken(lexer, "", 0, 2, 2, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
public void testStringLiteral() {
Lexer lexer = new XQueryLexer();
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 1, null);
lexer.start("\"Hello World\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "Hello World", 1, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 2, 1, 1, null);
lexer.start("'Hello World'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "Hello World", 2, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
public void testStringLiteral_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("\"Hello World\"", 1, 13, 1);
matchToken(lexer, "Hello World", 1, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'Hello World'", 1, 13, 2);
matchToken(lexer, "Hello World", 2, 1, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + PredefinedEntityRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testStringLiteral_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("\"One&abc;&aBc;&Abc;&ABC;&a4;&a;Two\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 1, 4, 9, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 1, 9, 14, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 1, 14, 19, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 1, 19, 24, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 1, 24, 28, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 1, 28, 31, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 1, 31, 34, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 34, 35, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 35, 35, null);
lexer.start("'One&abc;&aBc;&Abc;&ABC;&a4;&a;Two'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 2, 4, 9, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 2, 9, 14, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 2, 14, 19, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 2, 19, 24, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 2, 24, 28, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 2, 28, 31, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 2, 31, 34, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 34, 35, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 35, 35, null);
lexer.start("\"&\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 2, 3, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 3, 3, null);
lexer.start("\"&abc!\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&abc", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 1, 5, 6, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 6, 7, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("\"& \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 2, 3, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("\"&");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&", 1, 1, 2, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 2, 2, null);
lexer.start("\"&abc");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&abc", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 5, null);
lexer.start("\"&;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&;", 1, 1, 3, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("&");
matchToken(lexer, "&", 0, 0, 1, XQueryTokenType.ENTITY_REFERENCE_NOT_IN_STRING);
matchToken(lexer, "", 0, 1, 1, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + EscapeQuot
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeQuot")
public void testStringLiteral_EscapeQuot() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One\"\"Two\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"\"", 1, 4, 6, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "Two", 1, 6, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 9, 10, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + EscapeApos
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-EscapeApos")
public void testStringLiteral_EscapeApos() {
Lexer lexer = new XQueryLexer();
lexer.start("'One''Two'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "''", 2, 4, 6, XQueryTokenType.ESCAPED_CHARACTER);
matchToken(lexer, "Two", 2, 6, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 9, 10, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: StringLiteral + CharRef
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testStringLiteral_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"OneTwo\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 1, 4, 9, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 1, 9, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("'OneTwo'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 2, 4, 9, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 2, 9, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 12, 13, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 13, 13, null);
lexer.start("\"&#\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 3, 4, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("\"&# \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 3, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("\"&#");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#", 1, 1, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 3, 3, null);
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 5, null);
lexer.start("\"&#;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#;", 1, 1, 4, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-StringLiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testStringLiteral_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("\"One ®ÜTwo\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 1, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 1, 4, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 1, 10, 16, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 1, 16, 22, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 1, 22, 25, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 25, 26, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("'One ®ÜTwo'");
matchToken(lexer, "'", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "One", 2, 1, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 2, 4, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 2, 10, 16, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 2, 16, 22, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 2, 22, 25, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "'", 2, 25, 26, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 26, 26, null);
lexer.start("\"&#x\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "\"", 1, 4, 5, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("\"&#x \"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 1, 4, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 5, 6, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("\"&#x");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x", 1, 1, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 4, 4, null);
lexer.start("\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "", 1, 1, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 6, 6, null);
lexer.start("\"&#x;G;g;&#xg2;\"");
matchToken(lexer, "\"", 0, 0, 1, XQueryTokenType.STRING_LITERAL_START);
matchToken(lexer, "&#x;", 1, 1, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 1, 5, 9, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 1, 9, 11, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 1, 11, 15, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 1, 15, 17, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&#x", 1, 17, 20, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 1, 20, 23, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "\"", 1, 23, 24, XQueryTokenType.STRING_LITERAL_END);
matchToken(lexer, "", 0, 24, 24, null);
}
// endregion
// region XQuery 1.0 :: Comment + CommentContents
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-Comment")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommentContents")
public void testComment() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(:", 4, XQueryTokenType.COMMENT_START_TAG);
matchSingleToken(lexer, ":)", 0, XQueryTokenType.COMMENT_END_TAG);
lexer.start("(: Test :");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Test :", 4, 2, 9, XQueryTokenType.COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(: Test :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Test ", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(::Test::)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, ":Test:", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
lexer.start("(:\nMultiline\nComment\n:)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, "\nMultiline\nComment\n", 4, 2, 21, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 21, 23, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 23, 23, null);
lexer.start("(: Outer (: Inner :) Outer :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Outer (: Inner :) Outer ", 4, 2, 27, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 27, 29, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 29, 29, null);
lexer.start("(: Outer ( : Inner :) Outer :)");
matchToken(lexer, "(:", 0, 0, 2, XQueryTokenType.COMMENT_START_TAG);
matchToken(lexer, " Outer ( : Inner ", 4, 2, 19, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 19, 21, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, " ", 0, 21, 22, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "Outer", 0, 22, 27, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 27, 28, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, ":)", 0, 28, 30, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 30, 30, null);
}
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-Comment")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CommentContents")
public void testComment_InitialState() {
Lexer lexer = new XQueryLexer();
lexer.start("(: Test :", 2, 9, 4);
matchToken(lexer, " Test :", 4, 2, 9, XQueryTokenType.COMMENT);
matchToken(lexer, "", 6, 9, 9, XQueryTokenType.UNEXPECTED_END_OF_BLOCK);
matchToken(lexer, "", 0, 9, 9, null);
lexer.start("(: Test :)", 2, 10, 4);
matchToken(lexer, " Test ", 4, 2, 8, XQueryTokenType.COMMENT);
matchToken(lexer, ":)", 4, 8, 10, XQueryTokenType.COMMENT_END_TAG);
matchToken(lexer, "", 0, 10, 10, null);
}
// endregion
// region XQuery 1.0 :: QName
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-QName")
@Specification(name="Namespaces in XML 1.0 3ed", reference="https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-QName")
public void testQName() {
Lexer lexer = new XQueryLexer();
lexer.start("one:two");
matchToken(lexer, "one", 0, 0, 3, XQueryTokenType.NCNAME);
matchToken(lexer, ":", 0, 3, 4, XQueryTokenType.QNAME_SEPARATOR);
matchToken(lexer, "two", 0, 4, 7, XQueryTokenType.NCNAME);
matchToken(lexer, "", 0, 7, 7, null);
}
// endregion
// region XQuery 1.0 :: NCName
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-NCName")
@Specification(name="Namespaces in XML 1.0 3ed", reference="https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName")
public void testNCName() {
Lexer lexer = new XQueryLexer();
lexer.start("test x b2b F.G a-b g\u0330d");
matchToken(lexer, "test", 0, 0, 4, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 4, 5, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "x", 0, 5, 6, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 6, 7, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "b2b", 0, 7, 10, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 10, 11, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "F.G", 0, 11, 14, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 14, 15, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "a-b", 0, 15, 18, XQueryTokenType.NCNAME);
matchToken(lexer, " ", 0, 18, 19, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "g\u0330d", 0, 19, 22, XQueryTokenType.NCNAME);
matchToken(lexer, "", 0, 22, 22, null);
}
// endregion
// region XQuery 1.0 :: S
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-S")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-S")
public void testS() {
Lexer lexer = new XQueryLexer();
lexer.start(" ");
matchToken(lexer, " ", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\t");
matchToken(lexer, "\t", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\r");
matchToken(lexer, "\r", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start("\n");
matchToken(lexer, "\n", 0, 0, 1, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 1, 1, null);
lexer.start(" \t \r\n ");
matchToken(lexer, " \t \r\n ", 0, 0, 9, XQueryTokenType.WHITE_SPACE);
matchToken(lexer, "", 0, 9, 9, null);
}
// endregion
// region XQuery 3.0 :: DecimalFormatDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-DecimalFormatDecl")
public void testDecimalFormatDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "decimal-format", XQueryTokenType.K_DECIMAL_FORMAT);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "=", XQueryTokenType.EQUAL);
}
// endregion
// region XQuery 3.0 :: DFPropertyName
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-DFPropertyName")
public void testDFPropertyName() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "decimal-separator", XQueryTokenType.K_DECIMAL_SEPARATOR);
matchSingleToken(lexer, "grouping-separator", XQueryTokenType.K_GROUPING_SEPARATOR);
matchSingleToken(lexer, "infinity", XQueryTokenType.K_INFINITY);
matchSingleToken(lexer, "minus-sign", XQueryTokenType.K_MINUS_SIGN);
matchSingleToken(lexer, "NaN", XQueryTokenType.K_NAN);
matchSingleToken(lexer, "percent", XQueryTokenType.K_PERCENT);
matchSingleToken(lexer, "per-mille", XQueryTokenType.K_PER_MILLE);
matchSingleToken(lexer, "zero-digit", XQueryTokenType.K_ZERO_DIGIT);
matchSingleToken(lexer, "digit", XQueryTokenType.K_DIGIT);
matchSingleToken(lexer, "pattern-separator", XQueryTokenType.K_PATTERN_SEPARATOR);
}
// endregion
// region XQuery 3.0 :: AnnotationDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AnnotationDecl")
public void testAnnotationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
}
// endregion
// region XQuery 3.0 :: Annotation
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-Annotation")
public void testAnnotation() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "%", XQueryTokenType.ANNOTATION_INDICATOR);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: ContextItemDecl
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ContextItemDecl")
public void testContextItemDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "context", XQueryTokenType.K_CONTEXT);
matchSingleToken(lexer, "item", XQueryTokenType.K_ITEM);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
}
// endregion
// region XQuery 3.0 :: AllowingEmpty
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AllowingEmpty")
public void testAllowingEmpty() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "allowing", XQueryTokenType.K_ALLOWING);
matchSingleToken(lexer, "empty", XQueryTokenType.K_EMPTY);
}
// endregion
// region XQuery 3.0 :: WindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowClause")
public void testWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "for", XQueryTokenType.K_FOR);
}
// endregion
// region XQuery 3.0 :: TumblingWindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TumblingWindowClause")
public void testTumblingWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "tumbling", XQueryTokenType.K_TUMBLING);
matchSingleToken(lexer, "window", XQueryTokenType.K_WINDOW);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
}
// endregion
// region XQuery 3.0 :: SlidingWindowClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SlidingWindowClause")
public void testSlidingWindowClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "sliding", XQueryTokenType.K_SLIDING);
matchSingleToken(lexer, "window", XQueryTokenType.K_WINDOW);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "in", XQueryTokenType.K_IN);
}
// endregion
// region XQuery 3.0 :: WindowStartCondition
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowStartCondition")
public void testWindowStartCondition() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "start", XQueryTokenType.K_START);
matchSingleToken(lexer, "when", XQueryTokenType.K_WHEN);
}
// endregion
// region XQuery 3.0 :: WindowEndCondition
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowEndCondition")
public void testWindowEndCondition() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "only", XQueryTokenType.K_ONLY);
matchSingleToken(lexer, "end", XQueryTokenType.K_END);
matchSingleToken(lexer, "when", XQueryTokenType.K_WHEN);
}
// endregion
// region XQuery 3.0 :: WindowVars
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-WindowVars")
public void testWindowVars() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, "previous", XQueryTokenType.K_PREVIOUS);
matchSingleToken(lexer, "next", XQueryTokenType.K_NEXT);
}
// endregion
// region XQuery 3.0 :: CountClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CountClause")
public void testCountClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "count", XQueryTokenType.K_COUNT);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 3.0 :: GroupByClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupByClause")
public void testGroupByClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "group", XQueryTokenType.K_GROUP);
matchSingleToken(lexer, "by", XQueryTokenType.K_BY);
}
// endregion
// region XQuery 3.0 :: GroupingSpecList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingSpecList")
public void testGroupingSpecList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
}
// endregion
// region XQuery 3.0 :: GroupingSpec
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingSpec")
public void testGroupingSpec() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, "collation", XQueryTokenType.K_COLLATION);
}
// endregion
// region XQuery 3.0 :: GroupingVariable
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-GroupingVariable")
public void testGroupingVariable() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
}
// endregion
// region XQuery 3.0 :: ReturnClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ReturnClause")
public void testReturnClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SwitchExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SwitchExpr")
public void testSwitchExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "switch", XQueryTokenType.K_SWITCH);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "default", XQueryTokenType.K_DEFAULT);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SwitchCaseClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SwitchCaseClause")
public void testSwitchCaseClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "case", XQueryTokenType.K_CASE);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region XQuery 3.0 :: SequenceTypeUnion
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SequenceTypeUnion")
public void testSequenceTypeUnion() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 3.0 :: TryClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TryClause")
public void testTryClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "try", XQueryTokenType.K_TRY);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: CatchClause
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CatchClause")
public void testCatchClause() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "catch", XQueryTokenType.K_CATCH);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: CatchErrorList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CatchErrorList")
public void testCatchErrorList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "|", XQueryTokenType.UNION);
}
// endregion
// region XQuery 3.0 :: StringConcatExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-StringConcatExpr")
public void testStringConcatExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "||", XQueryTokenType.CONCATENATION);
}
// endregion
// region XQuery 3.0 :: ValidateExpr
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#doc-xquery-ValidateExpr")
public void testValidateExpr_Type() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "type", XQueryTokenType.K_TYPE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: SimpleMapExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-SimpleMapExpr")
public void testSimpleMapExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "!", XQueryTokenType.MAP_OPERATOR);
}
// endregion
// region XQuery 3.0 :: ArgumentList
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ArgumentList")
public void testArgumentList() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: ArgumentPlaceholder
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ArgumentPlaceholder")
public void testArgumentPlaceholder() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "?", XQueryTokenType.OPTIONAL);
}
// endregion
// region XQuery 3.0 :: CompNamespaceConstructor
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-CompNamespaceConstructor")
public void testCompNamespaceConstructor() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region XQuery 3.0 :: NamedFunctionRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-NamedFunctionRef")
public void testNamedFunctionRef() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "#", XQueryTokenType.FUNCTION_REF_OPERATOR);
}
// endregion
// region XQuery 3.0 :: InlineFunctionExpr
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-InlineFunctionExpr")
public void testInlineFunctionExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 3.0 :: NamespaceNodeTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-NamespaceNodeTest")
public void testNamespaceNodeTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace-node", XQueryTokenType.K_NAMESPACE_NODE);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: AnyFunctionTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-AnyFunctionTest")
public void testAnyFunctionTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, "*", XQueryTokenType.STAR);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: TypedFunctionTest
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-TypedFunctionTest")
public void testTypedFunctionTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region XQuery 3.0 :: ParenthesizedItemType
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-ParenthesizedItemType")
public void testParenthesizedItemType() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
public void testBracedURILiteral() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "Q", XQueryTokenType.NCNAME);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 2, null);
lexer.start("Q{Hello World}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "Hello World", 26, 2, 13, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 13, 14, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 14, 14, null);
// NOTE: "", '', {{ and }} are used as escaped characters in string and attribute literals.
lexer.start("Q{A\"\"B''C{{D}}E}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "A\"\"B''C", 26, 2, 9, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "{", 26, 9, 10, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "{", 26, 10, 11, XQueryTokenType.BAD_CHARACTER);
matchToken(lexer, "D", 26, 11, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 12, 13, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "}", 0, 13, 14, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "E", 0, 14, 15, XQueryTokenType.NCNAME);
matchToken(lexer, "}", 0, 15, 16, XQueryTokenType.BLOCK_CLOSE);
matchToken(lexer, "", 0, 16, 16, null);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral + PredefinedEntityRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-PredefinedEntityRef")
public void testBracedURILiteral_PredefinedEntityRef() {
Lexer lexer = new XQueryLexer();
// NOTE: The predefined entity reference names are not validated by the lexer, as some
// XQuery processors support HTML predefined entities. Shifting the name validation to
// the parser allows proper validation errors to be generated.
lexer.start("Q{One&abc;&aBc;&Abc;&ABC;&a4;&a;Two}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&abc;", 26, 5, 10, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&aBc;", 26, 10, 15, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&Abc;", 26, 15, 20, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&ABC;", 26, 20, 25, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a4;", 26, 25, 29, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "&a;", 26, 29, 32, XQueryTokenType.PREDEFINED_ENTITY_REFERENCE);
matchToken(lexer, "Two", 26, 32, 35, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 35, 36, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 36, 36, null);
lexer.start("Q{&}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 3, 4, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 4, 4, null);
lexer.start("Q{&abc!}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&abc", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "!", 26, 6, 7, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 7, 8, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 8, 8, null);
lexer.start("Q{& }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 3, 4, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("Q{&");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&", 26, 2, 3, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 3, 3, null);
lexer.start("Q{&abc");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&abc", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 6, null);
lexer.start("Q{&;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&;", 26, 2, 4, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
}
// endregion
// region XQuery 3.0 :: BracedURILiteral + CharRef
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testBracedURILiteral_CharRef_Octal() {
Lexer lexer = new XQueryLexer();
lexer.start("Q{OneTwo}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 26, 5, 10, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 26, 10, 13, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 13, 14, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 14, 14, null);
lexer.start("Q{&#}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 4, 5, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 5, 5, null);
lexer.start("Q{&# }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 4, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("Q{&#");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#", 26, 2, 4, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 4, 4, null);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 6, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 6, null);
lexer.start("Q{&#;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#;", 26, 2, 5, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
}
@Specification(name="XQuery 3.0", reference="https://www.w3.org/TR/xquery-30/#doc-xquery30-BracedURILiteral")
@Specification(name="XQuery 1.0 2ed", reference="https://www.w3.org/TR/2010/REC-xquery-20101214/#prod-xquery-CharRef")
@Specification(name="XML 1.0 5ed", reference="https://www.w3.org/TR/2008/REC-xml-20081126/#NT-CharRef")
public void testBracedURILiteral_CharRef_Hexadecimal() {
Lexer lexer = new XQueryLexer();
lexer.start("Q{One ®ÜTwo}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "One", 26, 2, 5, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, " ", 26, 5, 11, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "®", 26, 11, 17, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Ü", 26, 17, 23, XQueryTokenType.CHARACTER_REFERENCE);
matchToken(lexer, "Two", 26, 23, 26, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 26, 27, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 27, 27, null);
lexer.start("Q{&#x}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "}", 26, 5, 6, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 6, 6, null);
lexer.start("Q{&#x }");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, " ", 26, 5, 6, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 6, 7, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 7, 7, null);
lexer.start("Q{&#x");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x", 26, 2, 5, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 5, 5, null);
lexer.start("Q{");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "", 26, 2, 7, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 7, 7, null);
lexer.start("Q{&#x;G;g;&#xg2;}");
matchToken(lexer, "Q{", 0, 0, 2, XQueryTokenType.BRACED_URI_LITERAL_START);
matchToken(lexer, "&#x;", 26, 2, 6, XQueryTokenType.EMPTY_ENTITY_REFERENCE);
matchToken(lexer, "", 26, 6, 10, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "G;", 26, 10, 12, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "", 26, 12, 16, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g;", 26, 16, 18, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "&#x", 26, 18, 21, XQueryTokenType.PARTIAL_ENTITY_REFERENCE);
matchToken(lexer, "g2;", 26, 21, 24, XQueryTokenType.STRING_LITERAL_CONTENTS);
matchToken(lexer, "}", 26, 24, 25, XQueryTokenType.BRACED_URI_LITERAL_END);
matchToken(lexer, "", 0, 25, 25, null);
}
// endregion
// region Update Facility 1.0 :: FunctionDecl
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-FunctionDecl")
public void testFunctionDecl_UpdateFacility10() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "updating", XQueryTokenType.K_UPDATING);
matchSingleToken(lexer, "function", XQueryTokenType.K_FUNCTION);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "external", XQueryTokenType.K_EXTERNAL);
}
// endregion
// region Update Facility 1.0 :: RevalidationDecl
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-RevalidationDecl")
public void testRevalidationDecl() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "declare", XQueryTokenType.K_DECLARE);
matchSingleToken(lexer, "revalidation", XQueryTokenType.K_REVALIDATION);
matchSingleToken(lexer, "strict", XQueryTokenType.K_STRICT);
matchSingleToken(lexer, "lax", XQueryTokenType.K_LAX);
matchSingleToken(lexer, "skip", XQueryTokenType.K_SKIP);
}
// endregion
// region Update Facility 1.0 :: InsertExprTargetChoice
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-InsertExprTargetChoice")
public void testInsertExprTargetChoice() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "first", XQueryTokenType.K_FIRST);
matchSingleToken(lexer, "last", XQueryTokenType.K_LAST);
matchSingleToken(lexer, "into", XQueryTokenType.K_INTO);
matchSingleToken(lexer, "after", XQueryTokenType.K_AFTER);
matchSingleToken(lexer, "before", XQueryTokenType.K_BEFORE);
}
// endregion
// region Update Facility 1.0 :: InsertExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-InsertExpr")
public void testInsertExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "insert", XQueryTokenType.K_INSERT);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "nodes", XQueryTokenType.K_NODES);
}
// endregion
// region Update Facility 1.0 :: DeleteExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-DeleteExpr")
public void testDeleteExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "delete", XQueryTokenType.K_DELETE);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "nodes", XQueryTokenType.K_NODES);
}
// endregion
// region Update Facility 1.0 :: ReplaceExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-ReplaceExpr")
public void testReplaceExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "replace", XQueryTokenType.K_REPLACE);
matchSingleToken(lexer, "value", XQueryTokenType.K_VALUE);
matchSingleToken(lexer, "of", XQueryTokenType.K_OF);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "with", XQueryTokenType.K_WITH);
}
// endregion
// region Update Facility 1.0 :: RenameExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-RenameExpr")
public void testRenameExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "rename", XQueryTokenType.K_RENAME);
matchSingleToken(lexer, "node", XQueryTokenType.K_NODE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
}
// endregion
// region Update Facility 1.0 :: TransformExpr
@Specification(name="XQuery Update Facility 1.0", reference="https://www.w3.org/TR/2011/REC-xquery-update-10-20110317/#prod-xquery-TransformExpr")
public void testTransformExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "copy", XQueryTokenType.K_COPY);
matchSingleToken(lexer, "$", XQueryTokenType.VARIABLE_INDICATOR);
matchSingleToken(lexer, ":=", XQueryTokenType.ASSIGN_EQUAL);
matchSingleToken(lexer, ",", XQueryTokenType.COMMA);
matchSingleToken(lexer, "modify", XQueryTokenType.K_MODIFY);
matchSingleToken(lexer, "return", XQueryTokenType.K_RETURN);
}
// endregion
// region Update Facility 3.0 :: CompatibilityAnnotation
@Specification(name="XQuery Update Facility 3.0", reference="https://www.w3.org/TR/2015/WD-xquery-update-30-20150219/#prod-xquery30-CompatibilityAnnotation")
public void testCompatibilityAnnotation() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "updating", XQueryTokenType.K_UPDATING);
}
// endregion
// region MarkLogic 6.0 :: CompatibilityAnnotation
public void testCompatibilityAnnotation_MarkLogic() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "private", XQueryTokenType.K_PRIVATE);
}
// endregion
// region MarkLogic 6.0 :: ValidateExpr
public void testValidateExpr_ValidateAs() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "validate", XQueryTokenType.K_VALIDATE);
matchSingleToken(lexer, "as", XQueryTokenType.K_AS);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region MarkLogic 6.0 :: ForwardAxis
public void testForwardAxis_MarkLogic() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "namespace", XQueryTokenType.K_NAMESPACE);
matchSingleToken(lexer, "property", XQueryTokenType.K_PROPERTY);
matchSingleToken(lexer, "::", XQueryTokenType.AXIS_SEPARATOR);
}
// endregion
// region MarkLogic 6.0 :: BinaryExpr
public void testBinaryExpr() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "binary", XQueryTokenType.K_BINARY);
matchSingleToken(lexer, "{", XQueryTokenType.BLOCK_OPEN);
matchSingleToken(lexer, "}", XQueryTokenType.BLOCK_CLOSE);
}
// endregion
// region MarkLogic 6.0 :: BinaryKindTest
public void testBinaryKindTest() {
Lexer lexer = new XQueryLexer();
matchSingleToken(lexer, "binary", XQueryTokenType.K_BINARY);
matchSingleToken(lexer, "(", XQueryTokenType.PARENTHESIS_OPEN);
matchSingleToken(lexer, ")", XQueryTokenType.PARENTHESIS_CLOSE);
}
// endregion
}
|
Fix the CompBinaryConstructor construct name in the Lexer tests.
|
src/test/java/uk/co/reecedunn/intellij/plugin/xquery/tests/lexer/XQueryLexerTest.java
|
Fix the CompBinaryConstructor construct name in the Lexer tests.
|
|
Java
|
apache-2.0
|
836347abefb6da14a0171de82d1d1b0cff6d7429
| 0
|
pentaho/big-data-plugin,pentaho/big-data-plugin,pentaho/big-data-plugin
|
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2019-2022 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.impl.browse.model;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.pentaho.big.data.impl.browse.NamedClusterProvider;
import org.pentaho.di.plugins.fileopensave.api.providers.BaseEntity;
import org.pentaho.di.plugins.fileopensave.api.providers.File;
import java.util.Date;
public class NamedClusterFile extends BaseEntity implements File {
public static final String TYPE = "file";
public NamedClusterFile() {
// Needed for JSON marshalling
}
@Override public String getType() {
return TYPE;
}
@Override public String getProvider() {
return NamedClusterProvider.TYPE;
}
public static NamedClusterFile create( String parent, FileObject fileObject ) {
NamedClusterFile namedClusterFile = new NamedClusterFile();
namedClusterFile.setName( fileObject.getName().getBaseName() );
namedClusterFile.setPath( fileObject.getName().getFriendlyURI() );
namedClusterFile.setParent( parent );
namedClusterFile.setRoot( NamedClusterProvider.NAME );
namedClusterFile.setCanEdit( true );
try {
namedClusterFile.setDate( new Date( fileObject.getContent().getLastModifiedTime() ) );
} catch ( FileSystemException ignored ) {
namedClusterFile.setDate( new Date() );
}
return namedClusterFile;
}
@Override public boolean equals( Object obj ) {
// If the object is compared with itself then return true
if ( obj == this ) {
return true;
}
if ( !( obj instanceof NamedClusterFile ) ) {
return false;
}
NamedClusterFile compare = (NamedClusterFile) obj;
return compare.getProvider().equals( getProvider() )
&& ( ( compare.getPath() == null && getPath() == null ) || compare.getPath().equals( getPath() ) );
}
}
|
kettle-plugins/browse/src/main/java/org/pentaho/big/data/impl/browse/model/NamedClusterFile.java
|
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2019 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.big.data.impl.browse.model;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.pentaho.big.data.impl.browse.NamedClusterProvider;
import org.pentaho.di.plugins.fileopensave.api.providers.BaseEntity;
import org.pentaho.di.plugins.fileopensave.api.providers.File;
import java.util.Date;
public class NamedClusterFile extends BaseEntity implements File {
public static final String TYPE = "file";
public NamedClusterFile() {
// Needed for JSON marshalling
}
@Override public String getType() {
return TYPE;
}
@Override public String getProvider() {
return NamedClusterProvider.TYPE;
}
public static NamedClusterFile create( String parent, FileObject fileObject ) {
NamedClusterFile namedClusterFile = new NamedClusterFile();
namedClusterFile.setName( fileObject.getName().getBaseName() );
namedClusterFile.setPath( fileObject.getName().getFriendlyURI() );
namedClusterFile.setParent( parent );
namedClusterFile.setRoot( NamedClusterProvider.NAME );
namedClusterFile.setCanEdit( true );
try {
namedClusterFile.setDate( new Date( fileObject.getContent().getLastModifiedTime() ) );
} catch ( FileSystemException ignored ) {
namedClusterFile.setDate( new Date() );
}
return namedClusterFile;
}
}
|
[BACKLOG-36268] Need to override the equals method for all file types to
ensure proper function within the Eclipse widgets.
|
kettle-plugins/browse/src/main/java/org/pentaho/big/data/impl/browse/model/NamedClusterFile.java
|
[BACKLOG-36268] Need to override the equals method for all file types to ensure proper function within the Eclipse widgets.
|
|
Java
|
apache-2.0
|
8a849057ba8a70fb6be25bd983084d189b5e7703
| 0
|
cacristo/ceos-project
|
package org.jaexcel.framework.JAEX.definition;
/**
* This will define all the error messages related to the framework. <br>
*
* @version 1.0
* @author Carlos CRISTO ABREU
*/
public enum ExceptionMessage {
/* declared messages of ConfigurationException incompatible */
ConfigurationException_XlsConfigurationMissing("The annotation XlsConfiguration is missing. Review your configuration."),
ConfigurationException_XlsSheetMissing("The annotation XlsSheet is missing. Review your configuration."),
ConfigurationException_CellStyleMissing("Cell style configuration is missing. Review your configuration."),
ConfigurationException_Conflict("Conflict at the configuration. Review your configuration."),
// TODO see the below message will be applied (remove if not)
ConfigurationException_Incompatible("Incompatible configuration. Review your configuration."),
/* declared messages of ConverterException */
ConverterException_Default("Problem while convert the element."),
ConverterException_String("Problem while convert the string element."),
ConverterException_BigDecimal("Problem while convert the BigDecimal element."),
ConverterException_Double("Problem while convert the double element."),
ConverterException_Float("Problem while convert the float element."),
ConverterException_Integer("Problem while convert the integer element."),
ConverterException_Long("Problem while convert the long element."),
ConverterException_Boolean("Problem while convert the boolean element."),
ConverterException_Date("Problem while convert the Date element, review your decorator mask."),
ConverterException_Decorator("Problem while apply the decorator."),
/* declared messages of ElementException */
ElementException_NullObject("The entry object is null. Make sure you are sending a correct object."),
ElementException_EmptyObject("The entry object is empty. Make sure you are sending a correct object."),
/* declared messages of SheetException */
SheetException_CreationWorkbook("Problem while creating the Workbook. Review your configuration."),
SheetException_CreationSheet("Problem while creating the Sheet. Review your configuration."),
// TODO see the below messages will be applied (remove if not)
SheetException_SaveWorkbook("Problem while saving the Workbook."),
SheetException_UpdateSheet("Problem while add a new Sheet.");
private String message;
private ExceptionMessage(String msg) {
message = msg;
}
/**
* Get the error message.
*
* @return the message
*/
public String getMessage() {
return message;
}
}
|
JAEX/src/main/java/org/jaexcel/framework/JAEX/definition/ExceptionMessage.java
|
package org.jaexcel.framework.JAEX.definition;
/**
* This will define all the error messages related to the framework. <br>
*
* @version 1.0
* @author Carlos CRISTO ABREU
*/
public enum ExceptionMessage {
/* declared messages of ConfigurationException incompatible */
ConfigurationException_Missing("Header configuration is missing. Review your configuration."),
ConfigurationException_Incompatible("Incompatible configuration. Review your configuration."),
ConfigurationException_Conflit("Conflit at the configuration. Review your configuration."),
/* declared messages of ConverterException */
ConverterException_Default("Problem while convert the element."),
ConverterException_String("Problem while convert the string element."),
ConverterException_BigDecimal("Problem while convert the BigDecimal element."),
ConverterException_Double("Problem while convert the double element."),
ConverterException_Float("Problem while convert the float element."),
ConverterException_Integer("Problem while convert the integer element."),
ConverterException_Long("Problem while convert the long element."),
ConverterException_Boolean("Problem while convert the boolean element."),
ConverterException_Date("Problem while convert the Date element, review your decorator mask."),
ConverterException_Decorator("Problem while apply the decorator."),
/* declared messages of ElementException */
ElementException_NullObject("The entry object is null. Make sure you are sending a correct object."),
ElementException_EmptyObject("The entry object is empty. Make sure you are sending a correct object."),
ElementException_Row("Hola Mundo"),
ElementException_Cell("Hola Mundo"),
/* declared messages of SheetException */
SheetException_CreationWorkbook("Problem while creating the Workbook."),
SheetException_SaveWorkbook("Problem while saving the Workbook."),
SheetException_CreationSheet("Problem while creating the Sheet."),
SheetException_UpdateSheet("Problem while add a new Sheet.");
private String message;
private ExceptionMessage(String msg) {
message = msg;
}
/**
* Get the error message.
*
* @return the message
*/
public String getMessage() {
return message;
}
}
|
Upgrade exceptions messages
|
JAEX/src/main/java/org/jaexcel/framework/JAEX/definition/ExceptionMessage.java
|
Upgrade exceptions messages
|
|
Java
|
apache-2.0
|
a72375e5ed56dc39d1f6e8b36ca52763d892a3ef
| 0
|
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
|
package ca.corefacility.bioinformatics.irida.ria.unit.web.analysis;
import java.util.*;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.MessageSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.ria.web.cart.CartController;
import ca.corefacility.bioinformatics.irida.ria.web.cart.components.Cart;
import ca.corefacility.bioinformatics.irida.ria.web.cart.dto.*;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.SequencingObjectService;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class CartControllerTest {
SampleService sampleService;
ProjectService projectService;
UserService userService;
MessageSource messageSource;
CartController controller;
SequencingObjectService sequencingObjectService;
Cart cart;
private Long projectId;
Set<Long> sampleIds;
private Project project;
private Set<Sample> samples;
@Before
public void setup() {
sampleService = mock(SampleService.class);
projectService = mock(ProjectService.class);
userService = mock(UserService.class);
messageSource = mock(MessageSource.class);
sequencingObjectService = mock(SequencingObjectService.class);
cart = new Cart(projectService, messageSource);
String iridaPipelinePluginStyle = "";
controller = new CartController(sampleService, userService, projectService, sequencingObjectService,
iridaPipelinePluginStyle, cart);
testData();
// Set up messages
when(messageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))).thenReturn("A i18n string has been returned");
}
@Test
public void testAddProjectSample() {
AddToCartRequest request = new AddToCartRequest(1L,
ImmutableSet.of(new CartSampleRequest(1L, "sample1"), new CartSampleRequest(2L, "sample2"),
new CartSampleRequest(3L, "sample3")));
AddToCartResponse response = controller.addSamplesToCart(request, Locale.ENGLISH);
assertEquals("Should have 3 samples in the cart", 3, response.getCount());
assertNull("Should be no duplicated", response.getDuplicate());
assertNull("Should be no existing", response.getExisting());
// Try adding a sample the second time.
AddToCartRequest secondRequest = new AddToCartRequest(1L, ImmutableSet.of(new CartSampleRequest(1L, "sample1"), new CartSampleRequest(4L, "sample4")));
AddToCartResponse secondsResponse = controller.addSamplesToCart(secondRequest, Locale.ENGLISH);
assertNotNull("Should indicate that there was an existing sample added", secondsResponse.getExisting());
assertEquals("Should now be 4 samples in the cart", 4, secondsResponse.getCount());
assertNull("Should be no duplicated", response.getDuplicate());
// Try adding a sample with a duplicate sample name, but different ID.
AddToCartRequest thirdRequest = new AddToCartRequest(1L, ImmutableSet.of(new CartSampleRequest(5L, "sample1")));
AddToCartResponse thirdResponse = controller.addSamplesToCart(thirdRequest, Locale.ENGLISH);
assertNotNull("Should give a duplicate sample name message", thirdResponse);
assertEquals("Should not have added the duplicate to the cart", 4, thirdResponse.getCount());
}
@Test
public void testClearCart() {
// Add some samples to the cart
AddToCartRequest addToCartRequest = new AddToCartRequest(1L,
ImmutableSet.of(new CartSampleRequest(1L, "sample2"), new CartSampleRequest(4L, "sample4"),
new CartSampleRequest(5L, "sample1")));
AddToCartResponse addToCartResponse = controller.addSamplesToCart(addToCartRequest, Locale.ENGLISH);
assertEquals("Should be 3 samples in the cart", 3, addToCartResponse.getCount());
// Test emptying the cart.
controller.clearCart();
assertEquals("The cart should be empty", 0, cart.get()
.size());
}
@Test
public void testRemoveSamplesFromCart() {
// Add some samples to the cart
AddToCartRequest addToCartRequest = new AddToCartRequest(1L,
ImmutableSet.of(new CartSampleRequest(1L, "sample2"), new CartSampleRequest(4L, "sample4"),
new CartSampleRequest(5L, "sample1")));
AddToCartResponse addToCartResponse = controller.addSamplesToCart(addToCartRequest, Locale.ENGLISH);
assertEquals("Should be 3 samples in the cart", 3, addToCartResponse.getCount());
// Test removing a single sample from the cart
RemoveSampleRequest removeSampleRequest = new RemoveSampleRequest(1L, 1L);
RemoveSampleResponse removeSampleResponse = controller.removeSamplesFromCart(removeSampleRequest);
assertEquals("After removing a sample there should be 2 left in cart.", 2, removeSampleResponse.getCount());
}
@Test
public void testRemoveProjectFromCart() {
// Add some samples to the cart
AddToCartRequest addToCartRequest = new AddToCartRequest(1L,
ImmutableSet.of(new CartSampleRequest(1L, "sample2")));
controller.addSamplesToCart(addToCartRequest, Locale.ENGLISH);
AddToCartRequest addToCartRequest2 = new AddToCartRequest(2L,
ImmutableSet.of(new CartSampleRequest(11L, "sample4"), new CartSampleRequest(12L, "sample1")));
AddToCartResponse addToCartResponse2 = controller.addSamplesToCart(addToCartRequest2, Locale.ENGLISH);
assertEquals("Should be 3 samples in the cart", 3, addToCartResponse2.getCount());
RemoveSampleResponse removeSampleResponse = controller.removeProjectFromCart(1L);
assertEquals("There are 2 different projects in the cart, therefore there still should be 2 samples", 2,
removeSampleResponse.getCount());
}
@Test
@Ignore
public void testGetCartMap() {
RequestAttributes ra = new ServletRequestAttributes(new MockHttpServletRequest());
RequestContextHolder.setRequestAttributes(ra);
Map<Project, Set<Sample>> selected = new HashMap<>();
selected.put(project, samples);
controller.addSelected(selected, Locale.ENGLISH);
//
// Map<String, Object> cartMap = controller.getCartMap();
// assertTrue(cartMap.containsKey("projects"));
// @SuppressWarnings("unchecked")
// List<Map<String, Object>> pList = (List<Map<String, Object>>) cartMap.get("projects");
// Map<String, Object> projectMap = pList.iterator().next();
//
// assertTrue(projectMap.containsKey("samples"));
// @SuppressWarnings("unchecked")
// List<Map<String, Object>> sList = (List<Map<String, Object>>) projectMap.get("samples");
// for (Map<String, Object> map : sList) {
// assertTrue(map.containsKey("id"));
// assertTrue(map.containsKey("label"));
// }
}
private void testData() {
projectId = 1L;
sampleIds = Sets.newHashSet(2L, 3L);
project = new Project("project");
project.setId(projectId);
samples = new HashSet<>();
when(projectService.read(projectId)).thenReturn(project);
for (Long id : sampleIds) {
Sample sample = new Sample("sample" + id);
sample.setId(id);
samples.add(sample);
when(sampleService.getSampleForProject(project, id)).thenReturn(new ProjectSampleJoin(project,sample, true));
}
// Need a second project to test removing a project from the cart.
Project project2 = new Project("Project2");
project2.setId(2L);
when(projectService.read(2L)).thenReturn(project2);
Set<Long> sampleIds2 = Sets.newHashSet(11L, 12L, 13L, 14L);
for (Long id : sampleIds2) {
Sample sample = new Sample("sample" + id);
sample.setId(id);
samples.add(sample);
when(sampleService.getSampleForProject(project2, id)).thenReturn(
new ProjectSampleJoin(project2, sample, true));
}
final ArrayList<Long> ids = new ArrayList<>(sampleIds);
when(messageSource.getMessage("cart.in-cart", new Object[] {}, Locale.ENGLISH)).thenReturn(
"Sample already in cart");
when(messageSource.getMessage("cart.excluded", new Object[] { "sample1" }, Locale.ENGLISH)).thenReturn(
"Sample name is already in the cart, no duplicate names please.");
when(sampleService.getSamplesInProject(project, ids)).thenReturn(new ArrayList<>(samples));
ArrayList<Long> subIds = Lists.newArrayList(sampleIds.iterator().next());
when(sampleService.getSamplesInProject(project, subIds)).thenReturn(samples.stream().filter(x -> Objects.equals(
x.getId(), subIds.get(0))).collect(
Collectors.toList()));
}
}
|
src/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/analysis/CartControllerTest.java
|
package ca.corefacility.bioinformatics.irida.ria.unit.web.analysis;
import java.util.*;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.MessageSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import ca.corefacility.bioinformatics.irida.model.joins.Join;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.ria.web.cart.CartController;
import ca.corefacility.bioinformatics.irida.ria.web.cart.components.Cart;
import ca.corefacility.bioinformatics.irida.ria.web.cart.dto.AddToCartRequest;
import ca.corefacility.bioinformatics.irida.ria.web.cart.dto.AddToCartResponse;
import ca.corefacility.bioinformatics.irida.ria.web.cart.dto.CartSampleRequest;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.SequencingObjectService;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class CartControllerTest {
SampleService sampleService;
ProjectService projectService;
UserService userService;
MessageSource messageSource;
CartController controller;
SequencingObjectService sequencingObjectService;
Cart cart;
private Long projectId;
Set<Long> sampleIds;
private Project project;
private Set<Sample> samples;
@Before
public void setup() {
sampleService = mock(SampleService.class);
projectService = mock(ProjectService.class);
userService = mock(UserService.class);
messageSource = mock(MessageSource.class);
sequencingObjectService = mock(SequencingObjectService.class);
cart = new Cart(projectService, messageSource);
String iridaPipelinePluginStyle = "";
controller = new CartController(sampleService, userService, projectService, sequencingObjectService,
iridaPipelinePluginStyle, cart);
testData();
// Set up messages
when(messageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))).thenReturn("A i18n string has been returned");
}
@Test
public void testAddProjectSample() {
AddToCartRequest request = new AddToCartRequest(1L,
ImmutableSet.of(new CartSampleRequest(1L, "sample1"), new CartSampleRequest(2L, "sample2"),
new CartSampleRequest(3L, "sample3")));
AddToCartResponse response = controller.addSamplesToCart(request, Locale.ENGLISH);
assertEquals("Should have 3 samples in the cart", 3, response.getCount());
assertNull("Should be no duplicated", response.getDuplicate());
assertNull("Should be no existing", response.getExisting());
// Try adding a sample the second time.
AddToCartRequest secondRequest = new AddToCartRequest(1L, ImmutableSet.of(new CartSampleRequest(1L, "sample1"), new CartSampleRequest(4L, "sample4")));
AddToCartResponse secondsResponse = controller.addSamplesToCart(secondRequest, Locale.ENGLISH);
assertNotNull("Should indicate that there was an existing sample added", secondsResponse.getExisting());
assertEquals("Should now be 4 samples in the cart", 4, secondsResponse.getCount());
assertNull("Should be no duplicated", response.getDuplicate());
// Try adding a sample with a duplicate sample name, but different ID.
AddToCartRequest thirdRequest = new AddToCartRequest(1L, ImmutableSet.of(new CartSampleRequest(5L, "sample1")));
AddToCartResponse thirdResponse = controller.addSamplesToCart(thirdRequest, Locale.ENGLISH);
assertNotNull("Should give a duplicate sample name message", thirdResponse);
assertEquals("Should not have added the diplicate to the cart", 4, thirdResponse.getCount());
}
@Test
@Ignore
public void testRemoveProjectSamples() {
// Map<Project, Set<Sample>> selected = new HashMap<>();
// selected.put(project, samples);
// controller.addSelected(selected, Locale.ENGLISH);
//
// Set<Long> subIds = Sets.newHashSet(sampleIds.iterator().next());
//
// controller.removeProjectSamples(projectId, subIds);
//
// verify(projectService).read(projectId);
// verify(sampleService).getSamplesInProject(project, new ArrayList<>(subIds));
//
// Map<Project, List<Sample>> response = controller.getSelected();
//
// assertEquals(1, response.keySet().size());
// Project projectKey = selected.keySet().iterator().next();
// assertEquals(project, projectKey);
// for (Sample s : selected.get(projectKey)) {
// assertFalse(subIds.contains(s.getId()));
// }
}
@Test
@Ignore
public void testRemoveProjectSample() {
// Map<Project, Set<Sample>> selected = new HashMap<>();
// selected.put(project, samples);
// controller.addSelected(selected, Locale.ENGLISH);
// Sample sample = samples.iterator().next();
//
// controller.removeProjectSample(projectId, sample.getId());
//
// Map<Project, List<Sample>> response = controller.getSelected();
// assertEquals(1, response.keySet().size());
// assertFalse(response.get(project).contains(sample));
}
@Test
@Ignore
public void testRemoveAllProjectSamples() {
// Map<Project, Set<Sample>> selected = new HashMap<>();
// selected.put(project, samples);
// controller.addSelected(selected, Locale.ENGLISH);
//
// controller.removeProjectSamples(projectId, sampleIds);
//
// verify(projectService).read(projectId);
// verify(sampleService).getSamplesInProject(project, Lists.newArrayList(sampleIds));
//
// Map<Project, List<Sample>> response = controller.getSelected();
//
// assertFalse("project should have been removed because all samples were removed", selected.containsKey(project));
}
@Test
@Ignore
public void testClearCart() {
Map<String, Object> clearCart = controller.clearCart();
assertTrue((boolean) clearCart.get("success"));
Map<Project, List<Sample>> selected = controller.getSelected();
assertTrue(selected.isEmpty());
}
@Test
@Ignore
public void testAddProject() {
controller.addProject(projectId, Locale.ENGLISH);
List<Join<Project, Sample>> joins = new ArrayList<>();
samples.forEach((s) -> {
joins.add(new ProjectSampleJoin(project, s, true));
});
when(sampleService.getSamplesForProject(project)).thenReturn(joins);
verify(projectService).read(projectId);
verify(sampleService).getSamplesForProject(project);
Map<Project, List<Sample>> selected = controller.getSelected();
assertEquals(1, selected.keySet().size());
Project projectKey = selected.keySet().iterator().next();
assertEquals(project, projectKey);
for (Sample s : selected.get(projectKey)) {
assertTrue(sampleIds.contains(s.getId()));
}
}
@Test
@Ignore
public void testRemoveProject() {
// controller.removeProject(projectId);
// verify(projectService).read(projectId);
}
@Test
@Ignore
public void testGetCartMap() {
RequestAttributes ra = new ServletRequestAttributes(new MockHttpServletRequest());
RequestContextHolder.setRequestAttributes(ra);
Map<Project, Set<Sample>> selected = new HashMap<>();
selected.put(project, samples);
controller.addSelected(selected, Locale.ENGLISH);
//
// Map<String, Object> cartMap = controller.getCartMap();
// assertTrue(cartMap.containsKey("projects"));
// @SuppressWarnings("unchecked")
// List<Map<String, Object>> pList = (List<Map<String, Object>>) cartMap.get("projects");
// Map<String, Object> projectMap = pList.iterator().next();
//
// assertTrue(projectMap.containsKey("samples"));
// @SuppressWarnings("unchecked")
// List<Map<String, Object>> sList = (List<Map<String, Object>>) projectMap.get("samples");
// for (Map<String, Object> map : sList) {
// assertTrue(map.containsKey("id"));
// assertTrue(map.containsKey("label"));
// }
}
private void testData() {
projectId = 1L;
sampleIds = Sets.newHashSet(2L, 3L);
project = new Project("project");
project.setId(projectId);
samples = new HashSet<>();
when(projectService.read(projectId)).thenReturn(project);
for (Long id : sampleIds) {
Sample sample = new Sample("sample" + id);
sample.setId(id);
samples.add(sample);
when(sampleService.getSampleForProject(project, id)).thenReturn(new ProjectSampleJoin(project,sample, true));
}
final ArrayList<Long> ids = new ArrayList<>(sampleIds);
when(messageSource.getMessage("cart.in-cart", new Object[] {}, Locale.ENGLISH)).thenReturn(
"Sample already in cart");
when(messageSource.getMessage("cart.excluded", new Object[] { "sample1" }, Locale.ENGLISH)).thenReturn(
"Sample name is already in the cart, no duplicate names please.");
when(sampleService.getSamplesInProject(project, ids)).thenReturn(new ArrayList<>(samples));
ArrayList<Long> subIds = Lists.newArrayList(sampleIds.iterator().next());
when(sampleService.getSamplesInProject(project, subIds)).thenReturn(samples.stream().filter(x -> Objects.equals(
x.getId(), subIds.get(0))).collect(
Collectors.toList()));
}
}
|
This is a redundant test class.
Signed-off-by: Josh Adam <8493dc4643ddc08e2ef6b4cf76c12d4ffb7203d1@canada.ca>
|
src/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/analysis/CartControllerTest.java
|
This is a redundant test class.
|
|
Java
|
apache-2.0
|
d3424bfed43c927df54e775c1450934368476c80
| 0
|
androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity;
import android.annotation.SuppressLint;
import android.os.Build;
import android.window.OnBackInvokedCallback;
import android.window.OnBackInvokedDispatcher;
import androidx.annotation.DoNotInline;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.annotation.RequiresApi;
import androidx.core.os.BuildCompat;
import androidx.core.util.Consumer;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import java.util.ArrayDeque;
import java.util.Iterator;
/**
* Dispatcher that can be used to register {@link OnBackPressedCallback} instances for handling
* the {@link ComponentActivity#onBackPressed()} callback via composition.
* <pre>
* public class FormEntryFragment extends Fragment {
* {@literal @}Override
* public void onAttach({@literal @}NonNull Context context) {
* super.onAttach(context);
* OnBackPressedCallback callback = new OnBackPressedCallback(
* true // default to enabled
* ) {
* {@literal @}Override
* public void handleOnBackPressed() {
* showAreYouSureDialog();
* }
* };
* requireActivity().getOnBackPressedDispatcher().addCallback(
* this, // LifecycleOwner
* callback);
* }
* }
* </pre>
*/
public final class OnBackPressedDispatcher {
@Nullable
private final Runnable mFallbackOnBackPressed;
@SuppressWarnings("WeakerAccess") /* synthetic access */
final ArrayDeque<OnBackPressedCallback> mOnBackPressedCallbacks = new ArrayDeque<>();
private Consumer<Boolean> mEnabledConsumer;
private OnBackInvokedCallback mOnBackInvokedCallback;
private OnBackInvokedDispatcher mInvokedDispatcher;
private boolean mBackInvokedCallbackRegistered = false;
/**
* Sets the {@link OnBackInvokedDispatcher} for handling system back for Android SDK T+.
*
* @param invoker the OnBackInvokedDispatcher to be set on this dispatcher
*/
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public void setOnBackInvokedDispatcher(@NonNull OnBackInvokedDispatcher invoker) {
mInvokedDispatcher = invoker;
updateBackInvokedCallbackState();
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
void updateBackInvokedCallbackState() {
boolean shouldBeRegistered = hasEnabledCallbacks();
if (mInvokedDispatcher != null) {
if (shouldBeRegistered && !mBackInvokedCallbackRegistered) {
Api33Impl.registerOnBackInvokedCallback(
mInvokedDispatcher,
OnBackInvokedDispatcher.PRIORITY_OVERLAY,
mOnBackInvokedCallback
);
mBackInvokedCallbackRegistered = true;
} else if (!shouldBeRegistered && mBackInvokedCallbackRegistered) {
Api33Impl.unregisterOnBackInvokedCallback(mInvokedDispatcher,
mOnBackInvokedCallback);
mBackInvokedCallbackRegistered = false;
}
}
}
/**
* Create a new OnBackPressedDispatcher that dispatches System back button pressed events
* to one or more {@link OnBackPressedCallback} instances.
*/
public OnBackPressedDispatcher() {
this(null);
}
/**
* Create a new OnBackPressedDispatcher that dispatches System back button pressed events
* to one or more {@link OnBackPressedCallback} instances.
*
* @param fallbackOnBackPressed The Runnable that should be triggered if
* {@link #onBackPressed()} is called when {@link #hasEnabledCallbacks()} returns false.
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
public OnBackPressedDispatcher(@Nullable Runnable fallbackOnBackPressed) {
mFallbackOnBackPressed = fallbackOnBackPressed;
if (BuildCompat.isAtLeastT()) {
mEnabledConsumer = aBoolean -> {
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
}
};
mOnBackInvokedCallback = Api33Impl.createOnBackInvokedCallback(this::onBackPressed);
}
}
/**
* Add a new {@link OnBackPressedCallback}. Callbacks are invoked in the reverse order in which
* they are added, so this newly added {@link OnBackPressedCallback} will be the first
* callback to receive a callback if {@link #onBackPressed()} is called.
* <p>
* This method is <strong>not</strong> {@link Lifecycle} aware - if you'd like to ensure that
* you only get callbacks when at least {@link Lifecycle.State#STARTED started}, use
* {@link #addCallback(LifecycleOwner, OnBackPressedCallback)}. It is expected that you
* call {@link OnBackPressedCallback#remove()} to manually remove your callback.
*
* @param onBackPressedCallback The callback to add
*
* @see #onBackPressed()
*/
@MainThread
public void addCallback(@NonNull OnBackPressedCallback onBackPressedCallback) {
addCancellableCallback(onBackPressedCallback);
}
/**
* Internal implementation of {@link #addCallback(OnBackPressedCallback)} that gives
* access to the {@link Cancellable} that specifically removes this callback from
* the dispatcher without relying on {@link OnBackPressedCallback#remove()} which
* is what external developers should be using.
*
* @param onBackPressedCallback The callback to add
* @return a {@link Cancellable} which can be used to {@link Cancellable#cancel() cancel}
* the callback and remove it from the set of OnBackPressedCallbacks.
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@SuppressWarnings("WeakerAccess") /* synthetic access */
@MainThread
@NonNull
Cancellable addCancellableCallback(@NonNull OnBackPressedCallback onBackPressedCallback) {
mOnBackPressedCallbacks.add(onBackPressedCallback);
OnBackPressedCancellable cancellable = new OnBackPressedCancellable(onBackPressedCallback);
onBackPressedCallback.addCancellable(cancellable);
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
onBackPressedCallback.setIsEnabledConsumer(mEnabledConsumer);
}
return cancellable;
}
/**
* Receive callbacks to a new {@link OnBackPressedCallback} when the given
* {@link LifecycleOwner} is at least {@link Lifecycle.State#STARTED started}.
* <p>
* This will automatically call {@link #addCallback(OnBackPressedCallback)} and
* remove the callback as the lifecycle state changes.
* As a corollary, if your lifecycle is already at least
* {@link Lifecycle.State#STARTED started}, calling this method will result in an immediate
* call to {@link #addCallback(OnBackPressedCallback)}.
* <p>
* When the {@link LifecycleOwner} is {@link Lifecycle.State#DESTROYED destroyed}, it will
* automatically be removed from the list of callbacks. The only time you would need to
* manually call {@link OnBackPressedCallback#remove()} is if
* you'd like to remove the callback prior to destruction of the associated lifecycle.
*
* <p>
* If the Lifecycle is already {@link Lifecycle.State#DESTROYED destroyed}
* when this method is called, the callback will not be added.
*
* @param owner The LifecycleOwner which controls when the callback should be invoked
* @param onBackPressedCallback The callback to add
*
* @see #onBackPressed()
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@SuppressLint("LambdaLast")
@MainThread
public void addCallback(@NonNull LifecycleOwner owner,
@NonNull OnBackPressedCallback onBackPressedCallback) {
Lifecycle lifecycle = owner.getLifecycle();
if (lifecycle.getCurrentState() == Lifecycle.State.DESTROYED) {
return;
}
onBackPressedCallback.addCancellable(
new LifecycleOnBackPressedCancellable(lifecycle, onBackPressedCallback));
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
onBackPressedCallback.setIsEnabledConsumer(mEnabledConsumer);
}
}
/**
* Checks if there is at least one {@link OnBackPressedCallback#isEnabled enabled}
* callback registered with this dispatcher.
*
* @return True if there is at least one enabled callback.
*/
@MainThread
public boolean hasEnabledCallbacks() {
Iterator<OnBackPressedCallback> iterator =
mOnBackPressedCallbacks.descendingIterator();
while (iterator.hasNext()) {
if (iterator.next().isEnabled()) {
return true;
}
}
return false;
}
/**
* Trigger a call to the currently added {@link OnBackPressedCallback callbacks} in reverse
* order in which they were added. Only if the most recently added callback is not
* {@link OnBackPressedCallback#isEnabled() enabled}
* will any previously added callback be called.
* <p>
* If {@link #hasEnabledCallbacks()} is <code>false</code> when this method is called, the
* fallback Runnable set by {@link #OnBackPressedDispatcher(Runnable) the constructor}
* will be triggered.
*/
@MainThread
public void onBackPressed() {
Iterator<OnBackPressedCallback> iterator =
mOnBackPressedCallbacks.descendingIterator();
while (iterator.hasNext()) {
OnBackPressedCallback callback = iterator.next();
if (callback.isEnabled()) {
callback.handleOnBackPressed();
return;
}
}
if (mFallbackOnBackPressed != null) {
mFallbackOnBackPressed.run();
}
}
private class OnBackPressedCancellable implements Cancellable {
private final OnBackPressedCallback mOnBackPressedCallback;
OnBackPressedCancellable(OnBackPressedCallback onBackPressedCallback) {
mOnBackPressedCallback = onBackPressedCallback;
}
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@Override
public void cancel() {
mOnBackPressedCallbacks.remove(mOnBackPressedCallback);
mOnBackPressedCallback.removeCancellable(this);
if (BuildCompat.isAtLeastT()) {
mOnBackPressedCallback.setIsEnabledConsumer(null);
updateBackInvokedCallbackState();
}
}
}
private class LifecycleOnBackPressedCancellable implements LifecycleEventObserver,
Cancellable {
private final Lifecycle mLifecycle;
private final OnBackPressedCallback mOnBackPressedCallback;
@Nullable
private Cancellable mCurrentCancellable;
LifecycleOnBackPressedCancellable(@NonNull Lifecycle lifecycle,
@NonNull OnBackPressedCallback onBackPressedCallback) {
mLifecycle = lifecycle;
mOnBackPressedCallback = onBackPressedCallback;
lifecycle.addObserver(this);
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_START) {
mCurrentCancellable = addCancellableCallback(mOnBackPressedCallback);
} else if (event == Lifecycle.Event.ON_STOP) {
// Should always be non-null
if (mCurrentCancellable != null) {
mCurrentCancellable.cancel();
}
} else if (event == Lifecycle.Event.ON_DESTROY) {
cancel();
}
}
@Override
public void cancel() {
mLifecycle.removeObserver(this);
mOnBackPressedCallback.removeCancellable(this);
if (mCurrentCancellable != null) {
mCurrentCancellable.cancel();
mCurrentCancellable = null;
}
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
static class Api33Impl {
private Api33Impl() { }
@DoNotInline
static void registerOnBackInvokedCallback(
Object dispatcher, int priority, Object callback
) {
OnBackInvokedDispatcher onBackInvokedDispatcher = (OnBackInvokedDispatcher) dispatcher;
OnBackInvokedCallback onBackInvokedCallback = (OnBackInvokedCallback) callback;
onBackInvokedDispatcher.registerOnBackInvokedCallback(priority, onBackInvokedCallback);
}
@DoNotInline
static void unregisterOnBackInvokedCallback(Object dispatcher, Object callback) {
OnBackInvokedDispatcher onBackInvokedDispatcher = (OnBackInvokedDispatcher) dispatcher;
OnBackInvokedCallback onBackInvokedCallback = (OnBackInvokedCallback) callback;
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(onBackInvokedCallback);
}
@DoNotInline
static OnBackInvokedCallback createOnBackInvokedCallback(Runnable runnable) {
return runnable::run;
}
}
}
|
activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.java
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity;
import android.annotation.SuppressLint;
import android.os.Build;
import android.window.OnBackInvokedCallback;
import android.window.OnBackInvokedDispatcher;
import androidx.annotation.DoNotInline;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.annotation.RequiresApi;
import androidx.core.os.BuildCompat;
import androidx.core.util.Consumer;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import java.util.ArrayDeque;
import java.util.Iterator;
/**
* Dispatcher that can be used to register {@link OnBackPressedCallback} instances for handling
* the {@link ComponentActivity#onBackPressed()} callback via composition.
* <pre>
* public class FormEntryFragment extends Fragment {
* {@literal @}Override
* public void onAttach({@literal @}NonNull Context context) {
* super.onAttach(context);
* OnBackPressedCallback callback = new OnBackPressedCallback(
* true // default to enabled
* ) {
* {@literal @}Override
* public void handleOnBackPressed() {
* showAreYouSureDialog();
* }
* };
* requireActivity().getOnBackPressedDispatcher().addCallback(
* this, // LifecycleOwner
* callback);
* }
* }
* </pre>
*/
public final class OnBackPressedDispatcher {
@Nullable
private final Runnable mFallbackOnBackPressed;
@SuppressWarnings("WeakerAccess") /* synthetic access */
final ArrayDeque<OnBackPressedCallback> mOnBackPressedCallbacks = new ArrayDeque<>();
private Consumer<Boolean> mEnabledConsumer;
private OnBackInvokedCallback mOnBackInvokedCallback;
private OnBackInvokedDispatcher mInvokedDispatcher;
private boolean mBackInvokedCallbackRegistered = false;
/**
* Sets the {@link OnBackInvokedDispatcher} for handling system back for Android SDK T+.
*
* @param invoker the OnBackInvokedDispatcher to be set on this dispatcher
*/
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public void setOnBackInvokedDispatcher(@NonNull OnBackInvokedDispatcher invoker) {
mInvokedDispatcher = invoker;
updateBackInvokedCallbackState();
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
void updateBackInvokedCallbackState() {
boolean shouldBeRegistered = hasEnabledCallbacks();
if (mInvokedDispatcher != null) {
if (shouldBeRegistered && !mBackInvokedCallbackRegistered) {
Api33Impl.registerOnBackInvokedCallback(
mInvokedDispatcher,
OnBackInvokedDispatcher.PRIORITY_OVERLAY,
mOnBackInvokedCallback
);
mBackInvokedCallbackRegistered = true;
} else if (!shouldBeRegistered && mBackInvokedCallbackRegistered) {
Api33Impl.unregisterOnBackInvokedCallback(mInvokedDispatcher,
mOnBackInvokedCallback);
mBackInvokedCallbackRegistered = false;
}
}
}
/**
* Create a new OnBackPressedDispatcher that dispatches System back button pressed events
* to one or more {@link OnBackPressedCallback} instances.
*/
public OnBackPressedDispatcher() {
this(null);
}
/**
* Create a new OnBackPressedDispatcher that dispatches System back button pressed events
* to one or more {@link OnBackPressedCallback} instances.
*
* @param fallbackOnBackPressed The Runnable that should be triggered if
* {@link #onBackPressed()} is called when {@link #hasEnabledCallbacks()} returns false.
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
public OnBackPressedDispatcher(@Nullable Runnable fallbackOnBackPressed) {
mFallbackOnBackPressed = fallbackOnBackPressed;
if (BuildCompat.isAtLeastT()) {
mEnabledConsumer = aBoolean -> {
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
}
};
mOnBackInvokedCallback = new OnBackInvokedCallback() {
@Override
public void onBackInvoked() {
onBackPressed();
}
};
}
}
/**
* Add a new {@link OnBackPressedCallback}. Callbacks are invoked in the reverse order in which
* they are added, so this newly added {@link OnBackPressedCallback} will be the first
* callback to receive a callback if {@link #onBackPressed()} is called.
* <p>
* This method is <strong>not</strong> {@link Lifecycle} aware - if you'd like to ensure that
* you only get callbacks when at least {@link Lifecycle.State#STARTED started}, use
* {@link #addCallback(LifecycleOwner, OnBackPressedCallback)}. It is expected that you
* call {@link OnBackPressedCallback#remove()} to manually remove your callback.
*
* @param onBackPressedCallback The callback to add
*
* @see #onBackPressed()
*/
@MainThread
public void addCallback(@NonNull OnBackPressedCallback onBackPressedCallback) {
addCancellableCallback(onBackPressedCallback);
}
/**
* Internal implementation of {@link #addCallback(OnBackPressedCallback)} that gives
* access to the {@link Cancellable} that specifically removes this callback from
* the dispatcher without relying on {@link OnBackPressedCallback#remove()} which
* is what external developers should be using.
*
* @param onBackPressedCallback The callback to add
* @return a {@link Cancellable} which can be used to {@link Cancellable#cancel() cancel}
* the callback and remove it from the set of OnBackPressedCallbacks.
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@SuppressWarnings("WeakerAccess") /* synthetic access */
@MainThread
@NonNull
Cancellable addCancellableCallback(@NonNull OnBackPressedCallback onBackPressedCallback) {
mOnBackPressedCallbacks.add(onBackPressedCallback);
OnBackPressedCancellable cancellable = new OnBackPressedCancellable(onBackPressedCallback);
onBackPressedCallback.addCancellable(cancellable);
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
onBackPressedCallback.setIsEnabledConsumer(mEnabledConsumer);
}
return cancellable;
}
/**
* Receive callbacks to a new {@link OnBackPressedCallback} when the given
* {@link LifecycleOwner} is at least {@link Lifecycle.State#STARTED started}.
* <p>
* This will automatically call {@link #addCallback(OnBackPressedCallback)} and
* remove the callback as the lifecycle state changes.
* As a corollary, if your lifecycle is already at least
* {@link Lifecycle.State#STARTED started}, calling this method will result in an immediate
* call to {@link #addCallback(OnBackPressedCallback)}.
* <p>
* When the {@link LifecycleOwner} is {@link Lifecycle.State#DESTROYED destroyed}, it will
* automatically be removed from the list of callbacks. The only time you would need to
* manually call {@link OnBackPressedCallback#remove()} is if
* you'd like to remove the callback prior to destruction of the associated lifecycle.
*
* <p>
* If the Lifecycle is already {@link Lifecycle.State#DESTROYED destroyed}
* when this method is called, the callback will not be added.
*
* @param owner The LifecycleOwner which controls when the callback should be invoked
* @param onBackPressedCallback The callback to add
*
* @see #onBackPressed()
*/
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@SuppressLint("LambdaLast")
@MainThread
public void addCallback(@NonNull LifecycleOwner owner,
@NonNull OnBackPressedCallback onBackPressedCallback) {
Lifecycle lifecycle = owner.getLifecycle();
if (lifecycle.getCurrentState() == Lifecycle.State.DESTROYED) {
return;
}
onBackPressedCallback.addCancellable(
new LifecycleOnBackPressedCancellable(lifecycle, onBackPressedCallback));
if (BuildCompat.isAtLeastT()) {
updateBackInvokedCallbackState();
onBackPressedCallback.setIsEnabledConsumer(mEnabledConsumer);
}
}
/**
* Checks if there is at least one {@link OnBackPressedCallback#isEnabled enabled}
* callback registered with this dispatcher.
*
* @return True if there is at least one enabled callback.
*/
@MainThread
public boolean hasEnabledCallbacks() {
Iterator<OnBackPressedCallback> iterator =
mOnBackPressedCallbacks.descendingIterator();
while (iterator.hasNext()) {
if (iterator.next().isEnabled()) {
return true;
}
}
return false;
}
/**
* Trigger a call to the currently added {@link OnBackPressedCallback callbacks} in reverse
* order in which they were added. Only if the most recently added callback is not
* {@link OnBackPressedCallback#isEnabled() enabled}
* will any previously added callback be called.
* <p>
* If {@link #hasEnabledCallbacks()} is <code>false</code> when this method is called, the
* fallback Runnable set by {@link #OnBackPressedDispatcher(Runnable) the constructor}
* will be triggered.
*/
@MainThread
public void onBackPressed() {
Iterator<OnBackPressedCallback> iterator =
mOnBackPressedCallbacks.descendingIterator();
while (iterator.hasNext()) {
OnBackPressedCallback callback = iterator.next();
if (callback.isEnabled()) {
callback.handleOnBackPressed();
return;
}
}
if (mFallbackOnBackPressed != null) {
mFallbackOnBackPressed.run();
}
}
private class OnBackPressedCancellable implements Cancellable {
private final OnBackPressedCallback mOnBackPressedCallback;
OnBackPressedCancellable(OnBackPressedCallback onBackPressedCallback) {
mOnBackPressedCallback = onBackPressedCallback;
}
@OptIn(markerClass = BuildCompat.PrereleaseSdkCheck.class)
@Override
public void cancel() {
mOnBackPressedCallbacks.remove(mOnBackPressedCallback);
mOnBackPressedCallback.removeCancellable(this);
if (BuildCompat.isAtLeastT()) {
mOnBackPressedCallback.setIsEnabledConsumer(null);
updateBackInvokedCallbackState();
}
}
}
private class LifecycleOnBackPressedCancellable implements LifecycleEventObserver,
Cancellable {
private final Lifecycle mLifecycle;
private final OnBackPressedCallback mOnBackPressedCallback;
@Nullable
private Cancellable mCurrentCancellable;
LifecycleOnBackPressedCancellable(@NonNull Lifecycle lifecycle,
@NonNull OnBackPressedCallback onBackPressedCallback) {
mLifecycle = lifecycle;
mOnBackPressedCallback = onBackPressedCallback;
lifecycle.addObserver(this);
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_START) {
mCurrentCancellable = addCancellableCallback(mOnBackPressedCallback);
} else if (event == Lifecycle.Event.ON_STOP) {
// Should always be non-null
if (mCurrentCancellable != null) {
mCurrentCancellable.cancel();
}
} else if (event == Lifecycle.Event.ON_DESTROY) {
cancel();
}
}
@Override
public void cancel() {
mLifecycle.removeObserver(this);
mOnBackPressedCallback.removeCancellable(this);
if (mCurrentCancellable != null) {
mCurrentCancellable.cancel();
mCurrentCancellable = null;
}
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
static class Api33Impl {
private Api33Impl() { }
@DoNotInline
static void registerOnBackInvokedCallback(
OnBackInvokedDispatcher onBackInvokedDispatcher, int priority,
OnBackInvokedCallback onBackInvokedCallback
) {
onBackInvokedDispatcher.registerOnBackInvokedCallback(priority, onBackInvokedCallback);
}
@DoNotInline
static void unregisterOnBackInvokedCallback(
OnBackInvokedDispatcher onBackInvokedDispatcher,
OnBackInvokedCallback onBackInvokedCallback
) {
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(onBackInvokedCallback);
}
}
}
|
Avoid ClassVerificationErrors in OnBackPressedDispatcher
Although we won't actually call any of the T specific OnBackInvoked APIs
on Android versions prior to T, the class loader does not know that. So
it attempts to load all of the classes and since theose APIs are not
present we get a ClassVerificationError.
We should move any initialization of these classes to static functions
that are specific to API 33.
RelNote: "Initializing a `OnBackPressedDispatcher` will not longer cause
`ClassVerificationError`s when using SDK versions prior to 33."
Test: verified with integration app and running test on 32- devices
Bug: 241739353
Change-Id: Ic32e1fb18a4f17692d4b62ddf9d37bb5e67c2771
|
activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.java
|
Avoid ClassVerificationErrors in OnBackPressedDispatcher
|
|
Java
|
apache-2.0
|
92ca227173ce7341b8ba6a05a0ad9a2815f7aa4c
| 0
|
c963951/briantest
|
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation 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.example.bot.spring.echo;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.impl.SimpleLog;
import org.json.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.github.abola.crawler.CrawlerPack;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Thumbnail;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.MessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.message.ImageMessage;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.StickerMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
@SpringBootApplication
@LineMessageHandler
public class EchoApplication {
@Autowired
private LineMessagingClient lineMessagingClient;
public static void main(String[] args) throws Exception {
SpringApplication.run(EchoApplication.class, args);
}
@EventMapping
public void handleDefaultMessageEvent(MessageEvent<MessageContent> event) throws Exception {
System.out.println("event: " + event);
List<Message> Messages = new ArrayList<Message>();
CrawlerPack.setLoggerLevel(SimpleLog.LOG_LEVEL_OFF);
MessageContent content = event.getMessage();
if (content instanceof LocationMessageContent) {
LocationMessageContent locationMessage = (LocationMessageContent) event.getMessage();
Messages.add(new TextMessage(locationMessage.getAddress()));
} else if (content instanceof TextMessageContent) {
String message = ((TextMessageContent) event.getMessage()).getText();
if (message.startsWith("%")) {
Messages.add(new TextMessage(getPPT(message)));
} else if (message.startsWith("#")) {
Messages.add(new TextMessage(getHoroscope(message)));
} else if (message.startsWith("&")) {
Messages.addAll(getYoutube(message));
} else if (message.equals("LeaveGroup")) {
Source source = event.getSource();
if (source instanceof GroupSource) {
Messages.add(new TextMessage("大家再見~家再見~再見~見"));
Messages.add(new StickerMessage("2", "524"));
reply(event.getReplyToken(),Messages);
lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get();
} else if (source instanceof RoomSource) {
Messages.add(new TextMessage("你就不要想起我"));
reply(event.getReplyToken(),Messages);
lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get();
}
return;
}
}
if (Messages.size() == 0){
return;
}
reply(event.getReplyToken(),Messages);
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
lineMessagingClient.replyMessage(new ReplyMessage(replyToken, messages)).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
public static Integer countReply(Elements reply) {
return reply.text().split(" ").length;
}
public static String getPPT(String message) {
String board = "Gossiping";
String[] sign = message.split("%");
board = sign[1];
String gossipMainPage = "https://www.ptt.cc/bbs/" + board + "/index.html";
String gossipIndexPage = "https://www.ptt.cc/bbs/" + board + "/index%s.html";
String prevPage = CrawlerPack.start().addCookie("over18", "1").getFromHtml(gossipMainPage)
.select(".action-bar a:matchesOwn(上頁)").get(0).attr("href");
System.out.println("event: " + prevPage);
prevPage = prevPage.replaceAll("/bbs/" + board + "/index([0-9]+).html", "$1");
Integer lastPage = Integer.valueOf(prevPage);
Integer loadLastPosts = 2;
List<String> lastPostsLink = new ArrayList<String>();
while (loadLastPosts > lastPostsLink.size()) {
String currPage = String.format(gossipIndexPage, lastPage--);
Elements links = CrawlerPack.start().addCookie("over18", "1").getFromHtml(currPage).select(".r-ent");
for (Element link : links) {
boolean MoreThen50 = false;
Elements pushs = link.select(".nrec span");
for (Element push : pushs) {
String a = push.ownText();
if (StringUtils.isNumeric(a) && Integer.parseInt(a) > 50) {
MoreThen50 = true;
break;
} else if ("爆".equals(a)) {
MoreThen50 = true;
break;
}
}
if (!MoreThen50) {
continue;
}
if (lastPostsLink.size() > loadLastPosts) {
break;
}
Elements titles = link.select(".title > a");
for (Element title : titles) {
lastPostsLink.add( title.ownText() + "\r\n" + "https://www.ptt.cc" + title.attr("href"));
}
}
}
return String.join("\r\n", lastPostsLink);
}
public static String getHoroscopeEn(String message) {
String[] result = message.split("&");
String sign = result[1];
sign = sign.toLowerCase();
String url = "http://theastrologer-api.herokuapp.com/api/horoscope/" + sign + "/today";
String charset = "UTF-8";
try {
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
String jsonBody = "";
try (Scanner scanner = new Scanner(response)) {
jsonBody += scanner.useDelimiter("\\A").next();
}
JSONObject obj = new JSONObject(jsonBody);
String horoscope = obj.getString("horoscope");
return horoscope;
} catch (MalformedURLException e) {
return "Problem retrieving horoscope";
} catch (IOException e) {
return "Problem retrieving horoscope";
}
}
public static String getHoroscope(String message) {
String[] result = message.split("#");
String sign = result[1];
HashMap<String, String> map = new HashMap<String, String>();
map.put("牡羊", "Aries");
map.put("金牛", "Taurus");
map.put("雙子", "Gemini");
map.put("巨蟹", "Cancer");
map.put("獅子", "Leo");
map.put("處女", "Virgo");
map.put("天秤", "Libra");
map.put("天蠍", "Scorpio");
map.put("射手", "Sagittarius");
map.put("魔羯", "Capricorn");
map.put("水瓶", "Aquarius");
map.put("雙魚", "Pisces");
String uri = "http://www.daily-zodiac.com/zodiac/" + map.get(sign);
String day = CrawlerPack.start().getFromHtml(uri).select(".user-zodiac > h3").text();
String article = CrawlerPack.start().getFromHtml(uri).select(".user-zodiac .article").text();
return day + "\r\n" + article;
}
public static List<Message> getYoutube(String message) throws Exception {
String[] result = message.split("&");
String queryTerm = result[1];
YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
YouTube.Search.List search = youtube.search().list("id,snippet");
String apiKey = "AIzaSyDrWDpehcmxXo4gaqSL2AttQ3UZudOtgyk";
search.setKey(apiKey);
search.setQ(queryTerm);
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(1L);
search.setRegionCode("TW");
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
if (searchResultList != null) {
return prettyPrint(searchResultList);
}
return null;
}
private static List<Message> prettyPrint(List<SearchResult> listSearchResults) {
List<Message> messages = new ArrayList<Message>();
for(SearchResult singleVideo : listSearchResults){
ResourceId rId = singleVideo.getId();
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
if (rId.getKind().equals("youtube#video")) {
messages.add(new ImageMessage(thumbnail.getUrl(), thumbnail.getUrl()));
messages.add(new TextMessage("https://www.youtube.com/watch?v="+rId.getVideoId()));
}
}
return messages;
}
}
|
sample-spring-boot-echo/src/main/java/com/example/bot/spring/echo/EchoApplication.java
|
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation 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.example.bot.spring.echo;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.impl.SimpleLog;
import org.json.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.github.abola.crawler.CrawlerPack;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.LocationMessageContent;
import com.linecorp.bot.model.event.message.MessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.message.ImagemapMessage;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.StickerMessage;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.imagemap.ImagemapArea;
import com.linecorp.bot.model.message.imagemap.ImagemapBaseSize;
import com.linecorp.bot.model.message.imagemap.MessageImagemapAction;
import com.linecorp.bot.model.message.imagemap.URIImagemapAction;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
@SpringBootApplication
@LineMessageHandler
public class EchoApplication {
@Autowired
private LineMessagingClient lineMessagingClient;
public static void main(String[] args) throws Exception {
SpringApplication.run(EchoApplication.class, args);
}
@EventMapping
public void handleDefaultMessageEvent(MessageEvent<MessageContent> event) throws Exception {
System.out.println("event: " + event);
List<Message> Messages = new ArrayList<Message>();
CrawlerPack.setLoggerLevel(SimpleLog.LOG_LEVEL_OFF);
MessageContent content = event.getMessage();
if (content instanceof LocationMessageContent) {
LocationMessageContent locationMessage = (LocationMessageContent) event.getMessage();
Messages.add(new TextMessage(locationMessage.getAddress()));
} else if (content instanceof TextMessageContent) {
String message = ((TextMessageContent) event.getMessage()).getText();
if (message.startsWith("%")) {
Messages.add(new TextMessage(getPPT(message)));
} else if (message.startsWith("#")) {
Messages.add(new TextMessage(getHoroscope(message)));
} else if (message.startsWith("&")) {
Messages.add(new TextMessage(getYoutube(message)));
} else if (message.equals("LeaveGroup")) {
Source source = event.getSource();
if (source instanceof GroupSource) {
Messages.add(new TextMessage("大家再見~家再見~再見~見"));
Messages.add(new StickerMessage("2", "524"));
reply(event.getReplyToken(),Messages);
lineMessagingClient.leaveGroup(((GroupSource) source).getGroupId()).get();
} else if (source instanceof RoomSource) {
Messages.add(new TextMessage("你就不要想起我"));
reply(event.getReplyToken(),Messages);
lineMessagingClient.leaveRoom(((RoomSource) source).getRoomId()).get();
}
return;
} else if (message.startsWith("t1")) {
Messages.add(test());
}
}
if (Messages.size() == 0){
return;
}
reply(event.getReplyToken(),Messages);
}
public ImagemapMessage test() {
return new ImagemapMessage(
"https://scdn.line-apps.com/n/_5/partner-center/img/og-msgapi.png",
"This is alt text",
new ImagemapBaseSize(1040, 1040),
Arrays.asList(
new URIImagemapAction(
"https://store.line.me/family/manga/en",
new ImagemapArea(
0, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/music/en",
new ImagemapArea(
520, 0, 520, 520
)
),
new URIImagemapAction(
"https://store.line.me/family/play/en",
new ImagemapArea(
0, 520, 520, 520
)
),
new MessageImagemapAction(
"URANAI!",
new ImagemapArea(
520, 520, 520, 520
)
)
)
);
}
private static String createUri(String path) {
return ServletUriComponentsBuilder.fromCurrentContextPath()
.path(path).build()
.toUriString();
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
lineMessagingClient.replyMessage(new ReplyMessage(replyToken, messages)).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
public static Integer countReply(Elements reply) {
return reply.text().split(" ").length;
}
public static String getPPT(String message) {
String board = "Gossiping";
String[] sign = message.split("%");
board = sign[1];
String gossipMainPage = "https://www.ptt.cc/bbs/" + board + "/index.html";
String gossipIndexPage = "https://www.ptt.cc/bbs/" + board + "/index%s.html";
String prevPage = CrawlerPack.start().addCookie("over18", "1").getFromHtml(gossipMainPage)
.select(".action-bar a:matchesOwn(上頁)").get(0).attr("href");
System.out.println("event: " + prevPage);
prevPage = prevPage.replaceAll("/bbs/" + board + "/index([0-9]+).html", "$1");
Integer lastPage = Integer.valueOf(prevPage);
Integer loadLastPosts = 2;
List<String> lastPostsLink = new ArrayList<String>();
while (loadLastPosts > lastPostsLink.size()) {
String currPage = String.format(gossipIndexPage, lastPage--);
Elements links = CrawlerPack.start().addCookie("over18", "1").getFromHtml(currPage).select(".r-ent");
for (Element link : links) {
boolean MoreThen50 = false;
Elements pushs = link.select(".nrec span");
for (Element push : pushs) {
String a = push.ownText();
if (StringUtils.isNumeric(a) && Integer.parseInt(a) > 50) {
MoreThen50 = true;
break;
} else if ("爆".equals(a)) {
MoreThen50 = true;
break;
}
}
if (!MoreThen50) {
continue;
}
if (lastPostsLink.size() > loadLastPosts) {
break;
}
Elements titles = link.select(".title > a");
for (Element title : titles) {
lastPostsLink.add( title.ownText() + "\r\n" + "https://www.ptt.cc" + title.attr("href"));
}
}
}
return String.join("\r\n", lastPostsLink);
}
public static String getHoroscopeEn(String message) {
String[] result = message.split("&");
String sign = result[1];
sign = sign.toLowerCase();
String url = "http://theastrologer-api.herokuapp.com/api/horoscope/" + sign + "/today";
String charset = "UTF-8";
try {
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
String jsonBody = "";
try (Scanner scanner = new Scanner(response)) {
jsonBody += scanner.useDelimiter("\\A").next();
}
JSONObject obj = new JSONObject(jsonBody);
String horoscope = obj.getString("horoscope");
return horoscope;
} catch (MalformedURLException e) {
return "Problem retrieving horoscope";
} catch (IOException e) {
return "Problem retrieving horoscope";
}
}
public static String getHoroscope(String message) {
String[] result = message.split("#");
String sign = result[1];
HashMap<String, String> map = new HashMap<String, String>();
map.put("牡羊", "Aries");
map.put("金牛", "Taurus");
map.put("雙子", "Gemini");
map.put("巨蟹", "Cancer");
map.put("獅子", "Leo");
map.put("處女", "Virgo");
map.put("天秤", "Libra");
map.put("天蠍", "Scorpio");
map.put("射手", "Sagittarius");
map.put("魔羯", "Capricorn");
map.put("水瓶", "Aquarius");
map.put("雙魚", "Pisces");
String uri = "http://www.daily-zodiac.com/zodiac/" + map.get(sign);
String day = CrawlerPack.start().getFromHtml(uri).select(".user-zodiac > h3").text();
String article = CrawlerPack.start().getFromHtml(uri).select(".user-zodiac .article").text();
return day + "\r\n" + article;
}
public static String getYoutube(String message) throws Exception {
String[] result = message.split("&");
String queryTerm = result[1];
YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
YouTube.Search.List search = youtube.search().list("id,snippet");
String apiKey = "AIzaSyDrWDpehcmxXo4gaqSL2AttQ3UZudOtgyk";
search.setKey(apiKey);
search.setQ(queryTerm);
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(1L);
search.setRegionCode("TW");
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
if (searchResultList != null) {
return "https://www.youtube.com/watch?v="+prettyPrint(searchResultList);
}
return null;
}
private static String prettyPrint(List<SearchResult> listSearchResults) {
for(SearchResult singleVideo : listSearchResults){
ResourceId rId = singleVideo.getId();
if (rId.getKind().equals("youtube#video")) {
return rId.getVideoId();
}
}
return "";
}
// private static ImagemapMessage prettyPrint1(List<SearchResult> listSearchResults) {
// for(SearchResult singleVideo : listSearchResults){
// ResourceId rId = singleVideo.getId();
// if (rId.getKind().equals("youtube#video")) {
// Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
// return (new ImagemapMessage(thumbnail.getUrl(),
// singleVideo.getSnippet().getTitle(),
// new ImagemapBaseSize(1024, 1024),
// Arrays.asList(
// new URIImagemapAction(
// "https://www.youtube.com/watch?v="+rId.getVideoId(),
// new ImagemapArea(
// 0, 0, 50, 50
// )
// ),
// new MessageImagemapAction(
// "URANAI!",
// new ImagemapArea(
// 100, 0, 50, 50
// )
// )
// )
// ));
// }
// }
// return null;
// }
}
|
testtttt
|
sample-spring-boot-echo/src/main/java/com/example/bot/spring/echo/EchoApplication.java
|
testtttt
|
|
Java
|
apache-2.0
|
ffe710731140b1671360ee51a13f7da43248c1cc
| 0
|
c0d1ngb4d/vpn-toggle,c0d1ngb4d/vpn-toggle
|
/*
* Copyright (C) 2015 Ayelen Chavez y Joaquín Rinaudo
*
* 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.
*
* Contributors:
*
* Ayelen Chavez ashy.on.line@gmail.com
* Joaquin Rinaudo jmrinaudo@gmail.com
*
*/
package com.codingbad.vpntoggle.fragment;
import android.Manifest;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.codingbad.library.fragment.AbstractFragment;
import com.codingbad.vpntoggle.R;
import com.codingbad.vpntoggle.adapter.ItemsAdapter;
import com.codingbad.vpntoggle.model.ApplicationItem;
import com.codingbad.vpntoggle.model.ApplicationsStatus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import roboguice.inject.InjectView;
/**
* Created by ayi on 6/26/15.
*/
public class ApplicationsListFragment extends AbstractFragment<ApplicationsListFragment.Callbacks> implements View.OnClickListener, SearchView.OnQueryTextListener {
private static final String LIST_STATE = "listState";
private static final String SEARCH_STATE = "searchState";
@InjectView(R.id.fragment_list_recyclerview)
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private ApplicationsStatus applications;
private ItemsAdapter adapter;
private List<ApplicationItem> searchItems;
private SearchView searchView;
public static Fragment newInstance() {
return new ApplicationsListFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_applicationslist, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupRecyclerView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_apply) {
applications.apply();
callbacks.onChangesApplied(applications.getApplicationItems());
Snackbar.make(getActivity().findViewById(android.R.id.content), "Changes has been applied", Snackbar.LENGTH_LONG)
.setAction("Undo", this)
.setActionTextColor(getResources().getColor(R.color.accent))
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
if (applications == null) {
List<ApplicationItem> items = callbacks.getApplicationsSavedStatus();
List<ApplicationItem> allApplications = getDeviceApplications();
for (ApplicationItem applicationItem : allApplications) {
if (! items.contains(applicationItem)) {
items.add(applicationItem);
}
}
applications = new ApplicationsStatus(items);
}
List<ApplicationItem> search = null;
// searchItems stored searched values when device was rotated
if (searchItems != null) {
search = searchItems;
searchItems = null;
} else if (adapter != null) {
// adapter is alive if fragment was not destroyed - app minimized, for example
search = adapter.getSearchApplicationItems();
}
// if still null, show all the applications
if (search == null) {
search = applications.getApplicationItems();
}
adapter = new ItemsAdapter();
adapter.setItems(search);
recyclerView.setAdapter(adapter);
}
private void setupRecyclerView() {
recyclerView.setHasFixedSize(true);
// set layout manager which positions items in the screen
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
ArrayList<ApplicationItem> applications = savedInstanceState.getParcelableArrayList(LIST_STATE);
this.applications = new ApplicationsStatus(applications);
searchItems = savedInstanceState.getParcelableArrayList(SEARCH_STATE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (applications != null) {
outState.putParcelableArrayList(LIST_STATE, (ArrayList<? extends Parcelable>) applications.getApplicationItems());
}
if (adapter != null) {
outState.putParcelableArrayList(SEARCH_STATE, (ArrayList<? extends Parcelable>) adapter.getSearchApplicationItems());
}
}
private ArrayList<ApplicationItem> getDeviceApplications() {
final PackageManager packageManager = getActivity().getPackageManager();
List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Map<Integer, ApplicationItem> applicationItemMap = new HashMap<Integer, ApplicationItem>();
for (ApplicationInfo applicationInfo : installedApplications) {
if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(Manifest.permission.INTERNET, applicationInfo.packageName)) {
String appName = (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "(unknown)");
Uri appIconUri = null;
if (applicationInfo.icon != 0) {
appIconUri = Uri.parse("android.resource://" + applicationInfo.packageName + "/" + applicationInfo.icon);
}
int appUid = applicationInfo.uid;
if (applicationItemMap.containsKey(appUid)) {
ApplicationItem applicationItem = applicationItemMap.get(appUid);
applicationItem.addApplication(appName);
applicationItemMap.put(appUid, applicationItem);
} else {
applicationItemMap.put(appUid, new ApplicationItem(appIconUri, appName, appUid));
}
}
}
return new ArrayList<ApplicationItem>(applicationItemMap.values());
}
@Override
public void onClick(View v) {
// UNDO apply
searchView.setQuery("", false);
searchView.clearFocus();
callbacks.onChangesApplied(applications.undo());
adapter = new ItemsAdapter();
adapter.addItemList(applications.getApplicationItems());
recyclerView.setAdapter(adapter);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String query) {
final List<ApplicationItem> filteredModelList = filter(applications.getApplicationItems(), query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<ApplicationItem> filter(List<ApplicationItem> items, String query) {
query = query.toLowerCase();
final List<ApplicationItem> filteredApplicationItems = new ArrayList<>();
for (ApplicationItem applicationItem : items) {
if (applicationItem.getApplicationName().toLowerCase().contains(query)) {
filteredApplicationItems.add(applicationItem);
}
}
return filteredApplicationItems;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Retrieve the SearchView and plug it into SearchManager
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(this);
}
public interface Callbacks {
void onChangesApplied(List<ApplicationItem> applications);
List<ApplicationItem> getApplicationsSavedStatus();
}
}
|
app/src/main/java/com/codingbad/vpntoggle/fragment/ApplicationsListFragment.java
|
/*
* Copyright (C) 2015 Ayelen Chavez y Joaquín Rinaudo
*
* 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.
*
* Contributors:
*
* Ayelen Chavez ashy.on.line@gmail.com
* Joaquin Rinaudo jmrinaudo@gmail.com
*
*/
package com.codingbad.vpntoggle.fragment;
import android.Manifest;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.codingbad.library.fragment.AbstractFragment;
import com.codingbad.vpntoggle.R;
import com.codingbad.vpntoggle.adapter.ItemsAdapter;
import com.codingbad.vpntoggle.model.ApplicationItem;
import com.codingbad.vpntoggle.model.ApplicationsStatus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import roboguice.inject.InjectView;
/**
* Created by ayi on 6/26/15.
*/
public class ApplicationsListFragment extends AbstractFragment<ApplicationsListFragment.Callbacks> implements View.OnClickListener, SearchView.OnQueryTextListener {
private static final String LIST_STATE = "listState";
private static final String SEARCH_STATE = "searchState";
@InjectView(R.id.fragment_list_recyclerview)
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private ApplicationsStatus applications;
private ItemsAdapter adapter;
private List<ApplicationItem> searchItems;
private SearchView searchView;
public static Fragment newInstance() {
return new ApplicationsListFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_applicationslist, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupRecyclerView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_apply) {
applications.apply();
callbacks.onChangesApplied(applications.getApplicationItems());
Snackbar.make(getActivity().findViewById(android.R.id.content), "Changes has been applied", Snackbar.LENGTH_LONG)
.setAction("Undo", this)
.setActionTextColor(getResources().getColor(R.color.accent))
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
if (applications == null) {
List<ApplicationItem> items = callbacks.getApplicationsSavedStatus();
if (items == null) {
items = getDeviceApplications();
}
applications = new ApplicationsStatus(items);
}
List<ApplicationItem> search = null;
// searchItems stored searched values when device was rotated
if (searchItems != null) {
search = searchItems;
searchItems = null;
} else if (adapter != null) {
// adapter is alive if fragment was not destroyed - app minimized, for example
search = adapter.getSearchApplicationItems();
}
// if still null, show all the applications
if (search == null) {
search = applications.getApplicationItems();
}
adapter = new ItemsAdapter();
adapter.setItems(search);
recyclerView.setAdapter(adapter);
}
private void setupRecyclerView() {
recyclerView.setHasFixedSize(true);
// set layout manager which positions items in the screen
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
ArrayList<ApplicationItem> applications = savedInstanceState.getParcelableArrayList(LIST_STATE);
this.applications = new ApplicationsStatus(applications);
searchItems = savedInstanceState.getParcelableArrayList(SEARCH_STATE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (applications != null) {
outState.putParcelableArrayList(LIST_STATE, (ArrayList<? extends Parcelable>) applications.getApplicationItems());
}
if (adapter != null) {
outState.putParcelableArrayList(SEARCH_STATE, (ArrayList<? extends Parcelable>) adapter.getSearchApplicationItems());
}
}
private ArrayList<ApplicationItem> getDeviceApplications() {
final PackageManager packageManager = getActivity().getPackageManager();
List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Map<Integer, ApplicationItem> applicationItemMap = new HashMap<Integer, ApplicationItem>();
for (ApplicationInfo applicationInfo : installedApplications) {
if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(Manifest.permission.INTERNET, applicationInfo.packageName)) {
String appName = (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "(unknown)");
Uri appIconUri = null;
if (applicationInfo.icon != 0) {
appIconUri = Uri.parse("android.resource://" + applicationInfo.packageName + "/" + applicationInfo.icon);
}
int appUid = applicationInfo.uid;
if (applicationItemMap.containsKey(appUid)) {
ApplicationItem applicationItem = applicationItemMap.get(appUid);
applicationItem.addApplication(appName);
applicationItemMap.put(appUid, applicationItem);
} else {
applicationItemMap.put(appUid, new ApplicationItem(appIconUri, appName, appUid));
}
}
}
return new ArrayList<ApplicationItem>(applicationItemMap.values());
}
@Override
public void onClick(View v) {
// UNDO apply
searchView.setQuery("", false);
searchView.clearFocus();
callbacks.onChangesApplied(applications.undo());
adapter = new ItemsAdapter();
adapter.addItemList(applications.getApplicationItems());
recyclerView.setAdapter(adapter);
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String query) {
final List<ApplicationItem> filteredModelList = filter(applications.getApplicationItems(), query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<ApplicationItem> filter(List<ApplicationItem> items, String query) {
query = query.toLowerCase();
final List<ApplicationItem> filteredApplicationItems = new ArrayList<>();
for (ApplicationItem applicationItem : items) {
if (applicationItem.getApplicationName().toLowerCase().contains(query)) {
filteredApplicationItems.add(applicationItem);
}
}
return filteredApplicationItems;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Retrieve the SearchView and plug it into SearchManager
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(this);
}
public interface Callbacks {
void onChangesApplied(List<ApplicationItem> applications);
List<ApplicationItem> getApplicationsSavedStatus();
}
}
|
adding apps that might not be saved before
|
app/src/main/java/com/codingbad/vpntoggle/fragment/ApplicationsListFragment.java
|
adding apps that might not be saved before
|
|
Java
|
apache-2.0
|
e92c4843208f43ed3e4436cf086e67dcff5a634e
| 0
|
diydyq/velocity-engine,pcollaog/velocity-engine,diydyq/velocity-engine,pcollaog/velocity-engine
|
package org.apache.velocity.exception;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Base class for Velocity exceptions thrown to the
* application layer.
*
* @author <a href="mailto:kdowney@amberarcher.com">Kyle F. Downey</a>
* @version $Id: VelocityException.java,v 1.2 2001/03/27 02:25:08 geirm Exp $
*/
public class VelocityException extends Exception
{
public VelocityException(String exceptionMessage )
{
super(exceptionMessage);
}
}
|
src/java/org/apache/velocity/exception/VelocityException.java
|
package org.apache.velocity.exception;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Base class for Velocity exceptions thrown to the
* application layer.
*
* @author <a href="kdowney@amberarcher.com">Kyle F. Downey</a>
* @version $Id: VelocityException.java,v 1.1 2001/03/27 02:06:40 geirm Exp $
*/
public class VelocityException extends Exception
{
public VelocityException(String exceptionMessage )
{
super(exceptionMessage);
}
}
|
Can't imagine how he finds these... :)
PR:
Obtained from:
Submitted by:
Reviewed by:
git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@74735 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/velocity/exception/VelocityException.java
|
Can't imagine how he finds these... :) PR: Obtained from: Submitted by: Reviewed by:
|
|
Java
|
apache-2.0
|
f2beb02d8ed5c4655079356045751a9ea6bc2ecd
| 0
|
RenzoH89/hsac-fitnesse-fixtures,teunisnl/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures,brezelordina/hsac-fitnesse-fixtures-1,brezelordina/hsac-fitnesse-fixtures-1,brezelordina/hsac-fitnesse-fixtures-1,ilseh/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,ilseh/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,alexkogon/hsac-fitnesse-fixtures,brezelordina/hsac-fitnesse-fixtures-1,kk9599/hsac-fitnesse-fixtures,ilseh/hsac-fitnesse-fixtures,ilseh/hsac-fitnesse-fixtures,fhoeben/hsac-fitnesse-fixtures,teunisnl/hsac-fitnesse-fixtures,GDasai/hsac-fitnesse-fixtures,kk9599/hsac-fitnesse-fixtures,teunisnl/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures,alexkogon/hsac-fitnesse-fixtures,teunisnl/hsac-fitnesse-fixtures
|
package nl.hsac.fitnesse.fixture.util;
import org.apache.http.HttpStatus;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Wrapper around HTTP response (and request).
*/
public class HttpResponse {
private final static Map<String, HttpResponse> INSTANCES = new ConcurrentHashMap<String, HttpResponse>();
private String request;
protected String response;
private int statusCode;
/**
* @throws RuntimeException if no valid response is available
*/
public void validResponse() {
if (statusCode == HttpStatus.SC_NOT_IMPLEMENTED) {
throw new RuntimeException("The method is not implemented by this URI");
}
if (statusCode == HttpStatus.SC_NOT_FOUND) {
throw new RuntimeException("No content available for this URI");
}
}
/**
* @return the request
*/
public String getRequest() {
return request;
}
/**
* @param aRequest the request to set
*/
public void setRequest(String aRequest) {
request = aRequest;
}
/**
* @return the response
*/
public String getResponse() {
return response;
}
/**
* @param aResponse the response to set
*/
public void setResponse(String aResponse) {
response = aResponse;
}
/**
* @return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* @param aStatusCode the statusCode to set
*/
public void setStatusCode(int aStatusCode) {
statusCode = aStatusCode;
}
@Override
public String toString() {
// toString() is not normally called on responses,
// but Fitnesse will if it is to be stored in a parameter
// we make sure these could later be retrieved
// see also: parse()
String result = super.toString();
INSTANCES.put(result, this);
return result;
}
/**
* Returns response toString() was called on previously.
* @param value toString() of response being searched.
* @return response if one is known, null otherwise.
*/
public static HttpResponse parse(String value) {
return INSTANCES.get(value);
}
/**
* Clears set of known responses (that can be returned by parse()).
*/
public static void clearInstances() {
INSTANCES.clear();
}
}
|
src/main/java/nl/hsac/fitnesse/fixture/util/HttpResponse.java
|
package nl.hsac.fitnesse.fixture.util;
import org.apache.http.HttpStatus;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Wrapper around HTTP response (and request).
*/
public class HttpResponse {
private final static Map<String, HttpResponse> INSTANCES = new ConcurrentHashMap<String, HttpResponse>();
private String request;
protected String response;
private int statusCode;
/**
* @throws RuntimeException if no valid response is available
*/
public void validResponse() {
if (statusCode == HttpStatus.SC_NOT_IMPLEMENTED) {
throw new RuntimeException("The Post method is not implemented by this URI");
}
if (statusCode == HttpStatus.SC_NOT_FOUND) {
throw new RuntimeException("No content available for this URI");
}
}
/**
* @return the request
*/
public String getRequest() {
return request;
}
/**
* @param aRequest the request to set
*/
public void setRequest(String aRequest) {
request = aRequest;
}
/**
* @return the response
*/
public String getResponse() {
return response;
}
/**
* @param aResponse the response to set
*/
public void setResponse(String aResponse) {
response = aResponse;
}
/**
* @return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* @param aStatusCode the statusCode to set
*/
public void setStatusCode(int aStatusCode) {
statusCode = aStatusCode;
}
@Override
public String toString() {
// toString() is not normally called on responses,
// but Fitnesse will if it is to be stored in a parameter
// we make sure these could later be retrieved
// see also: parse()
String result = super.toString();
INSTANCES.put(result, this);
return result;
}
/**
* Returns response toString() was called on previously.
* @param value toString() of response being searched.
* @return response if one is known, null otherwise.
*/
public static HttpResponse parse(String value) {
return INSTANCES.get(value);
}
/**
* Clears set of known responses (that can be returned by parse()).
*/
public static void clearInstances() {
INSTANCES.clear();
}
}
|
Update message since we can't be sure what the method used was at this point
|
src/main/java/nl/hsac/fitnesse/fixture/util/HttpResponse.java
|
Update message since we can't be sure what the method used was at this point
|
|
Java
|
apache-2.0
|
a2b7b8a3158aad2c3b11ac2be55d2453088bb5fb
| 0
|
lunisolar/magma
|
/*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.lunisolar.magma.func.supp.check;
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import javax.annotation.concurrent.ThreadSafe; // NOSONAR
import java.util.Objects; // NOSONAR
import eu.lunisolar.magma.basics.*; // NOSONAR
import eu.lunisolar.magma.basics.builder.*; // NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR
import eu.lunisolar.magma.basics.fluent.Fluent; // NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.*; // NOSONAR
import eu.lunisolar.magma.func.supp.Be; // NOSONAR
import eu.lunisolar.magma.func.supp.memento.*; // NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import eu.lunisolar.magma.basics.fluent.FluentSyntax;
import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR
import eu.lunisolar.magma.func.supp.value.*;
public interface CheckTrait<T, SELF extends CheckTrait<T, SELF>> extends Fluent<SELF>, aValue<a<T>>, LSingle<T>, ValueTrait<T, SELF> {
public static final String MESSAGE_S_S_S = "%s [%s]: %s.";
public static final String MESSAGE_S_S_S_S = "%s [%s]: %s. Value: %s";
@Nullable
T get();
default @Nullable T value() {
return get();
}
@Nonnull
default String checkTraitType() {
return "Value";
}
@Nonnull
default String checkTraitName() {
return "?";
}
@Nonnull
default ExMF<RuntimeException> checkTraitFactory() {
return X::value;
}
default SELF mustNot(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default SELF mustNot$(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default SELF mustNot(@Nonnull LPredicate<T> pred, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default SELF must(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default SELF must$(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default SELF must(@Nonnull LPredicate<T> pred, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2> SELF mustNot(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2> SELF mustNot$(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2> SELF mustNot(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2> SELF must(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2> SELF must$(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2> SELF must(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2, T3> SELF mustNot(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2, T3> SELF mustNot$(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2, T3> SELF mustNot(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2, T3> SELF must(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2, T3> SELF must$(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2, T3> SELF must(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <R> Checks.Check<R> mustBeInstanceOf(@Nonnull Class<R> clazz, @Nonnull String message) {
Null.nonNullArg(clazz, "clazz");
return (Checks.Check) must(Be::instanceOf, clazz, message);
}
default @Nonnull T nonnull() {
must(Be::notNull, "Value cannot be null!");
return value();
}
default SELF fails(@Nonnull String newMessage) {
must(LPredicate::alwaysFalse, newMessage);
return self();
}
default SELF fails$(@Nonnull String newMessage) {
must$(LPredicate::alwaysFalse, newMessage);
return self();
}
default SELF fails(@Nonnull String newMessage, @Nullable Object... messageParams) {
must(LPredicate::alwaysFalse, newMessage, messageParams);
return self();
}
}
|
magma-func-supp/src/main/java/eu/lunisolar/magma/func/supp/check/CheckTrait.java
|
/*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.lunisolar.magma.func.supp.check;
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import javax.annotation.concurrent.ThreadSafe; // NOSONAR
import java.util.Objects; // NOSONAR
import eu.lunisolar.magma.basics.*; // NOSONAR
import eu.lunisolar.magma.basics.builder.*; // NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR
import eu.lunisolar.magma.basics.fluent.Fluent; // NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.*; // NOSONAR
import eu.lunisolar.magma.func.supp.Be; // NOSONAR
import eu.lunisolar.magma.func.supp.memento.*; // NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import eu.lunisolar.magma.basics.fluent.FluentSyntax;
import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR
import eu.lunisolar.magma.func.supp.value.*;
public interface CheckTrait<T, SELF extends CheckTrait<T, SELF>> extends Fluent<SELF>, aValue<a<T>>, LSingle<T>, ValueTrait<T, SELF> {
public static final String MESSAGE_S_S_S = "%s [%s]: %s.";
public static final String MESSAGE_S_S_S_S = "%s [%s]: %s. Value: %s";
@Nullable
T get();
default @Nullable T value() {
return get();
}
@Nonnull
default String checkTraitType() {
return "Value";
}
@Nonnull
default String checkTraitName() {
return "?";
}
@Nonnull
default ExMF<RuntimeException> checkTraitFactory() {
return X::value;
}
default SELF mustNot(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default SELF mustNot$(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default SELF mustNot(@Nonnull LPredicate<T> pred, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIf(get(), pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default SELF must(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default SELF must$(@Nonnull LPredicate<T> pred, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default SELF must(@Nonnull LPredicate<T> pred, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LPredicate.throwIfNot(get(), pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2> SELF mustNot(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2> SELF mustNot$(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2> SELF mustNot(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIf(get(), a2, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2> SELF must(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2> SELF must$(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2> SELF must(@Nonnull LBiPredicate<T, T2> pred, T2 a2, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LBiPredicate.throwIfNot(get(), a2, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2, T3> SELF mustNot(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2, T3> SELF mustNot$(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2, T3> SELF mustNot(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIf(get(), a2, a3, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <T2, T3> SELF must(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S, checkTraitType(), checkTraitName(), newMessage);
return self();
}
default <T2, T3> SELF must$(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), MESSAGE_S_S_S_S, checkTraitType(), checkTraitName(), newMessage, get());
return self();
}
default <T2, T3> SELF must(@Nonnull LTriPredicate<T, T2, T3> pred, T2 a2, T3 a3, @Nonnull String newMessage, @Nullable Object... messageParams) {
Null.nonNullArg(pred, "pred");
LTriPredicate.throwIfNot(get(), a2, a3, pred, checkTraitFactory(), newMessage, messageParams);
return self();
}
default <R> Checks.Check<R> mustBeInstanceOf(@Nonnull Class<R> clazz, @Nonnull String message) {
Null.nonNullArg(clazz, "clazz");
return (Checks.Check) must(Be::instanceOf, clazz, message);
}
default SELF fails(@Nonnull String newMessage) {
must(LPredicate::alwaysFalse, newMessage);
return self();
}
default SELF fails$(@Nonnull String newMessage) {
must$(LPredicate::alwaysFalse, newMessage);
return self();
}
default SELF fails(@Nonnull String newMessage, @Nullable Object... messageParams) {
must(LPredicate::alwaysFalse, newMessage, messageParams);
return self();
}
}
|
LM-3003 Check<T> should have nonnull() method.
|
magma-func-supp/src/main/java/eu/lunisolar/magma/func/supp/check/CheckTrait.java
|
LM-3003 Check<T> should have nonnull() method.
|
|
Java
|
apache-2.0
|
26241691d46c913ffcd043acbcabb984245e97f8
| 0
|
opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open,opennetworkinglab/spring-open
|
package net.onrc.onos.ofcontroller.networkgraph;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import net.onrc.onos.datagrid.IDatagridService;
import net.onrc.onos.datagrid.IEventChannel;
import net.onrc.onos.datagrid.IEventChannelListener;
import net.onrc.onos.datastore.topology.RCLink;
import net.onrc.onos.datastore.topology.RCPort;
import net.onrc.onos.datastore.topology.RCSwitch;
import net.onrc.onos.ofcontroller.networkgraph.PortEvent.SwitchPort;
import net.onrc.onos.ofcontroller.util.EventEntry;
import net.onrc.onos.ofcontroller.util.Dpid;
import net.onrc.onos.registry.controller.IControllerRegistryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The "NB" read-only Network Map.
*
* - Maintain Invariant/Relationships between Topology Objects.
*
* TODO To be synchronized based on TopologyEvent Notification.
*
* TODO TBD: Caller is expected to maintain parent/child calling order. Parent
* Object must exist before adding sub component(Add Switch -> Port).
*
* TODO TBD: This class may delay the requested change to handle event
* re-ordering. e.g.) Link Add came in, but Switch was not there.
*
*/
public class TopologyManager implements NetworkGraphDiscoveryInterface {
private static final Logger log = LoggerFactory
.getLogger(TopologyManager.class);
private IEventChannel<byte[], TopologyEvent> eventChannel;
private static final String EVENT_CHANNEL_NAME = "onos.topology";
private EventHandler eventHandler = new EventHandler();
private final NetworkGraphDatastore datastore;
private final NetworkGraphImpl networkGraph = new NetworkGraphImpl();
private final IControllerRegistryService registryService;
private CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners;
//
// Local state for keeping track of reordered events.
// NOTE: Switch Events are not affected by the event reordering.
//
private Map<ByteBuffer, PortEvent> reorderedAddedPortEvents =
new HashMap<ByteBuffer, PortEvent>();
private Map<ByteBuffer, LinkEvent> reorderedAddedLinkEvents =
new HashMap<ByteBuffer, LinkEvent>();
private Map<ByteBuffer, DeviceEvent> reorderedAddedDeviceEvents =
new HashMap<ByteBuffer, DeviceEvent>();
//
// Local state for keeping track of locally discovered events so we can
// cleanup properly when a Switch or Port is removed.
//
// We keep all Port, Link and Device events per Switch DPID:
// - If a switch goes down, we remove all corresponding Port, Link and
// Device events.
// - If a port on a switch goes down, we remove all corresponding Link
// and Device events.
//
private Map<Long, Map<ByteBuffer, PortEvent>> discoveredAddedPortEvents =
new HashMap<>();
private Map<Long, Map<ByteBuffer, LinkEvent>> discoveredAddedLinkEvents =
new HashMap<>();
private Map<Long, Map<ByteBuffer, DeviceEvent>> discoveredAddedDeviceEvents =
new HashMap<>();
//
// Local state for keeping track of the application event notifications
//
List<SwitchEvent> apiAddedSwitchEvents = new LinkedList<SwitchEvent>();
List<SwitchEvent> apiRemovedSwitchEvents = new LinkedList<SwitchEvent>();
List<PortEvent> apiAddedPortEvents = new LinkedList<PortEvent>();
List<PortEvent> apiRemovedPortEvents = new LinkedList<PortEvent>();
List<LinkEvent> apiAddedLinkEvents = new LinkedList<LinkEvent>();
List<LinkEvent> apiRemovedLinkEvents = new LinkedList<LinkEvent>();
List<DeviceEvent> apiAddedDeviceEvents = new LinkedList<DeviceEvent>();
List<DeviceEvent> apiRemovedDeviceEvents = new LinkedList<DeviceEvent>();
/**
* Constructor.
*
* @param registryService the Registry Service to use.
* @param networkGraphListeners the collection of Network Graph Listeners
* to use.
*/
public TopologyManager(IControllerRegistryService registryService,
CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners) {
datastore = new NetworkGraphDatastore();
this.registryService = registryService;
this.networkGraphListeners = networkGraphListeners;
}
/**
* Get the Network Graph.
*
* @return the Network Graph.
*/
NetworkGraph getNetworkGraph() {
return networkGraph;
}
/**
* Event handler class.
*/
private class EventHandler extends Thread implements
IEventChannelListener<byte[], TopologyEvent> {
private BlockingQueue<EventEntry<TopologyEvent>> topologyEvents =
new LinkedBlockingQueue<EventEntry<TopologyEvent>>();
/**
* Startup processing.
*/
private void startup() {
//
// TODO: Read all state from the database:
//
// Collection<EventEntry<TopologyEvent>> collection =
// readWholeTopologyFromDB();
//
// For now, as a shortcut we read it from the datagrid
//
Collection<TopologyEvent> topologyEvents =
eventChannel.getAllEntries();
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
for (TopologyEvent topologyEvent : topologyEvents) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
processEvents(collection);
}
/**
* Run the thread.
*/
@Override
public void run() {
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
this.setName("TopologyManager.EventHandler " + this.getId());
startup();
//
// The main loop
//
try {
while (true) {
EventEntry<TopologyEvent> eventEntry = topologyEvents.take();
collection.add(eventEntry);
topologyEvents.drainTo(collection);
processEvents(collection);
collection.clear();
}
} catch (Exception exception) {
log.debug("Exception processing Topology Events: ", exception);
}
}
/**
* Process all topology events.
*
* @param events the events to process.
*/
private void processEvents(Collection<EventEntry<TopologyEvent>> events) {
// Local state for computing the final set of events
Map<ByteBuffer, SwitchEvent> addedSwitchEvents = new HashMap<>();
Map<ByteBuffer, SwitchEvent> removedSwitchEvents = new HashMap<>();
Map<ByteBuffer, PortEvent> addedPortEvents = new HashMap<>();
Map<ByteBuffer, PortEvent> removedPortEvents = new HashMap<>();
Map<ByteBuffer, LinkEvent> addedLinkEvents = new HashMap<>();
Map<ByteBuffer, LinkEvent> removedLinkEvents = new HashMap<>();
Map<ByteBuffer, DeviceEvent> addedDeviceEvents = new HashMap<>();
Map<ByteBuffer, DeviceEvent> removedDeviceEvents = new HashMap<>();
//
// Classify and suppress matching events
//
for (EventEntry<TopologyEvent> event : events) {
TopologyEvent topologyEvent = event.eventData();
SwitchEvent switchEvent = topologyEvent.switchEvent;
PortEvent portEvent = topologyEvent.portEvent;
LinkEvent linkEvent = topologyEvent.linkEvent;
DeviceEvent deviceEvent = topologyEvent.deviceEvent;
//
// Extract the events
//
switch (event.eventType()) {
case ENTRY_ADD:
log.debug("Topology event ENTRY_ADD: {}", topologyEvent);
if (switchEvent != null) {
ByteBuffer id = ByteBuffer.wrap(switchEvent.getID());
addedSwitchEvents.put(id, switchEvent);
removedSwitchEvents.remove(id);
// Switch Events are not affected by event reordering
}
if (portEvent != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
addedPortEvents.put(id, portEvent);
removedPortEvents.remove(id);
reorderedAddedPortEvents.remove(id);
}
if (linkEvent != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
addedLinkEvents.put(id, linkEvent);
removedLinkEvents.remove(id);
reorderedAddedLinkEvents.remove(id);
}
if (deviceEvent != null) {
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
addedDeviceEvents.put(id, deviceEvent);
removedDeviceEvents.remove(id);
reorderedAddedDeviceEvents.remove(id);
}
break;
case ENTRY_REMOVE:
log.debug("Topology event ENTRY_REMOVE: {}", topologyEvent);
if (switchEvent != null) {
ByteBuffer id = ByteBuffer.wrap(switchEvent.getID());
addedSwitchEvents.remove(id);
removedSwitchEvents.put(id, switchEvent);
// Switch Events are not affected by event reordering
}
if (portEvent != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
addedPortEvents.remove(id);
removedPortEvents.put(id, portEvent);
reorderedAddedPortEvents.remove(id);
}
if (linkEvent != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
addedLinkEvents.remove(id);
removedLinkEvents.put(id, linkEvent);
reorderedAddedLinkEvents.remove(id);
}
if (deviceEvent != null) {
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
addedDeviceEvents.remove(id);
removedDeviceEvents.put(id, deviceEvent);
reorderedAddedDeviceEvents.remove(id);
}
break;
}
}
//
// Lock the Network Graph while it is modified
//
networkGraph.acquireWriteLock();
try {
//
// Apply the classified events.
//
// Apply the "add" events in the proper order:
// switch, port, link, device
//
for (SwitchEvent switchEvent : addedSwitchEvents.values())
addSwitch(switchEvent);
for (PortEvent portEvent : addedPortEvents.values())
addPort(portEvent);
for (LinkEvent linkEvent : addedLinkEvents.values())
addLink(linkEvent);
for (DeviceEvent deviceEvent : addedDeviceEvents.values())
addDevice(deviceEvent);
//
// Apply the "remove" events in the reverse order:
// device, link, port, switch
//
for (DeviceEvent deviceEvent : removedDeviceEvents.values())
removeDevice(deviceEvent);
for (LinkEvent linkEvent : removedLinkEvents.values())
removeLink(linkEvent);
for (PortEvent portEvent : removedPortEvents.values())
removePort(portEvent);
for (SwitchEvent switchEvent : removedSwitchEvents.values())
removeSwitch(switchEvent);
//
// Apply reordered events
//
applyReorderedEvents(! addedSwitchEvents.isEmpty(),
! addedPortEvents.isEmpty());
}
finally {
//
// Network Graph modifications completed: Release the lock
//
networkGraph.releaseWriteLock();
}
//
// Dispatch the Topology Notification Events to the applications
//
dispatchNetworkGraphEvents();
}
/**
* Receive a notification that an entry is added.
*
* @param value the value for the entry.
*/
@Override
public void entryAdded(TopologyEvent value) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
value);
topologyEvents.add(eventEntry);
}
/**
* Receive a notification that an entry is removed.
*
* @param value the value for the entry.
*/
@Override
public void entryRemoved(TopologyEvent value) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_REMOVE,
value);
topologyEvents.add(eventEntry);
}
/**
* Receive a notification that an entry is updated.
*
* @param value the value for the entry.
*/
@Override
public void entryUpdated(TopologyEvent value) {
// NOTE: The ADD and UPDATE events are processed in same way
entryAdded(value);
}
}
/**
* Startup processing.
*
* @param datagridService the datagrid service to use.
*/
void startup(IDatagridService datagridService) {
eventChannel = datagridService.addListener(EVENT_CHANNEL_NAME,
eventHandler,
byte[].class,
TopologyEvent.class);
eventHandler.start();
}
/**
* Dispatch Network Graph Events to the listeners.
*/
private void dispatchNetworkGraphEvents() {
if (apiAddedSwitchEvents.isEmpty() &&
apiRemovedSwitchEvents.isEmpty() &&
apiAddedPortEvents.isEmpty() &&
apiRemovedPortEvents.isEmpty() &&
apiAddedLinkEvents.isEmpty() &&
apiRemovedLinkEvents.isEmpty() &&
apiAddedDeviceEvents.isEmpty() &&
apiRemovedDeviceEvents.isEmpty()) {
return; // No events to dispatch
}
// Deliver the events
for (INetworkGraphListener listener : this.networkGraphListeners) {
// TODO: Should copy before handing them over to listener?
listener.networkGraphEvents(apiAddedSwitchEvents,
apiRemovedSwitchEvents,
apiAddedPortEvents,
apiRemovedPortEvents,
apiAddedLinkEvents,
apiRemovedLinkEvents,
apiAddedDeviceEvents,
apiRemovedDeviceEvents);
}
//
// Cleanup
//
apiAddedSwitchEvents.clear();
apiRemovedSwitchEvents.clear();
apiAddedPortEvents.clear();
apiRemovedPortEvents.clear();
apiAddedLinkEvents.clear();
apiRemovedLinkEvents.clear();
apiAddedDeviceEvents.clear();
apiRemovedDeviceEvents.clear();
}
/**
* Apply reordered events.
*
* @param hasAddedSwitchEvents true if there were Added Switch Events.
* @param hasAddedPortEvents true if there were Added Port Events.
*/
private void applyReorderedEvents(boolean hasAddedSwitchEvents,
boolean hasAddedPortEvents) {
if (! (hasAddedSwitchEvents || hasAddedPortEvents))
return; // Nothing to do
//
// Try to apply the reordered events.
//
// NOTE: For simplicity we try to apply all events of a particular
// type if any "parent" type event was processed:
// - Apply reordered Port Events if Switches were added
// - Apply reordered Link and Device Events if Switches or Ports
// were added
//
Map<ByteBuffer, PortEvent> portEvents = reorderedAddedPortEvents;
Map<ByteBuffer, LinkEvent> linkEvents = reorderedAddedLinkEvents;
Map<ByteBuffer, DeviceEvent> deviceEvents = reorderedAddedDeviceEvents;
reorderedAddedPortEvents = new HashMap<>();
reorderedAddedLinkEvents = new HashMap<>();
reorderedAddedDeviceEvents = new HashMap<>();
//
// Apply reordered Port Events if Switches were added
//
if (hasAddedSwitchEvents) {
for (PortEvent portEvent : portEvents.values())
addPort(portEvent);
}
//
// Apply reordered Link and Device Events if Switches or Ports
// were added.
//
for (LinkEvent linkEvent : linkEvents.values())
addLink(linkEvent);
for (DeviceEvent deviceEvent : deviceEvents.values())
addDevice(deviceEvent);
}
/* ******************************
* NetworkGraphDiscoveryInterface methods
* ******************************/
@Override
public void putSwitchDiscoveryEvent(SwitchEvent switchEvent,
Collection<PortEvent> portEvents) {
if (datastore.addSwitch(switchEvent, portEvents)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Send out notification for each port
for (PortEvent portEvent : portEvents) {
topologyEvent = new TopologyEvent(portEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
}
//
// Keep track of the added ports
//
// Get the old Port Events
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(switchEvent.getDpid());
if (oldPortEvents == null)
oldPortEvents = new HashMap<>();
// Store the new Port Events in the local cache
Map<ByteBuffer, PortEvent> newPortEvents = new HashMap<>();
for (PortEvent portEvent : portEvents) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
newPortEvents.put(id, portEvent);
}
discoveredAddedPortEvents.put(switchEvent.getDpid(),
newPortEvents);
//
// Extract the removed ports
//
List<PortEvent> removedPortEvents = new LinkedList<>();
for (Map.Entry<ByteBuffer, PortEvent> entry : oldPortEvents.entrySet()) {
ByteBuffer key = entry.getKey();
PortEvent portEvent = entry.getValue();
if (! newPortEvents.containsKey(key))
removedPortEvents.add(portEvent);
}
// Cleanup old removed ports
for (PortEvent portEvent : removedPortEvents)
removePortDiscoveryEvent(portEvent);
}
}
@Override
public void removeSwitchDiscoveryEvent(SwitchEvent switchEvent) {
// Get the old Port Events
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(switchEvent.getDpid());
if (oldPortEvents == null)
oldPortEvents = new HashMap<>();
if (datastore.deactivateSwitch(switchEvent, oldPortEvents.values())) {
// Send out notification
eventChannel.removeEntry(switchEvent.getID());
// Send out notification for each port
for (PortEvent portEvent : oldPortEvents.values())
eventChannel.removeEntry(portEvent.getID());
discoveredAddedPortEvents.remove(switchEvent.getDpid());
// Cleanup for each link
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(switchEvent.getDpid());
if (oldLinkEvents != null) {
for (LinkEvent linkEvent : oldLinkEvents.values())
removeLinkDiscoveryEvent(linkEvent);
discoveredAddedLinkEvents.remove(switchEvent.getDpid());
}
// Cleanup for each device
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(switchEvent.getDpid());
if (oldDeviceEvents != null) {
for (DeviceEvent deviceEvent : oldDeviceEvents.values())
removeDeviceDiscoveryEvent(deviceEvent);
discoveredAddedDeviceEvents.remove(switchEvent.getDpid());
}
}
}
@Override
public void putPortDiscoveryEvent(PortEvent portEvent) {
if (datastore.addPort(portEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(portEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Port Event in the local cache
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(portEvent.getDpid());
if (oldPortEvents == null) {
oldPortEvents = new HashMap<>();
discoveredAddedPortEvents.put(portEvent.getDpid(),
oldPortEvents);
}
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
oldPortEvents.put(id, portEvent);
}
}
@Override
public void removePortDiscoveryEvent(PortEvent portEvent) {
if (datastore.deactivatePort(portEvent)) {
// Send out notification
eventChannel.removeEntry(portEvent.getID());
// Cleanup the Port Event from the local cache
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(portEvent.getDpid());
if (oldPortEvents != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
oldPortEvents.remove(id);
}
// Cleanup for the incoming link
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(portEvent.getDpid());
if (oldLinkEvents != null) {
for (LinkEvent linkEvent : oldLinkEvents.values()) {
if (linkEvent.getDst().equals(portEvent.id)) {
removeLinkDiscoveryEvent(linkEvent);
//
// NOTE: oldLinkEvents was modified by
// removeLinkDiscoveryEvent() and cannot be iterated
// anymore.
//
break;
}
}
}
// Cleanup for the connected devices
// TODO: The implementation below is probably wrong
List<DeviceEvent> removedDeviceEvents = new LinkedList<>();
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(portEvent.getDpid());
if (oldDeviceEvents != null) {
for (DeviceEvent deviceEvent : oldDeviceEvents.values()) {
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
if (swp.equals(portEvent.id)) {
removedDeviceEvents.add(deviceEvent);
break;
}
}
}
for (DeviceEvent deviceEvent : removedDeviceEvents)
removeDeviceDiscoveryEvent(deviceEvent);
}
}
}
@Override
public void putLinkDiscoveryEvent(LinkEvent linkEvent) {
if (datastore.addLink(linkEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Link Event in the local cache
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
if (oldLinkEvents == null) {
oldLinkEvents = new HashMap<>();
discoveredAddedLinkEvents.put(linkEvent.getDst().getDpid(),
oldLinkEvents);
}
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
oldLinkEvents.put(id, linkEvent);
}
}
@Override
public void removeLinkDiscoveryEvent(LinkEvent linkEvent) {
if (datastore.removeLink(linkEvent)) {
// Send out notification
eventChannel.removeEntry(linkEvent.getID());
// Cleanup the Link Event from the local cache
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
if (oldLinkEvents != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
oldLinkEvents.remove(id);
}
}
}
@Override
public void putDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
if (datastore.addDevice(deviceEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(deviceEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Device Event in the local cache
// TODO: The implementation below is probably wrong
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(swp.getDpid());
if (oldDeviceEvents == null) {
oldDeviceEvents = new HashMap<>();
discoveredAddedDeviceEvents.put(swp.getDpid(),
oldDeviceEvents);
}
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
oldDeviceEvents.put(id, deviceEvent);
}
}
}
@Override
public void removeDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
if (datastore.removeDevice(deviceEvent)) {
// Send out notification
eventChannel.removeEntry(deviceEvent.getID());
// Cleanup the Device Event from the local cache
// TODO: The implementation below is probably wrong
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(swp.getDpid());
if (oldDeviceEvents != null) {
oldDeviceEvents.remove(id);
}
}
}
}
/* ************************************************
* Internal methods to maintain the network graph
* ************************************************/
private void addSwitch(SwitchEvent switchEvent) {
Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
if (sw == null) {
sw = new SwitchImpl(networkGraph, switchEvent.getDpid());
networkGraph.putSwitch(sw);
} else {
// TODO: Update the switch attributes
// TODO: Nothing to do for now
}
apiAddedSwitchEvents.add(switchEvent);
}
private void removeSwitch(SwitchEvent switchEvent) {
Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
if (sw == null) {
log.warn("Switch {} already removed, ignoring", switchEvent);
return;
}
//
// Remove all Ports on the Switch
//
ArrayList<PortEvent> portsToRemove = new ArrayList<>();
for (Port port : sw.getPorts()) {
log.warn("Port {} on Switch {} should be removed prior to removing Switch. Removing Port now.",
port, switchEvent);
PortEvent portEvent = new PortEvent(port.getDpid(),
port.getNumber());
portsToRemove.add(portEvent);
}
for (PortEvent portEvent : portsToRemove)
removePort(portEvent);
networkGraph.removeSwitch(switchEvent.getDpid());
apiRemovedSwitchEvents.add(switchEvent);
}
private void addPort(PortEvent portEvent) {
Switch sw = networkGraph.getSwitch(portEvent.getDpid());
if (sw == null) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
reorderedAddedPortEvents.put(id, portEvent);
return;
}
SwitchImpl switchImpl = getSwitchImpl(sw);
Port port = sw.getPort(portEvent.getNumber());
if (port == null) {
port = new PortImpl(networkGraph, sw, portEvent.getNumber());
switchImpl.addPort(port);
} else {
// TODO: Update the port attributes
}
apiAddedPortEvents.add(portEvent);
}
private void removePort(PortEvent portEvent) {
Switch sw = networkGraph.getSwitch(portEvent.getDpid());
if (sw == null) {
log.warn("Parent Switch for Port {} already removed, ignoring",
portEvent);
return;
}
Port port = sw.getPort(portEvent.getNumber());
if (port == null) {
log.warn("Port {} already removed, ignoring", portEvent);
return;
}
//
// Remove all Devices attached to the Port
//
ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
for (Device device : port.getDevices()) {
log.debug("Removing Device {} on Port {}", device, portEvent);
DeviceEvent deviceEvent = new DeviceEvent(device.getMacAddress());
SwitchPort switchPort = new SwitchPort(port.getSwitch().getDpid(),
port.getNumber());
deviceEvent.addAttachmentPoint(switchPort);
devicesToRemove.add(deviceEvent);
}
for (DeviceEvent deviceEvent : devicesToRemove)
removeDevice(deviceEvent);
//
// Remove all Links connected to the Port
//
Set<Link> links = new HashSet<>();
links.add(port.getOutgoingLink());
links.add(port.getIncomingLink());
ArrayList<LinkEvent> linksToRemove = new ArrayList<>();
for (Link link : links) {
if (link == null)
continue;
log.debug("Removing Link {} on Port {}", link, portEvent);
LinkEvent linkEvent = new LinkEvent(link.getSrcSwitch().getDpid(),
link.getSrcPort().getNumber(),
link.getDstSwitch().getDpid(),
link.getDstPort().getNumber());
linksToRemove.add(linkEvent);
}
for (LinkEvent linkEvent : linksToRemove)
removeLink(linkEvent);
// Remove the Port from the Switch
SwitchImpl switchImpl = getSwitchImpl(sw);
switchImpl.removePort(port);
apiRemovedPortEvents.add(portEvent);
}
private void addLink(LinkEvent linkEvent) {
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if ((srcPort == null) || (dstPort == null)) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
reorderedAddedLinkEvents.put(id, linkEvent);
return;
}
// Get the Link instance from the Destination Port Incoming Link
Link link = dstPort.getIncomingLink();
assert(link == srcPort.getOutgoingLink());
if (link == null) {
link = new LinkImpl(networkGraph, srcPort, dstPort);
PortImpl srcPortImpl = getPortImpl(srcPort);
PortImpl dstPortImpl = getPortImpl(dstPort);
srcPortImpl.setOutgoingLink(link);
dstPortImpl.setIncomingLink(link);
// Remove all Devices attached to the Ports
ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
ArrayList<Port> ports = new ArrayList<>();
ports.add(srcPort);
ports.add(dstPort);
for (Port port : ports) {
for (Device device : port.getDevices()) {
log.error("Device {} on Port {} should have been removed prior to adding Link {}",
device, port, linkEvent);
DeviceEvent deviceEvent =
new DeviceEvent(device.getMacAddress());
SwitchPort switchPort =
new SwitchPort(port.getSwitch().getDpid(),
port.getNumber());
deviceEvent.addAttachmentPoint(switchPort);
devicesToRemove.add(deviceEvent);
}
}
for (DeviceEvent deviceEvent : devicesToRemove)
removeDevice(deviceEvent);
} else {
// TODO: Update the link attributes
}
apiAddedLinkEvents.add(linkEvent);
}
private void removeLink(LinkEvent linkEvent) {
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
if (srcPort == null) {
log.warn("Src Port for Link {} already removed, ignoring",
linkEvent);
return;
}
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (dstPort == null) {
log.warn("Dst Port for Link {} already removed, ignoring",
linkEvent);
return;
}
//
// Remove the Link instance from the Destination Port Incoming Link
// and the Source Port Outgoing Link.
//
Link link = dstPort.getIncomingLink();
if (link == null) {
log.warn("Link {} already removed on destination Port", linkEvent);
}
link = srcPort.getOutgoingLink();
if (link == null) {
log.warn("Link {} already removed on src Port", linkEvent);
}
getPortImpl(dstPort).setIncomingLink(null);
getPortImpl(srcPort).setOutgoingLink(null);
apiRemovedLinkEvents.add(linkEvent);
}
// TODO: Device-related work is incomplete
private void addDevice(DeviceEvent deviceEvent) {
Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
if (device == null) {
device = new DeviceImpl(networkGraph, deviceEvent.getMac());
}
DeviceImpl deviceImpl = getDeviceImpl(device);
// Update the IP addresses
for (InetAddress ipAddr : deviceEvent.getIpAddresses())
deviceImpl.addIpAddress(ipAddr);
// Process each attachment point
boolean attachmentFound = false;
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
reorderedAddedDeviceEvents.put(id, deviceEvent);
continue;
}
// Attached Ports must not have Link
if (port.getOutgoingLink() != null ||
port.getIncomingLink() != null) {
log.warn("Link (Out:{},In:{}) exist on the attachment point, skipping mutation.",
port.getOutgoingLink(),
port.getIncomingLink());
continue;
}
// Add Device <-> Port attachment
PortImpl portImpl = getPortImpl(port);
portImpl.addDevice(device);
deviceImpl.addAttachmentPoint(port);
attachmentFound = true;
}
// Update the device in the Network Graph
if (attachmentFound) {
networkGraph.putDevice(device);
apiAddedDeviceEvents.add(deviceEvent);
}
}
private void removeDevice(DeviceEvent deviceEvent) {
Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
if (device == null) {
log.warn("Device {} already removed, ignoring", deviceEvent);
return;
}
DeviceImpl deviceImpl = getDeviceImpl(device);
// Process each attachment point
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
log.warn("Port for the attachment point {} did not exist. skipping attachment point mutation", swp);
continue;
}
// Remove Device <-> Port attachment
PortImpl portImpl = getPortImpl(port);
portImpl.removeDevice(device);
deviceImpl.removeAttachmentPoint(port);
}
networkGraph.removeDevice(device);
apiRemovedDeviceEvents.add(deviceEvent);
}
/**
*
* @param switchEvent
* @return true if ready to accept event.
*/
private boolean prepareForAddSwitchEvent(SwitchEvent switchEvent) {
// No show stopping precondition
return true;
}
private boolean prepareForRemoveSwitchEvent(SwitchEvent switchEvent) {
// No show stopping precondition
return true;
}
private boolean prepareForAddPortEvent(PortEvent portEvent) {
// Parent Switch must exist
if (networkGraph.getSwitch(portEvent.getDpid()) == null) {
log.warn("Dropping add port event because switch doesn't exist: {}",
portEvent);
return false;
}
// Prep: None
return true;
}
private boolean prepareForRemovePortEvent(PortEvent portEvent) {
Port port = networkGraph.getPort(portEvent.getDpid(),
portEvent.getNumber());
if (port == null) {
log.debug("Port already removed? {}", portEvent);
// let it pass
return true;
}
// Prep: Remove Link and Device Attachment
ArrayList<DeviceEvent> deviceEvents = new ArrayList<>();
for (Device device : port.getDevices()) {
log.debug("Removing Device {} on Port {}", device, portEvent);
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(port.getSwitch().getDpid(),
port.getNumber()));
deviceEvents.add(devEvent);
}
for (DeviceEvent devEvent : deviceEvents) {
// calling Discovery API to wipe from DB, etc.
removeDeviceDiscoveryEvent(devEvent);
}
Set<Link> links = new HashSet<>();
links.add(port.getOutgoingLink());
links.add(port.getIncomingLink());
for (Link link : links) {
if (link == null) {
continue;
}
log.debug("Removing Link {} on Port {}", link, portEvent);
LinkEvent linkEvent =
new LinkEvent(link.getSrcSwitch().getDpid(),
link.getSrcPort().getNumber(),
link.getDstSwitch().getDpid(),
link.getDstPort().getNumber());
// calling Discovery API to wipe from DB, etc.
// Call internal remove Link, which will check
// ownership of DST dpid and modify DB only if it is the owner
removeLinkDiscoveryEvent(linkEvent, true);
}
return true;
}
private boolean prepareForAddLinkEvent(LinkEvent linkEvent) {
// Src/Dst Port must exist
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (srcPort == null || dstPort == null) {
log.warn("Dropping add link event because port doesn't exist: {}",
linkEvent);
return false;
}
// Prep: remove Device attachment on both Ports
ArrayList<DeviceEvent> deviceEvents = new ArrayList<>();
for (Device device : srcPort.getDevices()) {
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(srcPort.getSwitch().getDpid(), srcPort.getNumber()));
deviceEvents.add(devEvent);
}
for (Device device : dstPort.getDevices()) {
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(dstPort.getSwitch().getDpid(),
dstPort.getNumber()));
deviceEvents.add(devEvent);
}
for (DeviceEvent devEvent : deviceEvents) {
// calling Discovery API to wipe from DB, etc.
removeDeviceDiscoveryEvent(devEvent);
}
return true;
}
private boolean prepareForRemoveLinkEvent(LinkEvent linkEvent) {
// Src/Dst Port must exist
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (srcPort == null || dstPort == null) {
log.warn("Dropping remove link event because port doesn't exist {}", linkEvent);
return false;
}
Link link = srcPort.getOutgoingLink();
// Link is already gone, or different Link exist in memory
// XXX Check if we should reject or just accept these cases.
// it should be harmless to remove the Link on event from DB anyways
if (link == null ||
!link.getDstPort().getNumber().equals(linkEvent.getDst().number)
|| !link.getDstSwitch().getDpid().equals(linkEvent.getDst().dpid)) {
log.warn("Dropping remove link event because link doesn't exist: {}", linkEvent);
return false;
}
// Prep: None
return true;
}
/**
*
* @param deviceEvent Event will be modified to remove inapplicable attachemntPoints/ipAddress
* @return false if this event should be dropped.
*/
private boolean prepareForAddDeviceEvent(DeviceEvent deviceEvent) {
boolean preconditionBroken = false;
ArrayList<PortEvent.SwitchPort> failedSwitchPort = new ArrayList<>();
for ( PortEvent.SwitchPort swp : deviceEvent.getAttachmentPoints() ) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
preconditionBroken = true;
failedSwitchPort.add(swp);
continue;
}
// Attached Ports must not have Link
if (port.getOutgoingLink() != null ||
port.getIncomingLink() != null) {
preconditionBroken = true;
failedSwitchPort.add(swp);
continue;
}
}
// Rewriting event to exclude failed attachmentPoint
// XXX Assumption behind this is that inapplicable device event should
// be dropped, not deferred. If we decide to defer Device event,
// rewriting can become a problem
List<SwitchPort> attachmentPoints = deviceEvent.getAttachmentPoints();
attachmentPoints.removeAll(failedSwitchPort);
deviceEvent.setAttachmentPoints(attachmentPoints);
if (deviceEvent.getAttachmentPoints().isEmpty() &&
deviceEvent.getIpAddresses().isEmpty()) {
// return false to represent: Nothing left to do for this event.
// Caller should drop event
return false;
}
// Should we return false to tell caller that the event was trimmed?
// if ( preconditionBroken ) {
// return false;
// }
return true;
}
private boolean prepareForRemoveDeviceEvent(DeviceEvent deviceEvent) {
// No show stopping precondition?
// Prep: none
return true;
}
private SwitchImpl getSwitchImpl(Switch sw) {
if (sw instanceof SwitchImpl) {
return (SwitchImpl) sw;
}
throw new ClassCastException("SwitchImpl expected, but found: " + sw);
}
private PortImpl getPortImpl(Port p) {
if (p instanceof PortImpl) {
return (PortImpl) p;
}
throw new ClassCastException("PortImpl expected, but found: " + p);
}
private LinkImpl getLinkImpl(Link l) {
if (l instanceof LinkImpl) {
return (LinkImpl) l;
}
throw new ClassCastException("LinkImpl expected, but found: " + l);
}
private DeviceImpl getDeviceImpl(Device d) {
if (d instanceof DeviceImpl) {
return (DeviceImpl) d;
}
throw new ClassCastException("DeviceImpl expected, but found: " + d);
}
@Deprecated
private Collection<EventEntry<TopologyEvent>> readWholeTopologyFromDB() {
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
// XXX May need to clear whole topology first, depending on
// how we initially subscribe to replication events
// Add all active switches
for (RCSwitch sw : RCSwitch.getAllSwitches()) {
if (sw.getStatus() != RCSwitch.STATUS.ACTIVE) {
continue;
}
SwitchEvent switchEvent = new SwitchEvent(sw.getDpid());
TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
// Add all active ports
for (RCPort p : RCPort.getAllPorts()) {
if (p.getStatus() != RCPort.STATUS.ACTIVE) {
continue;
}
PortEvent portEvent = new PortEvent(p.getDpid(), p.getNumber());
TopologyEvent topologyEvent = new TopologyEvent(portEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
// TODO Is Device going to be in DB? If so, read from DB.
// for (RCDevice d : RCDevice.getAllDevices()) {
// DeviceEvent devEvent = new DeviceEvent( MACAddress.valueOf(d.getMac()) );
// for (byte[] portId : d.getAllPortIds() ) {
// devEvent.addAttachmentPoint( new SwitchPort( RCPort.getDpidFromKey(portId), RCPort.getNumberFromKey(portId) ));
// }
// }
for (RCLink l : RCLink.getAllLinks()) {
// check if src/dst switch/port exist before triggering event
Port srcPort = networkGraph.getPort(l.getSrc().dpid,
l.getSrc().number);
Port dstPort = networkGraph.getPort(l.getDst().dpid,
l.getDst().number);
if (srcPort == null || dstPort == null) {
continue;
}
LinkEvent linkEvent = new LinkEvent(l.getSrc().dpid,
l.getSrc().number,
l.getDst().dpid,
l.getDst().number);
TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
return collection;
}
@Deprecated
private void removeLinkDiscoveryEvent(LinkEvent linkEvent,
boolean dstCheckBeforeDBmodify) {
if (prepareForRemoveLinkEvent(linkEvent)) {
if (dstCheckBeforeDBmodify) {
// write to DB only if it is owner of the dst dpid
// XXX this will cause link remove events to be dropped
// if the dst switch just disconnected
if (registryService.hasControl(linkEvent.getDst().dpid)) {
datastore.removeLink(linkEvent);
}
} else {
datastore.removeLink(linkEvent);
}
removeLink(linkEvent);
// Send out notification
eventChannel.removeEntry(linkEvent.getID());
}
// TODO handle invariant violation
}
}
|
src/main/java/net/onrc/onos/ofcontroller/networkgraph/TopologyManager.java
|
package net.onrc.onos.ofcontroller.networkgraph;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import net.onrc.onos.datagrid.IDatagridService;
import net.onrc.onos.datagrid.IEventChannel;
import net.onrc.onos.datagrid.IEventChannelListener;
import net.onrc.onos.datastore.topology.RCLink;
import net.onrc.onos.datastore.topology.RCPort;
import net.onrc.onos.datastore.topology.RCSwitch;
import net.onrc.onos.ofcontroller.networkgraph.PortEvent.SwitchPort;
import net.onrc.onos.ofcontroller.util.EventEntry;
import net.onrc.onos.ofcontroller.util.Dpid;
import net.onrc.onos.registry.controller.IControllerRegistryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The "NB" read-only Network Map.
*
* - Maintain Invariant/Relationships between Topology Objects.
*
* TODO To be synchronized based on TopologyEvent Notification.
*
* TODO TBD: Caller is expected to maintain parent/child calling order. Parent
* Object must exist before adding sub component(Add Switch -> Port).
*
* TODO TBD: This class may delay the requested change to handle event
* re-ordering. e.g.) Link Add came in, but Switch was not there.
*
*/
public class TopologyManager implements NetworkGraphDiscoveryInterface {
private static final Logger log = LoggerFactory
.getLogger(TopologyManager.class);
private IEventChannel<byte[], TopologyEvent> eventChannel;
private static final String EVENT_CHANNEL_NAME = "onos.topology";
private EventHandler eventHandler = new EventHandler();
private final NetworkGraphDatastore datastore;
private final NetworkGraphImpl networkGraph = new NetworkGraphImpl();
private final IControllerRegistryService registryService;
private CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners;
//
// Local state for keeping track of reordered events.
// NOTE: Switch Events are not affected by the event reordering.
//
private Map<ByteBuffer, PortEvent> reorderedAddedPortEvents =
new HashMap<ByteBuffer, PortEvent>();
private Map<ByteBuffer, LinkEvent> reorderedAddedLinkEvents =
new HashMap<ByteBuffer, LinkEvent>();
private Map<ByteBuffer, DeviceEvent> reorderedAddedDeviceEvents =
new HashMap<ByteBuffer, DeviceEvent>();
//
// Local state for keeping track of locally discovered events so we can
// cleanup properly when a Switch or Port is removed.
//
// We keep all Port, Link and Device events per Switch DPID:
// - If a switch goes down, we remove all corresponding Port, Link and
// Device events.
// - If a port on a switch goes down, we remove all corresponding Link
// and Device events.
//
private Map<Long, Map<ByteBuffer, PortEvent>> discoveredAddedPortEvents =
new HashMap<>();
private Map<Long, Map<ByteBuffer, LinkEvent>> discoveredAddedLinkEvents =
new HashMap<>();
private Map<Long, Map<ByteBuffer, DeviceEvent>> discoveredAddedDeviceEvents =
new HashMap<>();
//
// Local state for keeping track of the application event notifications
//
List<SwitchEvent> apiAddedSwitchEvents = new LinkedList<SwitchEvent>();
List<SwitchEvent> apiRemovedSwitchEvents = new LinkedList<SwitchEvent>();
List<PortEvent> apiAddedPortEvents = new LinkedList<PortEvent>();
List<PortEvent> apiRemovedPortEvents = new LinkedList<PortEvent>();
List<LinkEvent> apiAddedLinkEvents = new LinkedList<LinkEvent>();
List<LinkEvent> apiRemovedLinkEvents = new LinkedList<LinkEvent>();
List<DeviceEvent> apiAddedDeviceEvents = new LinkedList<DeviceEvent>();
List<DeviceEvent> apiRemovedDeviceEvents = new LinkedList<DeviceEvent>();
/**
* Constructor.
*
* @param registryService the Registry Service to use.
* @param networkGraphListeners the collection of Network Graph Listeners
* to use.
*/
public TopologyManager(IControllerRegistryService registryService,
CopyOnWriteArrayList<INetworkGraphListener> networkGraphListeners) {
datastore = new NetworkGraphDatastore();
this.registryService = registryService;
this.networkGraphListeners = networkGraphListeners;
}
/**
* Get the Network Graph.
*
* @return the Network Graph.
*/
NetworkGraph getNetworkGraph() {
return networkGraph;
}
/**
* Event handler class.
*/
private class EventHandler extends Thread implements
IEventChannelListener<byte[], TopologyEvent> {
private BlockingQueue<EventEntry<TopologyEvent>> topologyEvents =
new LinkedBlockingQueue<EventEntry<TopologyEvent>>();
/**
* Startup processing.
*/
private void startup() {
//
// TODO: Read all state from the database:
//
// Collection<EventEntry<TopologyEvent>> collection =
// readWholeTopologyFromDB();
//
// For now, as a shortcut we read it from the datagrid
//
Collection<TopologyEvent> topologyEvents =
eventChannel.getAllEntries();
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
for (TopologyEvent topologyEvent : topologyEvents) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
processEvents(collection);
}
/**
* Run the thread.
*/
@Override
public void run() {
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
this.setName("TopologyManager.EventHandler " + this.getId());
startup();
//
// The main loop
//
try {
while (true) {
EventEntry<TopologyEvent> eventEntry = topologyEvents.take();
collection.add(eventEntry);
topologyEvents.drainTo(collection);
processEvents(collection);
collection.clear();
}
} catch (Exception exception) {
log.debug("Exception processing Topology Events: ", exception);
}
}
/**
* Process all topology events.
*
* @param events the events to process.
*/
private void processEvents(Collection<EventEntry<TopologyEvent>> events) {
// Local state for computing the final set of events
Map<ByteBuffer, SwitchEvent> addedSwitchEvents = new HashMap<>();
Map<ByteBuffer, SwitchEvent> removedSwitchEvents = new HashMap<>();
Map<ByteBuffer, PortEvent> addedPortEvents = new HashMap<>();
Map<ByteBuffer, PortEvent> removedPortEvents = new HashMap<>();
Map<ByteBuffer, LinkEvent> addedLinkEvents = new HashMap<>();
Map<ByteBuffer, LinkEvent> removedLinkEvents = new HashMap<>();
Map<ByteBuffer, DeviceEvent> addedDeviceEvents = new HashMap<>();
Map<ByteBuffer, DeviceEvent> removedDeviceEvents = new HashMap<>();
//
// Classify and suppress matching events
//
for (EventEntry<TopologyEvent> event : events) {
TopologyEvent topologyEvent = event.eventData();
SwitchEvent switchEvent = topologyEvent.switchEvent;
PortEvent portEvent = topologyEvent.portEvent;
LinkEvent linkEvent = topologyEvent.linkEvent;
DeviceEvent deviceEvent = topologyEvent.deviceEvent;
//
// Extract the events
//
switch (event.eventType()) {
case ENTRY_ADD:
log.debug("Topology event ENTRY_ADD: {}", topologyEvent);
if (switchEvent != null) {
ByteBuffer id = ByteBuffer.wrap(switchEvent.getID());
addedSwitchEvents.put(id, switchEvent);
removedSwitchEvents.remove(id);
// Switch Events are not affected by event reordering
}
if (portEvent != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
addedPortEvents.put(id, portEvent);
removedPortEvents.remove(id);
reorderedAddedPortEvents.remove(id);
}
if (linkEvent != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
addedLinkEvents.put(id, linkEvent);
removedLinkEvents.remove(id);
reorderedAddedLinkEvents.remove(id);
}
if (deviceEvent != null) {
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
addedDeviceEvents.put(id, deviceEvent);
removedDeviceEvents.remove(id);
reorderedAddedDeviceEvents.remove(id);
}
break;
case ENTRY_REMOVE:
log.debug("Topology event ENTRY_REMOVE: {}", topologyEvent);
if (switchEvent != null) {
ByteBuffer id = ByteBuffer.wrap(switchEvent.getID());
addedSwitchEvents.remove(id);
removedSwitchEvents.put(id, switchEvent);
// Switch Events are not affected by event reordering
}
if (portEvent != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
addedPortEvents.remove(id);
removedPortEvents.put(id, portEvent);
reorderedAddedPortEvents.remove(id);
}
if (linkEvent != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
addedLinkEvents.remove(id);
removedLinkEvents.put(id, linkEvent);
reorderedAddedLinkEvents.remove(id);
}
if (deviceEvent != null) {
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
addedDeviceEvents.remove(id);
removedDeviceEvents.put(id, deviceEvent);
reorderedAddedDeviceEvents.remove(id);
}
break;
}
}
//
// Lock the Network Graph while it is modified
//
networkGraph.acquireWriteLock();
//
// Apply the classified events.
//
// Apply the "add" events in the proper order:
// switch, port, link, device
//
for (SwitchEvent switchEvent : addedSwitchEvents.values())
addSwitch(switchEvent);
for (PortEvent portEvent : addedPortEvents.values())
addPort(portEvent);
for (LinkEvent linkEvent : addedLinkEvents.values())
addLink(linkEvent);
for (DeviceEvent deviceEvent : addedDeviceEvents.values())
addDevice(deviceEvent);
//
// Apply the "remove" events in the reverse order:
// device, link, port, switch
//
for (DeviceEvent deviceEvent : removedDeviceEvents.values())
removeDevice(deviceEvent);
for (LinkEvent linkEvent : removedLinkEvents.values())
removeLink(linkEvent);
for (PortEvent portEvent : removedPortEvents.values())
removePort(portEvent);
for (SwitchEvent switchEvent : removedSwitchEvents.values())
removeSwitch(switchEvent);
//
// Apply reordered events
//
applyReorderedEvents(! addedSwitchEvents.isEmpty(),
! addedPortEvents.isEmpty());
//
// Network Graph modifications completed: Release the lock
//
networkGraph.releaseWriteLock();
//
// Dispatch the Topology Notification Events to the applications
//
dispatchNetworkGraphEvents();
}
/**
* Receive a notification that an entry is added.
*
* @param value the value for the entry.
*/
@Override
public void entryAdded(TopologyEvent value) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
value);
topologyEvents.add(eventEntry);
}
/**
* Receive a notification that an entry is removed.
*
* @param value the value for the entry.
*/
@Override
public void entryRemoved(TopologyEvent value) {
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_REMOVE,
value);
topologyEvents.add(eventEntry);
}
/**
* Receive a notification that an entry is updated.
*
* @param value the value for the entry.
*/
@Override
public void entryUpdated(TopologyEvent value) {
// NOTE: The ADD and UPDATE events are processed in same way
entryAdded(value);
}
}
/**
* Startup processing.
*
* @param datagridService the datagrid service to use.
*/
void startup(IDatagridService datagridService) {
eventChannel = datagridService.addListener(EVENT_CHANNEL_NAME,
eventHandler,
byte[].class,
TopologyEvent.class);
eventHandler.start();
}
/**
* Dispatch Network Graph Events to the listeners.
*/
private void dispatchNetworkGraphEvents() {
if (apiAddedSwitchEvents.isEmpty() &&
apiRemovedSwitchEvents.isEmpty() &&
apiAddedPortEvents.isEmpty() &&
apiRemovedPortEvents.isEmpty() &&
apiAddedLinkEvents.isEmpty() &&
apiRemovedLinkEvents.isEmpty() &&
apiAddedDeviceEvents.isEmpty() &&
apiRemovedDeviceEvents.isEmpty()) {
return; // No events to dispatch
}
// Deliver the events
for (INetworkGraphListener listener : this.networkGraphListeners) {
// TODO: Should copy before handing them over to listener?
listener.networkGraphEvents(apiAddedSwitchEvents,
apiRemovedSwitchEvents,
apiAddedPortEvents,
apiRemovedPortEvents,
apiAddedLinkEvents,
apiRemovedLinkEvents,
apiAddedDeviceEvents,
apiRemovedDeviceEvents);
}
//
// Cleanup
//
apiAddedSwitchEvents.clear();
apiRemovedSwitchEvents.clear();
apiAddedPortEvents.clear();
apiRemovedPortEvents.clear();
apiAddedLinkEvents.clear();
apiRemovedLinkEvents.clear();
apiAddedDeviceEvents.clear();
apiRemovedDeviceEvents.clear();
}
/**
* Apply reordered events.
*
* @param hasAddedSwitchEvents true if there were Added Switch Events.
* @param hasAddedPortEvents true if there were Added Port Events.
*/
private void applyReorderedEvents(boolean hasAddedSwitchEvents,
boolean hasAddedPortEvents) {
if (! (hasAddedSwitchEvents || hasAddedPortEvents))
return; // Nothing to do
//
// Try to apply the reordered events.
//
// NOTE: For simplicity we try to apply all events of a particular
// type if any "parent" type event was processed:
// - Apply reordered Port Events if Switches were added
// - Apply reordered Link and Device Events if Switches or Ports
// were added
//
Map<ByteBuffer, PortEvent> portEvents = reorderedAddedPortEvents;
Map<ByteBuffer, LinkEvent> linkEvents = reorderedAddedLinkEvents;
Map<ByteBuffer, DeviceEvent> deviceEvents = reorderedAddedDeviceEvents;
reorderedAddedPortEvents = new HashMap<>();
reorderedAddedLinkEvents = new HashMap<>();
reorderedAddedDeviceEvents = new HashMap<>();
//
// Apply reordered Port Events if Switches were added
//
if (hasAddedSwitchEvents) {
for (PortEvent portEvent : portEvents.values())
addPort(portEvent);
}
//
// Apply reordered Link and Device Events if Switches or Ports
// were added.
//
for (LinkEvent linkEvent : linkEvents.values())
addLink(linkEvent);
for (DeviceEvent deviceEvent : deviceEvents.values())
addDevice(deviceEvent);
}
/* ******************************
* NetworkGraphDiscoveryInterface methods
* ******************************/
@Override
public void putSwitchDiscoveryEvent(SwitchEvent switchEvent,
Collection<PortEvent> portEvents) {
if (datastore.addSwitch(switchEvent, portEvents)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Send out notification for each port
for (PortEvent portEvent : portEvents) {
topologyEvent = new TopologyEvent(portEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
}
//
// Keep track of the added ports
//
// Get the old Port Events
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(switchEvent.getDpid());
if (oldPortEvents == null)
oldPortEvents = new HashMap<>();
// Store the new Port Events in the local cache
Map<ByteBuffer, PortEvent> newPortEvents = new HashMap<>();
for (PortEvent portEvent : portEvents) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
newPortEvents.put(id, portEvent);
}
discoveredAddedPortEvents.put(switchEvent.getDpid(),
newPortEvents);
//
// Extract the removed ports
//
List<PortEvent> removedPortEvents = new LinkedList<>();
for (Map.Entry<ByteBuffer, PortEvent> entry : oldPortEvents.entrySet()) {
ByteBuffer key = entry.getKey();
PortEvent portEvent = entry.getValue();
if (! newPortEvents.containsKey(key))
removedPortEvents.add(portEvent);
}
// Cleanup old removed ports
for (PortEvent portEvent : removedPortEvents)
removePortDiscoveryEvent(portEvent);
}
}
@Override
public void removeSwitchDiscoveryEvent(SwitchEvent switchEvent) {
// Get the old Port Events
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(switchEvent.getDpid());
if (oldPortEvents == null)
oldPortEvents = new HashMap<>();
if (datastore.deactivateSwitch(switchEvent, oldPortEvents.values())) {
// Send out notification
eventChannel.removeEntry(switchEvent.getID());
// Send out notification for each port
for (PortEvent portEvent : oldPortEvents.values())
eventChannel.removeEntry(portEvent.getID());
discoveredAddedPortEvents.remove(switchEvent.getDpid());
// Cleanup for each link
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(switchEvent.getDpid());
if (oldLinkEvents != null) {
for (LinkEvent linkEvent : oldLinkEvents.values())
removeLinkDiscoveryEvent(linkEvent);
discoveredAddedLinkEvents.remove(switchEvent.getDpid());
}
// Cleanup for each device
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(switchEvent.getDpid());
if (oldDeviceEvents != null) {
for (DeviceEvent deviceEvent : oldDeviceEvents.values())
removeDeviceDiscoveryEvent(deviceEvent);
discoveredAddedDeviceEvents.remove(switchEvent.getDpid());
}
}
}
@Override
public void putPortDiscoveryEvent(PortEvent portEvent) {
if (datastore.addPort(portEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(portEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Port Event in the local cache
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(portEvent.getDpid());
if (oldPortEvents == null) {
oldPortEvents = new HashMap<>();
discoveredAddedPortEvents.put(portEvent.getDpid(),
oldPortEvents);
}
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
oldPortEvents.put(id, portEvent);
}
}
@Override
public void removePortDiscoveryEvent(PortEvent portEvent) {
if (datastore.deactivatePort(portEvent)) {
// Send out notification
eventChannel.removeEntry(portEvent.getID());
// Cleanup the Port Event from the local cache
Map<ByteBuffer, PortEvent> oldPortEvents =
discoveredAddedPortEvents.get(portEvent.getDpid());
if (oldPortEvents != null) {
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
oldPortEvents.remove(id);
}
// Cleanup for the incoming link
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(portEvent.getDpid());
if (oldLinkEvents != null) {
for (LinkEvent linkEvent : oldLinkEvents.values()) {
if (linkEvent.getDst().equals(portEvent.id)) {
removeLinkDiscoveryEvent(linkEvent);
//
// NOTE: oldLinkEvents was modified by
// removeLinkDiscoveryEvent() and cannot be iterated
// anymore.
//
break;
}
}
}
// Cleanup for the connected devices
// TODO: The implementation below is probably wrong
List<DeviceEvent> removedDeviceEvents = new LinkedList<>();
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(portEvent.getDpid());
if (oldDeviceEvents != null) {
for (DeviceEvent deviceEvent : oldDeviceEvents.values()) {
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
if (swp.equals(portEvent.id)) {
removedDeviceEvents.add(deviceEvent);
break;
}
}
}
for (DeviceEvent deviceEvent : removedDeviceEvents)
removeDeviceDiscoveryEvent(deviceEvent);
}
}
}
@Override
public void putLinkDiscoveryEvent(LinkEvent linkEvent) {
if (datastore.addLink(linkEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Link Event in the local cache
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
if (oldLinkEvents == null) {
oldLinkEvents = new HashMap<>();
discoveredAddedLinkEvents.put(linkEvent.getDst().getDpid(),
oldLinkEvents);
}
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
oldLinkEvents.put(id, linkEvent);
}
}
@Override
public void removeLinkDiscoveryEvent(LinkEvent linkEvent) {
if (datastore.removeLink(linkEvent)) {
// Send out notification
eventChannel.removeEntry(linkEvent.getID());
// Cleanup the Link Event from the local cache
Map<ByteBuffer, LinkEvent> oldLinkEvents =
discoveredAddedLinkEvents.get(linkEvent.getDst().getDpid());
if (oldLinkEvents != null) {
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
oldLinkEvents.remove(id);
}
}
}
@Override
public void putDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
if (datastore.addDevice(deviceEvent)) {
// Send out notification
TopologyEvent topologyEvent = new TopologyEvent(deviceEvent);
eventChannel.addEntry(topologyEvent.getID(), topologyEvent);
// Store the new Device Event in the local cache
// TODO: The implementation below is probably wrong
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(swp.getDpid());
if (oldDeviceEvents == null) {
oldDeviceEvents = new HashMap<>();
discoveredAddedDeviceEvents.put(swp.getDpid(),
oldDeviceEvents);
}
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
oldDeviceEvents.put(id, deviceEvent);
}
}
}
@Override
public void removeDeviceDiscoveryEvent(DeviceEvent deviceEvent) {
if (datastore.removeDevice(deviceEvent)) {
// Send out notification
eventChannel.removeEntry(deviceEvent.getID());
// Cleanup the Device Event from the local cache
// TODO: The implementation below is probably wrong
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
Map<ByteBuffer, DeviceEvent> oldDeviceEvents =
discoveredAddedDeviceEvents.get(swp.getDpid());
if (oldDeviceEvents != null) {
oldDeviceEvents.remove(id);
}
}
}
}
/* ************************************************
* Internal methods to maintain the network graph
* ************************************************/
private void addSwitch(SwitchEvent switchEvent) {
Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
if (sw == null) {
sw = new SwitchImpl(networkGraph, switchEvent.getDpid());
networkGraph.putSwitch(sw);
} else {
// TODO: Update the switch attributes
// TODO: Nothing to do for now
}
apiAddedSwitchEvents.add(switchEvent);
}
private void removeSwitch(SwitchEvent switchEvent) {
Switch sw = networkGraph.getSwitch(switchEvent.getDpid());
if (sw == null) {
log.warn("Switch {} already removed, ignoring", switchEvent);
return;
}
//
// Remove all Ports on the Switch
//
ArrayList<PortEvent> portsToRemove = new ArrayList<>();
for (Port port : sw.getPorts()) {
log.warn("Port {} on Switch {} should be removed prior to removing Switch. Removing Port now.",
port, switchEvent);
PortEvent portEvent = new PortEvent(port.getDpid(),
port.getNumber());
portsToRemove.add(portEvent);
}
for (PortEvent portEvent : portsToRemove)
removePort(portEvent);
networkGraph.removeSwitch(switchEvent.getDpid());
apiRemovedSwitchEvents.add(switchEvent);
}
private void addPort(PortEvent portEvent) {
Switch sw = networkGraph.getSwitch(portEvent.getDpid());
if (sw == null) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(portEvent.getID());
reorderedAddedPortEvents.put(id, portEvent);
return;
}
SwitchImpl switchImpl = getSwitchImpl(sw);
Port port = sw.getPort(portEvent.getNumber());
if (port == null) {
port = new PortImpl(networkGraph, sw, portEvent.getNumber());
switchImpl.addPort(port);
} else {
// TODO: Update the port attributes
}
apiAddedPortEvents.add(portEvent);
}
private void removePort(PortEvent portEvent) {
Switch sw = networkGraph.getSwitch(portEvent.getDpid());
if (sw == null) {
log.warn("Parent Switch for Port {} already removed, ignoring",
portEvent);
return;
}
Port port = sw.getPort(portEvent.getNumber());
if (port == null) {
log.warn("Port {} already removed, ignoring", portEvent);
return;
}
//
// Remove all Devices attached to the Port
//
ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
for (Device device : port.getDevices()) {
log.debug("Removing Device {} on Port {}", device, portEvent);
DeviceEvent deviceEvent = new DeviceEvent(device.getMacAddress());
SwitchPort switchPort = new SwitchPort(port.getSwitch().getDpid(),
port.getNumber());
deviceEvent.addAttachmentPoint(switchPort);
devicesToRemove.add(deviceEvent);
}
for (DeviceEvent deviceEvent : devicesToRemove)
removeDevice(deviceEvent);
//
// Remove all Links connected to the Port
//
Set<Link> links = new HashSet<>();
links.add(port.getOutgoingLink());
links.add(port.getIncomingLink());
ArrayList<LinkEvent> linksToRemove = new ArrayList<>();
for (Link link : links) {
if (link == null)
continue;
log.debug("Removing Link {} on Port {}", link, portEvent);
LinkEvent linkEvent = new LinkEvent(link.getSrcSwitch().getDpid(),
link.getSrcPort().getNumber(),
link.getDstSwitch().getDpid(),
link.getDstPort().getNumber());
linksToRemove.add(linkEvent);
}
for (LinkEvent linkEvent : linksToRemove)
removeLink(linkEvent);
// Remove the Port from the Switch
SwitchImpl switchImpl = getSwitchImpl(sw);
switchImpl.removePort(port);
apiRemovedPortEvents.add(portEvent);
}
private void addLink(LinkEvent linkEvent) {
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if ((srcPort == null) || (dstPort == null)) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(linkEvent.getID());
reorderedAddedLinkEvents.put(id, linkEvent);
return;
}
// Get the Link instance from the Destination Port Incoming Link
Link link = dstPort.getIncomingLink();
assert(link == srcPort.getOutgoingLink());
if (link == null) {
link = new LinkImpl(networkGraph, srcPort, dstPort);
PortImpl srcPortImpl = getPortImpl(srcPort);
PortImpl dstPortImpl = getPortImpl(dstPort);
srcPortImpl.setOutgoingLink(link);
dstPortImpl.setIncomingLink(link);
// Remove all Devices attached to the Ports
ArrayList<DeviceEvent> devicesToRemove = new ArrayList<>();
ArrayList<Port> ports = new ArrayList<>();
ports.add(srcPort);
ports.add(dstPort);
for (Port port : ports) {
for (Device device : port.getDevices()) {
log.error("Device {} on Port {} should have been removed prior to adding Link {}",
device, port, linkEvent);
DeviceEvent deviceEvent =
new DeviceEvent(device.getMacAddress());
SwitchPort switchPort =
new SwitchPort(port.getSwitch().getDpid(),
port.getNumber());
deviceEvent.addAttachmentPoint(switchPort);
devicesToRemove.add(deviceEvent);
}
}
for (DeviceEvent deviceEvent : devicesToRemove)
removeDevice(deviceEvent);
} else {
// TODO: Update the link attributes
}
apiAddedLinkEvents.add(linkEvent);
}
private void removeLink(LinkEvent linkEvent) {
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
if (srcPort == null) {
log.warn("Src Port for Link {} already removed, ignoring",
linkEvent);
return;
}
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (dstPort == null) {
log.warn("Dst Port for Link {} already removed, ignoring",
linkEvent);
return;
}
//
// Remove the Link instance from the Destination Port Incoming Link
// and the Source Port Outgoing Link.
//
Link link = dstPort.getIncomingLink();
if (link == null) {
log.warn("Link {} already removed on destination Port", linkEvent);
}
link = srcPort.getOutgoingLink();
if (link == null) {
log.warn("Link {} already removed on src Port", linkEvent);
}
getPortImpl(dstPort).setIncomingLink(null);
getPortImpl(srcPort).setOutgoingLink(null);
apiRemovedLinkEvents.add(linkEvent);
}
// TODO: Device-related work is incomplete
private void addDevice(DeviceEvent deviceEvent) {
Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
if (device == null) {
device = new DeviceImpl(networkGraph, deviceEvent.getMac());
}
DeviceImpl deviceImpl = getDeviceImpl(device);
// Update the IP addresses
for (InetAddress ipAddr : deviceEvent.getIpAddresses())
deviceImpl.addIpAddress(ipAddr);
// Process each attachment point
boolean attachmentFound = false;
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
// Reordered event: delay the event in local cache
ByteBuffer id = ByteBuffer.wrap(deviceEvent.getID());
reorderedAddedDeviceEvents.put(id, deviceEvent);
continue;
}
// Attached Ports must not have Link
if (port.getOutgoingLink() != null ||
port.getIncomingLink() != null) {
log.warn("Link (Out:{},In:{}) exist on the attachment point, skipping mutation.",
port.getOutgoingLink(),
port.getIncomingLink());
continue;
}
// Add Device <-> Port attachment
PortImpl portImpl = getPortImpl(port);
portImpl.addDevice(device);
deviceImpl.addAttachmentPoint(port);
attachmentFound = true;
}
// Update the device in the Network Graph
if (attachmentFound) {
networkGraph.putDevice(device);
apiAddedDeviceEvents.add(deviceEvent);
}
}
private void removeDevice(DeviceEvent deviceEvent) {
Device device = networkGraph.getDeviceByMac(deviceEvent.getMac());
if (device == null) {
log.warn("Device {} already removed, ignoring", deviceEvent);
return;
}
DeviceImpl deviceImpl = getDeviceImpl(device);
// Process each attachment point
for (SwitchPort swp : deviceEvent.getAttachmentPoints()) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
log.warn("Port for the attachment point {} did not exist. skipping attachment point mutation", swp);
continue;
}
// Remove Device <-> Port attachment
PortImpl portImpl = getPortImpl(port);
portImpl.removeDevice(device);
deviceImpl.removeAttachmentPoint(port);
}
networkGraph.removeDevice(device);
apiRemovedDeviceEvents.add(deviceEvent);
}
/**
*
* @param switchEvent
* @return true if ready to accept event.
*/
private boolean prepareForAddSwitchEvent(SwitchEvent switchEvent) {
// No show stopping precondition
return true;
}
private boolean prepareForRemoveSwitchEvent(SwitchEvent switchEvent) {
// No show stopping precondition
return true;
}
private boolean prepareForAddPortEvent(PortEvent portEvent) {
// Parent Switch must exist
if (networkGraph.getSwitch(portEvent.getDpid()) == null) {
log.warn("Dropping add port event because switch doesn't exist: {}",
portEvent);
return false;
}
// Prep: None
return true;
}
private boolean prepareForRemovePortEvent(PortEvent portEvent) {
Port port = networkGraph.getPort(portEvent.getDpid(),
portEvent.getNumber());
if (port == null) {
log.debug("Port already removed? {}", portEvent);
// let it pass
return true;
}
// Prep: Remove Link and Device Attachment
ArrayList<DeviceEvent> deviceEvents = new ArrayList<>();
for (Device device : port.getDevices()) {
log.debug("Removing Device {} on Port {}", device, portEvent);
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(port.getSwitch().getDpid(),
port.getNumber()));
deviceEvents.add(devEvent);
}
for (DeviceEvent devEvent : deviceEvents) {
// calling Discovery API to wipe from DB, etc.
removeDeviceDiscoveryEvent(devEvent);
}
Set<Link> links = new HashSet<>();
links.add(port.getOutgoingLink());
links.add(port.getIncomingLink());
for (Link link : links) {
if (link == null) {
continue;
}
log.debug("Removing Link {} on Port {}", link, portEvent);
LinkEvent linkEvent =
new LinkEvent(link.getSrcSwitch().getDpid(),
link.getSrcPort().getNumber(),
link.getDstSwitch().getDpid(),
link.getDstPort().getNumber());
// calling Discovery API to wipe from DB, etc.
// Call internal remove Link, which will check
// ownership of DST dpid and modify DB only if it is the owner
removeLinkDiscoveryEvent(linkEvent, true);
}
return true;
}
private boolean prepareForAddLinkEvent(LinkEvent linkEvent) {
// Src/Dst Port must exist
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (srcPort == null || dstPort == null) {
log.warn("Dropping add link event because port doesn't exist: {}",
linkEvent);
return false;
}
// Prep: remove Device attachment on both Ports
ArrayList<DeviceEvent> deviceEvents = new ArrayList<>();
for (Device device : srcPort.getDevices()) {
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(srcPort.getSwitch().getDpid(), srcPort.getNumber()));
deviceEvents.add(devEvent);
}
for (Device device : dstPort.getDevices()) {
DeviceEvent devEvent = new DeviceEvent(device.getMacAddress());
devEvent.addAttachmentPoint(new SwitchPort(dstPort.getSwitch().getDpid(),
dstPort.getNumber()));
deviceEvents.add(devEvent);
}
for (DeviceEvent devEvent : deviceEvents) {
// calling Discovery API to wipe from DB, etc.
removeDeviceDiscoveryEvent(devEvent);
}
return true;
}
private boolean prepareForRemoveLinkEvent(LinkEvent linkEvent) {
// Src/Dst Port must exist
Port srcPort = networkGraph.getPort(linkEvent.getSrc().dpid,
linkEvent.getSrc().number);
Port dstPort = networkGraph.getPort(linkEvent.getDst().dpid,
linkEvent.getDst().number);
if (srcPort == null || dstPort == null) {
log.warn("Dropping remove link event because port doesn't exist {}", linkEvent);
return false;
}
Link link = srcPort.getOutgoingLink();
// Link is already gone, or different Link exist in memory
// XXX Check if we should reject or just accept these cases.
// it should be harmless to remove the Link on event from DB anyways
if (link == null ||
!link.getDstPort().getNumber().equals(linkEvent.getDst().number)
|| !link.getDstSwitch().getDpid().equals(linkEvent.getDst().dpid)) {
log.warn("Dropping remove link event because link doesn't exist: {}", linkEvent);
return false;
}
// Prep: None
return true;
}
/**
*
* @param deviceEvent Event will be modified to remove inapplicable attachemntPoints/ipAddress
* @return false if this event should be dropped.
*/
private boolean prepareForAddDeviceEvent(DeviceEvent deviceEvent) {
boolean preconditionBroken = false;
ArrayList<PortEvent.SwitchPort> failedSwitchPort = new ArrayList<>();
for ( PortEvent.SwitchPort swp : deviceEvent.getAttachmentPoints() ) {
// Attached Ports must exist
Port port = networkGraph.getPort(swp.dpid, swp.number);
if (port == null) {
preconditionBroken = true;
failedSwitchPort.add(swp);
continue;
}
// Attached Ports must not have Link
if (port.getOutgoingLink() != null ||
port.getIncomingLink() != null) {
preconditionBroken = true;
failedSwitchPort.add(swp);
continue;
}
}
// Rewriting event to exclude failed attachmentPoint
// XXX Assumption behind this is that inapplicable device event should
// be dropped, not deferred. If we decide to defer Device event,
// rewriting can become a problem
List<SwitchPort> attachmentPoints = deviceEvent.getAttachmentPoints();
attachmentPoints.removeAll(failedSwitchPort);
deviceEvent.setAttachmentPoints(attachmentPoints);
if (deviceEvent.getAttachmentPoints().isEmpty() &&
deviceEvent.getIpAddresses().isEmpty()) {
// return false to represent: Nothing left to do for this event.
// Caller should drop event
return false;
}
// Should we return false to tell caller that the event was trimmed?
// if ( preconditionBroken ) {
// return false;
// }
return true;
}
private boolean prepareForRemoveDeviceEvent(DeviceEvent deviceEvent) {
// No show stopping precondition?
// Prep: none
return true;
}
private SwitchImpl getSwitchImpl(Switch sw) {
if (sw instanceof SwitchImpl) {
return (SwitchImpl) sw;
}
throw new ClassCastException("SwitchImpl expected, but found: " + sw);
}
private PortImpl getPortImpl(Port p) {
if (p instanceof PortImpl) {
return (PortImpl) p;
}
throw new ClassCastException("PortImpl expected, but found: " + p);
}
private LinkImpl getLinkImpl(Link l) {
if (l instanceof LinkImpl) {
return (LinkImpl) l;
}
throw new ClassCastException("LinkImpl expected, but found: " + l);
}
private DeviceImpl getDeviceImpl(Device d) {
if (d instanceof DeviceImpl) {
return (DeviceImpl) d;
}
throw new ClassCastException("DeviceImpl expected, but found: " + d);
}
@Deprecated
private Collection<EventEntry<TopologyEvent>> readWholeTopologyFromDB() {
Collection<EventEntry<TopologyEvent>> collection =
new LinkedList<EventEntry<TopologyEvent>>();
// XXX May need to clear whole topology first, depending on
// how we initially subscribe to replication events
// Add all active switches
for (RCSwitch sw : RCSwitch.getAllSwitches()) {
if (sw.getStatus() != RCSwitch.STATUS.ACTIVE) {
continue;
}
SwitchEvent switchEvent = new SwitchEvent(sw.getDpid());
TopologyEvent topologyEvent = new TopologyEvent(switchEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
// Add all active ports
for (RCPort p : RCPort.getAllPorts()) {
if (p.getStatus() != RCPort.STATUS.ACTIVE) {
continue;
}
PortEvent portEvent = new PortEvent(p.getDpid(), p.getNumber());
TopologyEvent topologyEvent = new TopologyEvent(portEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
// TODO Is Device going to be in DB? If so, read from DB.
// for (RCDevice d : RCDevice.getAllDevices()) {
// DeviceEvent devEvent = new DeviceEvent( MACAddress.valueOf(d.getMac()) );
// for (byte[] portId : d.getAllPortIds() ) {
// devEvent.addAttachmentPoint( new SwitchPort( RCPort.getDpidFromKey(portId), RCPort.getNumberFromKey(portId) ));
// }
// }
for (RCLink l : RCLink.getAllLinks()) {
// check if src/dst switch/port exist before triggering event
Port srcPort = networkGraph.getPort(l.getSrc().dpid,
l.getSrc().number);
Port dstPort = networkGraph.getPort(l.getDst().dpid,
l.getDst().number);
if (srcPort == null || dstPort == null) {
continue;
}
LinkEvent linkEvent = new LinkEvent(l.getSrc().dpid,
l.getSrc().number,
l.getDst().dpid,
l.getDst().number);
TopologyEvent topologyEvent = new TopologyEvent(linkEvent);
EventEntry<TopologyEvent> eventEntry =
new EventEntry<TopologyEvent>(EventEntry.Type.ENTRY_ADD,
topologyEvent);
collection.add(eventEntry);
}
return collection;
}
@Deprecated
private void removeLinkDiscoveryEvent(LinkEvent linkEvent,
boolean dstCheckBeforeDBmodify) {
if (prepareForRemoveLinkEvent(linkEvent)) {
if (dstCheckBeforeDBmodify) {
// write to DB only if it is owner of the dst dpid
// XXX this will cause link remove events to be dropped
// if the dst switch just disconnected
if (registryService.hasControl(linkEvent.getDst().dpid)) {
datastore.removeLink(linkEvent);
}
} else {
datastore.removeLink(linkEvent);
}
removeLink(linkEvent);
// Send out notification
eventChannel.removeEntry(linkEvent.getID());
}
// TODO handle invariant violation
}
}
|
Release the lock inside a finally block to ensure it is released
Change-Id: I522a35000edefd8d1e9829b0ed746fc85b771668
|
src/main/java/net/onrc/onos/ofcontroller/networkgraph/TopologyManager.java
|
Release the lock inside a finally block to ensure it is released
|
|
Java
|
apache-2.0
|
b281da84a487dc41b629cc6ab11f4afd456376cb
| 0
|
wildfly-swarm/wildfly-swarm-bom,wildfly-swarm/wildfly-swarm-bom
|
/**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.plugin.maven;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.Authentication;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.collection.CollectResult;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.impl.ArtifactResolver;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;
import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.wildfly.swarm.tools.ArtifactResolvingHelper;
import org.wildfly.swarm.tools.ArtifactSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author Bob McWhirter
*/
public class MavenArtifactResolvingHelper implements ArtifactResolvingHelper {
final private ArtifactResolver resolver;
final protected RepositorySystemSession session;
final protected List<RemoteRepository> remoteRepositories = new ArrayList<>();
final private RepositorySystem system;
public MavenArtifactResolvingHelper(ArtifactResolver resolver,
RepositorySystem system,
RepositorySystemSession session) {
this.resolver = resolver;
this.system = system;
this.session = session;
this.remoteRepositories.add(new RemoteRepository.Builder("jboss-public-repository-group", "default", "http://repository.jboss.org/nexus/content/groups/public/").build());
}
public void remoteRepository(ArtifactRepository repo) {
RemoteRepository.Builder builder = new RemoteRepository.Builder(repo.getId(), "default", repo.getUrl());
final Authentication mavenAuth = repo.getAuthentication();
if (mavenAuth != null && mavenAuth.getUsername() != null && mavenAuth.getPassword() != null) {
builder.setAuthentication(new AuthenticationBuilder()
.addUsername(mavenAuth.getUsername())
.addPassword(mavenAuth.getPassword()).build());
}
this.remoteRepositories.add(builder.build());
}
public void remoteRepository(RemoteRepository repo) {
this.remoteRepositories.add(repo);
}
@Override
public ArtifactSpec resolve(ArtifactSpec spec) {
if (spec.file != null) {
return spec;
}
ArtifactRequest request = new ArtifactRequest();
DefaultArtifact artifact = new DefaultArtifact(spec.groupId(), spec.artifactId(), spec.classifier(), spec.type(), spec.version());
request.setArtifact(artifact);
request.setRepositories(this.remoteRepositories);
try {
ArtifactResult result = resolver.resolveArtifact(this.session, request);
if (result.isResolved()) {
spec.file = result.getArtifact().getFile();
return spec;
}
} catch (ArtifactResolutionException e) {
System.err.println("ERR " + e);
e.printStackTrace();
return null;
}
return null;
}
@Override
public Set<ArtifactSpec> resolveAll(Set<ArtifactSpec> specs) throws Exception {
if (specs.isEmpty()) {
return specs;
}
final CollectRequest request = new CollectRequest();
request.setRepositories(this.remoteRepositories);
specs.forEach(spec -> request
.addDependency(new Dependency(new DefaultArtifact(spec.groupId(),
spec.artifactId(),
spec.classifier(),
spec.type(),
spec.version()),
"compile")));
CollectResult result = this.system.collectDependencies(this.session, request);
PreorderNodeListGenerator gen = new PreorderNodeListGenerator();
result.getRoot().accept(gen);
return gen.getNodes().stream()
.filter(node -> !"system".equals(node.getDependency().getScope()))
.map(node -> {
final Artifact artifact = node.getArtifact();
return new ArtifactSpec(node.getDependency().getScope(),
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion(),
artifact.getExtension(),
artifact.getClassifier(),
null);
})
.map(this::resolve)
.filter(x -> x != null)
.collect(Collectors.toSet());
}
}
|
src/main/java/org/wildfly/swarm/plugin/maven/MavenArtifactResolvingHelper.java
|
/**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.plugin.maven;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.Authentication;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.collection.CollectResult;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.impl.ArtifactResolver;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;
import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.wildfly.swarm.tools.ArtifactResolvingHelper;
import org.wildfly.swarm.tools.ArtifactSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author Bob McWhirter
*/
public class MavenArtifactResolvingHelper implements ArtifactResolvingHelper {
final private ArtifactResolver resolver;
final protected RepositorySystemSession session;
final protected List<RemoteRepository> remoteRepositories = new ArrayList<>();
final private RepositorySystem system;
public MavenArtifactResolvingHelper(ArtifactResolver resolver, RepositorySystem system, RepositorySystemSession session) {
this.resolver = resolver;
this.system = system;
this.session = session;
this.remoteRepositories.add(new RemoteRepository.Builder("jboss-public-repository-group", "default", "http://repository.jboss.org/nexus/content/groups/public/").build());
}
public void remoteRepository(ArtifactRepository repo) {
RemoteRepository.Builder builder = new RemoteRepository.Builder(repo.getId(), "default", repo.getUrl());
final Authentication mavenAuth = repo.getAuthentication();
if (mavenAuth != null && mavenAuth.getUsername() != null && mavenAuth.getPassword() != null) {
builder.setAuthentication(new AuthenticationBuilder()
.addUsername(mavenAuth.getUsername())
.addPassword(mavenAuth.getPassword()).build());
}
this.remoteRepositories.add(builder.build());
}
public void remoteRepository(RemoteRepository repo) {
this.remoteRepositories.add(repo);
}
@Override
public ArtifactSpec resolve(ArtifactSpec spec) {
if (spec.file != null) {
return spec;
}
ArtifactRequest request = new ArtifactRequest();
DefaultArtifact artifact = new DefaultArtifact(spec.groupId(), spec.artifactId(), spec.classifier(), spec.type(), spec.version());
request.setArtifact(artifact);
request.setRepositories(this.remoteRepositories);
try {
ArtifactResult result = resolver.resolveArtifact(this.session, request);
if (result.isResolved()) {
spec.file = result.getArtifact().getFile();
return spec;
}
} catch (ArtifactResolutionException e) {
System.err.println("ERR " + e);
e.printStackTrace();
return null;
}
return null;
}
@Override
public Set<ArtifactSpec> resolveAll(Set<ArtifactSpec> specs) throws Exception {
if (specs.isEmpty()) {
return specs;
}
final CollectRequest request = new CollectRequest();
request.setRepositories(this.remoteRepositories);
specs.forEach(spec -> request
.addDependency(new Dependency(new DefaultArtifact(spec.groupId(),
spec.artifactId(),
spec.classifier(),
spec.type(),
spec.version()),
"compile")));
CollectResult result = this.system.collectDependencies(this.session, request);
PreorderNodeListGenerator gen = new PreorderNodeListGenerator();
result.getRoot().accept(gen);
return gen.getNodes().stream()
.map(node -> {
Artifact artifact = node.getArtifact();
return new ArtifactSpec("compile",
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion(),
artifact.getExtension(),
artifact.getClassifier(),
null);
})
.map(this::resolve)
.filter(x -> x != null)
.collect(Collectors.toSet());
}
}
|
Filter system-scoped dependencies when resolving [SWARM-270]
Motivation:
System-scoped dependencies shouldn't be resolved via aether, since they
are provided by the jvm. Attempting to resolve them results in an error.
Modifications:
* resolution modified to remove all system-scoped deps from the tree
before doing final resolution of each
Result:
Dependencies that have system-scoped transitives can now be used.
|
src/main/java/org/wildfly/swarm/plugin/maven/MavenArtifactResolvingHelper.java
|
Filter system-scoped dependencies when resolving [SWARM-270]
|
|
Java
|
apache-2.0
|
25653fb72e0ffaef6832a51874884b5dbe98ea0e
| 0
|
buckett/evaluation,csev/evaluation,csev/evaluation,sakaiproject/evaluation,buckett/evaluation,csev/evaluation,buckett/evaluation,sakaiproject/evaluation,sakaiproject/evaluation
|
/******************************************************************************
* EvalAssignsLogicImplTest.java - created by aaronz@vt.edu on Dec 28, 2006
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Contributors:
* Aaron Zeckoski (aaronz@vt.edu) - primary
*
*****************************************************************************/
package org.sakaiproject.evaluation.logic.test;
import java.util.Date;
import java.util.List;
import junit.framework.Assert;
import org.sakaiproject.evaluation.dao.EvaluationDao;
import org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl;
import org.sakaiproject.evaluation.logic.test.stubs.EvalExternalLogicStub;
import org.sakaiproject.evaluation.model.EvalAssignContext;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalScale;
import org.sakaiproject.evaluation.test.EvalTestDataLoad;
import org.sakaiproject.evaluation.test.PreloadTestData;
import org.springframework.test.AbstractTransactionalSpringContextTests;
/**
* Test class for EvalAssignsLogicImpl
*
* @author Aaron Zeckoski (aaronz@vt.edu)
*/
public class EvalAssignsLogicImplTest extends AbstractTransactionalSpringContextTests {
protected EvalAssignsLogicImpl assigns;
private EvaluationDao evaluationDao;
private EvalTestDataLoad etdl;
protected String[] getConfigLocations() {
// point to the needed spring config files, must be on the classpath
// (add component/src/webapp/WEB-INF to the build path in Eclipse),
// they also need to be referenced in the project.xml file
return new String[] {"hibernate-test.xml", "spring-hibernate.xml"};
}
// run this before each test starts
protected void onSetUpBeforeTransaction() throws Exception {
// load the spring created dao class bean from the Spring Application Context
evaluationDao = (EvaluationDao) applicationContext.getBean("org.sakaiproject.evaluation.dao.EvaluationDao");
if (evaluationDao == null) {
throw new NullPointerException("EvaluationDao could not be retrieved from spring context");
}
// check the preloaded data
Assert.assertTrue("Error preloading data", evaluationDao.countAll(EvalScale.class) > 0);
// check the preloaded test data
Assert.assertTrue("Error preloading test data", evaluationDao.countAll(EvalEvaluation.class) > 0);
PreloadTestData ptd = (PreloadTestData) applicationContext.getBean("org.sakaiproject.evaluation.test.PreloadTestData");
if (ptd == null) {
throw new NullPointerException("PreloadTestData could not be retrieved from spring context");
}
// get test objects
etdl = ptd.getEtdl();
// load up any other needed spring beans
// setup the mock objects if needed
// create and setup the object to be tested
assigns = new EvalAssignsLogicImpl();
assigns.setDao(evaluationDao);
assigns.setExternalLogic( new EvalExternalLogicStub() );
}
// run this before each test starts and as part of the transaction
protected void onSetUpInTransaction() {
// preload additional data if desired
}
/**
* ADD unit tests below here, use testMethod as the name of the unit test,
* Note that if a method is overloaded you should include the arguments in the
* test name like so: testMethodClassInt (for method(Class, int);
*/
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#saveAssignContext(org.sakaiproject.evaluation.model.EvalAssignContext, java.lang.String)}.
*/
public void testSaveAssignContext() {
// test adding context to inqueue eval
EvalAssignContext eacNew = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
assigns.saveAssignContext(eacNew, EvalTestDataLoad.MAINT_USER_ID);
// check save worked
List l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
Assert.assertTrue(l.contains(eacNew));
// test adding context to active eval
EvalAssignContext eacActive = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT2,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationActive);
assigns.saveAssignContext(eacActive, EvalTestDataLoad.MAINT_USER_ID);
// check save worked
l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationActive.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
Assert.assertTrue(l.contains(eacActive));
// test modify safe part while active
EvalAssignContext testEac1 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign1.getId() );
testEac1.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac1, EvalTestDataLoad.MAINT_USER_ID);
// test modify safe part while closed
EvalAssignContext testEac2 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign4.getId() );
testEac2.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac2, EvalTestDataLoad.MAINT_USER_ID);
// test admin can modify un-owned context
EvalAssignContext testEac3 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign6.getId() );
testEac3.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac3, EvalTestDataLoad.ADMIN_USER_ID);
// test cannot add duplicate context to in-queue eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot add duplicate context to active eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationActive),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test user without perm cannot add context to eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew),
EvalTestDataLoad.USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot add context to closed eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationViewable),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot modify non-owned context
try {
etdl.assign7.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(etdl.assign7, EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// TODO - these tests cannot pass right now because of hibernate screwing us -AZ
// // test modify context while new eval
// try {
// EvalAssignContext testEac4 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign6.getId() );
// testEac4.setContext( EvalTestDataLoad.CONTEXT3 );
// assigns.saveAssignContext(testEac4, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
//
// // test modify context while active eval
// try {
// EvalAssignContext testEac5 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign1.getId() );
// testEac5.setContext( EvalTestDataLoad.CONTEXT2 );
// assigns.saveAssignContext(testEac5, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
//
// // test modify context while closed eval
// try {
// EvalAssignContext testEac6 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign4.getId() );
// testEac6.setContext( EvalTestDataLoad.CONTEXT1 );
// assigns.saveAssignContext(testEac6, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
// TODO - test that evaluation cannot be changed
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#deleteAssignContext(java.lang.Long, java.lang.String)}.
*/
public void testDeleteAssignContext() {
// save some ACs to test removing
EvalAssignContext eac1 = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
EvalAssignContext eac2 = new EvalAssignContext(new Date(),
EvalTestDataLoad.ADMIN_USER_ID, EvalTestDataLoad.CONTEXT2,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
evaluationDao.save(eac1);
evaluationDao.save(eac2);
// check save worked
List l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
Assert.assertTrue(l.contains(eac1));
Assert.assertTrue(l.contains(eac2));
// test can remove contexts from new Evaluation
Long eacId = eac1.getId();
assigns.deleteAssignContext( eacId, EvalTestDataLoad.MAINT_USER_ID );
assigns.deleteAssignContext( etdl.assign6.getId(), EvalTestDataLoad.MAINT_USER_ID );
// check save worked
l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
Assert.assertTrue(! l.contains(eac1));
// test cannot remove context from active eval
try {
assigns.deleteAssignContext( etdl.assign1.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context from closed eval
try {
assigns.deleteAssignContext( etdl.assign4.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context without permission
try {
assigns.deleteAssignContext( eac2.getId(),
EvalTestDataLoad.USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context without ownership
try {
assigns.deleteAssignContext( etdl.assign7.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test remove invalid eac
try {
assigns.deleteAssignContext( EvalTestDataLoad.INVALID_LONG_ID,
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#getAssignContextsByEvalId(java.lang.Long)}.
*/
public void testGetAssignContextsByEvalId() {
List l = null;
List ids = null;
// test fetch ACs from closed
l = assigns.getAssignContextsByEvalId( etdl.evaluationClosed.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
ids = EvalTestDataLoad.makeIdList(l);
Assert.assertTrue(ids.contains( etdl.assign3.getId() ));
Assert.assertTrue(ids.contains( etdl.assign4.getId() ));
// test fetch ACs from active
l = assigns.getAssignContextsByEvalId( etdl.evaluationActive.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
ids = EvalTestDataLoad.makeIdList(l);
Assert.assertTrue(ids.contains( etdl.assign1.getId() ));
// test fetch ACs from new
l = assigns.getAssignContextsByEvalId( etdl.evaluationNew.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(0, l.size());
// test fetch from invalid id
try {
l = assigns.getAssignContextsByEvalId( EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#canCreateAssignEval(java.lang.String, java.lang.Long)}.
*/
public void testCanCreateAssignEval() {
// test can create an AC in new
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationNew.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationNew.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationNewAdmin.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationActive.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationActive.getId()) );
// test cannot create AC in closed evals
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationClosed.getId()) );
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationViewable.getId()) );
// test cannot create AC without perms
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.USER_ID, etdl.evaluationNew.getId()) );
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationNewAdmin.getId()) );
// test invalid evaluation id
try {
assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#canDeleteAssignContext(java.lang.String, java.lang.Long)}.
*/
public void testCanDeleteAssignContext() {
// test can remove an AC in new eval
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign6.getId()) );
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign6.getId()) );
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign7.getId()) );
// test cannot remove AC from running evals
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign1.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign4.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign3.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign5.getId()) );
// test cannot remove without permission
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.USER_ID, etdl.assign6.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign7.getId()) );
// test invalid evaluation id
try {
assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
}
|
impl/logic/src/test/org/sakaiproject/evaluation/logic/test/EvalAssignsLogicImplTest.java
|
/******************************************************************************
* EvalAssignsLogicImplTest.java - created by aaronz@vt.edu on Dec 28, 2006
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Contributors:
* Aaron Zeckoski (aaronz@vt.edu) - primary
*
*****************************************************************************/
package org.sakaiproject.evaluation.logic.test;
import java.util.Date;
import java.util.List;
import junit.framework.Assert;
import org.sakaiproject.evaluation.dao.EvaluationDao;
import org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl;
import org.sakaiproject.evaluation.logic.test.stubs.EvalExternalLogicStub;
import org.sakaiproject.evaluation.model.EvalAssignContext;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.EvalScale;
import org.sakaiproject.evaluation.test.EvalTestDataLoad;
import org.sakaiproject.evaluation.test.PreloadTestData;
import org.springframework.test.AbstractTransactionalSpringContextTests;
/**
* Test class for EvalAssignsLogicImpl
*
* @author Aaron Zeckoski (aaronz@vt.edu)
*/
public class EvalAssignsLogicImplTest extends AbstractTransactionalSpringContextTests {
protected EvalAssignsLogicImpl assigns;
private EvaluationDao evaluationDao;
private EvalTestDataLoad etdl;
protected String[] getConfigLocations() {
// point to the needed spring config files, must be on the classpath
// (add component/src/webapp/WEB-INF to the build path in Eclipse),
// they also need to be referenced in the project.xml file
return new String[] {"hibernate-test.xml", "spring-hibernate.xml"};
}
// run this before each test starts
protected void onSetUpBeforeTransaction() throws Exception {
// load the spring created dao class bean from the Spring Application Context
evaluationDao = (EvaluationDao) applicationContext.getBean("org.sakaiproject.evaluation.dao.EvaluationDao");
if (evaluationDao == null) {
throw new NullPointerException("EvaluationDao could not be retrieved from spring context");
}
// check the preloaded data
Assert.assertTrue("Error preloading data", evaluationDao.countAll(EvalScale.class) > 0);
// check the preloaded test data
Assert.assertTrue("Error preloading test data", evaluationDao.countAll(EvalEvaluation.class) > 0);
PreloadTestData ptd = (PreloadTestData) applicationContext.getBean("org.sakaiproject.evaluation.test.PreloadTestData");
if (ptd == null) {
throw new NullPointerException("PreloadTestData could not be retrieved from spring context");
}
// get test objects
etdl = ptd.getEtdl();
// load up any other needed spring beans
// setup the mock objects if needed
// create and setup the object to be tested
assigns = new EvalAssignsLogicImpl();
assigns.setDao(evaluationDao);
assigns.setExternalLogic( new EvalExternalLogicStub() );
}
// run this before each test starts and as part of the transaction
protected void onSetUpInTransaction() {
// preload additional data if desired
}
/**
* ADD unit tests below here, use testMethod as the name of the unit test,
* Note that if a method is overloaded you should include the arguments in the
* test name like so: testMethodClassInt (for method(Class, int);
*/
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#saveAssignContext(org.sakaiproject.evaluation.model.EvalAssignContext, java.lang.String)}.
*/
public void testSaveAssignContext() {
// test adding context to inqueue eval
EvalAssignContext eacNew = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
assigns.saveAssignContext(eacNew, EvalTestDataLoad.MAINT_USER_ID);
// check save worked
List l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
Assert.assertTrue(l.contains(eacNew));
// test adding context to active eval
EvalAssignContext eacActive = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT2,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationActive);
assigns.saveAssignContext(eacActive, EvalTestDataLoad.MAINT_USER_ID);
// check save worked
l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationActive.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
Assert.assertTrue(l.contains(eacActive));
// test modify safe part while active
EvalAssignContext testEac1 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign1.getId() );
testEac1.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac1, EvalTestDataLoad.MAINT_USER_ID);
// test modify safe part while closed
EvalAssignContext testEac2 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign4.getId() );
testEac2.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac2, EvalTestDataLoad.MAINT_USER_ID);
// test admin can modify un-owned context
EvalAssignContext testEac3 = (EvalAssignContext) evaluationDao.
findById( EvalAssignContext.class, etdl.assign6.getId() );
testEac3.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(testEac3, EvalTestDataLoad.ADMIN_USER_ID);
// test cannot add duplicate context to in-queue eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot add duplicate context to active eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationActive),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test user without perm cannot add context to eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew),
EvalTestDataLoad.USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot add context to closed eval
try {
assigns.saveAssignContext( new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationViewable),
EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot modify non-owned context
try {
etdl.assign7.setStudentsViewResults( Boolean.TRUE );
assigns.saveAssignContext(etdl.assign7, EvalTestDataLoad.MAINT_USER_ID);
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// TODO - these tests cannot pass right now because of hibernate screwing us -AZ
// // test modify context while new eval
// try {
// EvalAssignContext testEac4 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign6.getId() );
// testEac4.setContext( EvalTestDataLoad.CONTEXT3 );
// assigns.saveAssignContext(testEac4, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
//
// // test modify context while active eval
// try {
// EvalAssignContext testEac5 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign1.getId() );
// testEac5.setContext( EvalTestDataLoad.CONTEXT2 );
// assigns.saveAssignContext(testEac5, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
//
// // test modify context while closed eval
// try {
// EvalAssignContext testEac6 = (EvalAssignContext) evaluationDao.
// findById( EvalAssignContext.class, etdl.assign4.getId() );
// testEac6.setContext( EvalTestDataLoad.CONTEXT1 );
// assigns.saveAssignContext(testEac6, EvalTestDataLoad.MAINT_USER_ID);
// Assert.fail("Should have thrown exception");
// } catch (RuntimeException e) {
// Assert.assertNotNull(e);
// }
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#deleteAssignContext(java.lang.Long, java.lang.String)}.
*/
public void testDeleteAssignContext() {
// save some ACs to test removing
EvalAssignContext eac1 = new EvalAssignContext(new Date(),
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.CONTEXT1,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
EvalAssignContext eac2 = new EvalAssignContext(new Date(),
EvalTestDataLoad.ADMIN_USER_ID, EvalTestDataLoad.CONTEXT2,
Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,
etdl.evaluationNew);
evaluationDao.save(eac1);
evaluationDao.save(eac2);
// check save worked
List l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
Assert.assertTrue(l.contains(eac1));
Assert.assertTrue(l.contains(eac2));
// test can remove contexts from new Evaluation
Long eacId = eac1.getId();
assigns.deleteAssignContext( eacId, EvalTestDataLoad.MAINT_USER_ID );
assigns.deleteAssignContext( etdl.assign6.getId(), EvalTestDataLoad.MAINT_USER_ID );
// check save worked
l = evaluationDao.findByProperties(EvalAssignContext.class,
new String[] {"evaluation.id"}, new Object[] {etdl.evaluationNew.getId()});
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
Assert.assertTrue(! l.contains(eac1));
// test cannot remove context from active eval
try {
assigns.deleteAssignContext( etdl.assign1.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context from closed eval
try {
assigns.deleteAssignContext( etdl.assign4.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context without permission
try {
assigns.deleteAssignContext( eac2.getId(),
EvalTestDataLoad.USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test cannot remove context without ownership
try {
assigns.deleteAssignContext( etdl.assign7.getId(),
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
// test remove invalid eac
try {
assigns.deleteAssignContext( EvalTestDataLoad.INVALID_LONG_ID,
EvalTestDataLoad.MAINT_USER_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#getAssignContextsByEvalId(java.lang.Long)}.
*/
public void testGetAssignContextsByEvalId() {
List l = null;
List ids = null;
// test fetch ACs from closed
l = assigns.getAssignContextsByEvalId( etdl.evaluationClosed.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(2, l.size());
ids = EvalTestDataLoad.makeIdList(l);
Assert.assertTrue(ids.contains( etdl.assign3.getId() ));
Assert.assertTrue(ids.contains( etdl.assign4.getId() ));
// test fetch ACs from active
l = assigns.getAssignContextsByEvalId( etdl.evaluationActive.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(1, l.size());
ids = EvalTestDataLoad.makeIdList(l);
Assert.assertTrue(ids.contains( etdl.assign1.getId() ));
// test fetch ACs from new
l = assigns.getAssignContextsByEvalId( etdl.evaluationNew.getId() );
Assert.assertNotNull(l);
Assert.assertEquals(0, l.size());
// test fetch from invalid id
try {
l = assigns.getAssignContextsByEvalId( EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#canCreateAssignEval(java.lang.String, java.lang.Long)}.
*/
public void testCanCreateAssignEval() {
// test can create an AC in new
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationNew.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationNew.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationNewAdmin.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationActive.getId()) );
Assert.assertTrue( assigns.canCreateAssignEval(
EvalTestDataLoad.ADMIN_USER_ID, etdl.evaluationActive.getId()) );
// test cannot create AC in closed evals
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationClosed.getId()) );
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationViewable.getId()) );
// test cannot create AC without perms
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.USER_ID, etdl.evaluationNew.getId()) );
Assert.assertFalse( assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, etdl.evaluationNewAdmin.getId()) );
// test invalid evaluation id
try {
assigns.canCreateAssignEval(
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
/**
* Test method for {@link org.sakaiproject.evaluation.logic.impl.EvalAssignsLogicImpl#canDeleteAssignContext(java.lang.String, java.lang.Long)}.
*/
public void testCanDeleteAssignContext() {
// test can remove an AC in new eval
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign6.getId()) );
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign6.getId()) );
Assert.assertTrue( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign7.getId()) );
// test cannot remove AC from running evals
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign1.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign4.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign3.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.ADMIN_USER_ID, etdl.assign5.getId()) );
// test cannot remove without permission
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.USER_ID, etdl.assign6.getId()) );
Assert.assertFalse( assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, etdl.assign7.getId()) );
// test invalid evaluation id
try {
assigns.canDeleteAssignContext(
EvalTestDataLoad.MAINT_USER_ID, EvalTestDataLoad.INVALID_LONG_ID );
Assert.fail("Should have thrown exception");
} catch (RuntimeException e) {
Assert.assertNotNull(e);
}
}
}
|
Minor update to clarify changeable fields
git-svn-id: 6eed24e287f84bf0ab23ca377a3e397011128a6f@3335 fdecad78-55fc-0310-b1b2-d7d25cf747c9
|
impl/logic/src/test/org/sakaiproject/evaluation/logic/test/EvalAssignsLogicImplTest.java
|
Minor update to clarify changeable fields
|
|
Java
|
apache-2.0
|
8c7776ea3579631b2a0218f82f3315e307080e68
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.json.codeinsight;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.json.JsonBundle;
import com.intellij.json.JsonDialectUtil;
import com.intellij.json.JsonElementTypes;
import com.intellij.json.JsonLanguage;
import com.intellij.json.psi.*;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* Compliance checks include
* <ul>
* <li>Usage of line and block commentaries</li>
* <li>Usage of single quoted strings</li>
* <li>Usage of identifiers (unqouted words)</li>
* <li>Not double quoted string literal is used as property key</li>
* <li>Multiple top-level values</li>
* </ul>
*
* @author Mikhail Golubev
*/
public class JsonStandardComplianceInspection extends LocalInspectionTool {
public boolean myWarnAboutComments = true;
public boolean myWarnAboutNanInfinity = true;
public boolean myWarnAboutTrailingCommas = true;
public boolean myWarnAboutMultipleTopLevelValues = true;
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.ERROR;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!JsonDialectUtil.isStandardJson(holder.getFile())) return PsiElementVisitor.EMPTY_VISITOR;
return new StandardJsonValidatingElementVisitor(holder);
}
@Nullable
private static PsiElement findTrailingComma(@NotNull JsonContainer container, @NotNull IElementType ending) {
final PsiElement lastChild = container.getLastChild();
if (lastChild.getNode().getElementType() != ending) {
return null;
}
final PsiElement beforeEnding = PsiTreeUtil.skipWhitespacesAndCommentsBackward(lastChild);
if (beforeEnding != null && beforeEnding.getNode().getElementType() == JsonElementTypes.COMMA) {
return beforeEnding;
}
return null;
}
@Override
public JComponent createOptionsPanel() {
final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this);
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.comments"), "myWarnAboutComments");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.multiple.top.level.values"), "myWarnAboutMultipleTopLevelValues");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.trailing.comma"), "myWarnAboutTrailingCommas");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.nan.infinity"), "myWarnAboutNanInfinity");
return optionsPanel;
}
private static class AddDoubleQuotesFix implements LocalQuickFix {
@NotNull
@Override
public String getFamilyName() {
return JsonBundle.message("quickfix.add.double.quotes.desc");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
final String rawText = element.getText();
if (element instanceof JsonLiteral || element instanceof JsonReferenceExpression) {
String content = JsonPsiUtil.stripQuotes(rawText);
if (element instanceof JsonStringLiteral && rawText.startsWith("'")) {
content = escapeSingleQuotedStringContent(content);
}
final PsiElement replacement = new JsonElementGenerator(project).createValue("\"" + content + "\"");
CodeStyleManager.getInstance(project).performActionWithFormatterDisabled((Runnable)() -> element.replace(replacement));
}
else {
Logger.getInstance(JsonStandardComplianceInspection.class)
.error("Quick fix was applied to unexpected element", rawText, element.getParent().getText());
}
}
@NotNull
private static String escapeSingleQuotedStringContent(@NotNull String content) {
final StringBuilder result = new StringBuilder();
boolean nextCharEscaped = false;
for (int i = 0; i < content.length(); i++) {
final char c = content.charAt(i);
if ((nextCharEscaped && c != '\'') || (!nextCharEscaped && c == '"')) {
result.append('\\');
}
if (c != '\\' || nextCharEscaped) {
result.append(c);
nextCharEscaped = false;
}
else {
nextCharEscaped = true;
}
}
if (nextCharEscaped) {
result.append('\\');
}
return result.toString();
}
}
protected class StandardJsonValidatingElementVisitor extends JsonElementVisitor {
private final ProblemsHolder myHolder;
private final static String MISSING_VALUE = "missingValue";
public StandardJsonValidatingElementVisitor(ProblemsHolder holder) {myHolder = holder;}
protected boolean allowComments() { return false; }
protected boolean allowSingleQuotes() { return false; }
protected boolean allowIdentifierPropertyNames() { return false; }
protected boolean allowTrailingCommas() { return false; }
protected boolean isValidPropertyName(@NotNull PsiElement literal) {
return literal instanceof JsonLiteral && JsonPsiUtil.getElementTextWithoutHostEscaping(literal).startsWith("\"");
}
@Override
public void visitComment(@NotNull PsiComment comment) {
if (!allowComments() && myWarnAboutComments) {
if (JsonStandardComplianceProvider.shouldWarnAboutComment(comment) &&
comment.getContainingFile().getLanguage() instanceof JsonLanguage) {
myHolder.registerProblem(comment, JsonBundle.message("inspection.compliance.msg.comments"));
}
}
}
@Override
public void visitStringLiteral(@NotNull JsonStringLiteral stringLiteral) {
if (!allowSingleQuotes() && JsonPsiUtil.getElementTextWithoutHostEscaping(stringLiteral).startsWith("'")) {
myHolder.registerProblem(stringLiteral, JsonBundle.message("inspection.compliance.msg.single.quoted.strings"),
new AddDoubleQuotesFix());
}
// May be illegal property key as well
super.visitStringLiteral(stringLiteral);
}
@Override
public void visitLiteral(@NotNull JsonLiteral literal) {
if (JsonPsiUtil.isPropertyKey(literal) && !isValidPropertyName(literal)) {
myHolder.registerProblem(literal, JsonBundle.message("inspection.compliance.msg.illegal.property.key"), new AddDoubleQuotesFix());
}
// for standard JSON, the inspection for NaN, Infinity and -Infinity is now configurable
if (!allowNanInfinity() && literal instanceof JsonNumberLiteral && myWarnAboutNanInfinity) {
final String text = JsonPsiUtil.getElementTextWithoutHostEscaping(literal);
if (StandardJsonLiteralChecker.INF.equals(text) ||
StandardJsonLiteralChecker.MINUS_INF.equals(text) ||
StandardJsonLiteralChecker.NAN.equals(text)) {
myHolder.registerProblem(literal, JsonBundle.message("syntax.error.illegal.floating.point.literal"));
}
}
super.visitLiteral(literal);
}
protected boolean allowNanInfinity() {
return false;
}
@Override
public void visitReferenceExpression(@NotNull JsonReferenceExpression reference) {
if (!allowIdentifierPropertyNames() || !JsonPsiUtil.isPropertyKey(reference) || !isValidPropertyName(reference)) {
if (!MISSING_VALUE.equals(reference.getText()) || !InjectedLanguageManager.getInstance(myHolder.getProject()).isInjectedFragment(myHolder.getFile())) {
myHolder.registerProblem(reference, JsonBundle.message("inspection.compliance.msg.bad.token"), new AddDoubleQuotesFix());
}
}
// May be illegal property key as well
super.visitReferenceExpression(reference);
}
@Override
public void visitArray(@NotNull JsonArray array) {
if (myWarnAboutTrailingCommas && !allowTrailingCommas() &&
JsonStandardComplianceProvider.shouldWarnAboutTrailingComma(array)) {
final PsiElement trailingComma = findTrailingComma(array, JsonElementTypes.R_BRACKET);
if (trailingComma != null) {
myHolder.registerProblem(trailingComma, JsonBundle.message("inspection.compliance.msg.trailing.comma"));
}
}
super.visitArray(array);
}
@Override
public void visitObject(@NotNull JsonObject object) {
if (myWarnAboutTrailingCommas && !allowTrailingCommas() &&
JsonStandardComplianceProvider.shouldWarnAboutTrailingComma(object)) {
final PsiElement trailingComma = findTrailingComma(object, JsonElementTypes.R_CURLY);
if (trailingComma != null) {
myHolder.registerProblem(trailingComma, JsonBundle.message("inspection.compliance.msg.trailing.comma"));
}
}
super.visitObject(object);
}
@Override
public void visitValue(@NotNull JsonValue value) {
if (value.getContainingFile() instanceof JsonFile) {
final JsonFile jsonFile = (JsonFile)value.getContainingFile();
if (myWarnAboutMultipleTopLevelValues && value.getParent() == jsonFile && value != jsonFile.getTopLevelValue()) {
myHolder.registerProblem(value, JsonBundle.message("inspection.compliance.msg.multiple.top.level.values"));
}
}
}
}
}
|
json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.json.codeinsight;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.json.JsonBundle;
import com.intellij.json.JsonDialectUtil;
import com.intellij.json.JsonElementTypes;
import com.intellij.json.JsonLanguage;
import com.intellij.json.psi.*;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* Compliance checks include
* <ul>
* <li>Usage of line and block commentaries</li>
* <li>Usage of single quoted strings</li>
* <li>Usage of identifiers (unqouted words)</li>
* <li>Not double quoted string literal is used as property key</li>
* <li>Multiple top-level values</li>
* </ul>
*
* @author Mikhail Golubev
*/
public class JsonStandardComplianceInspection extends LocalInspectionTool {
private static final Logger LOG = Logger.getInstance(JsonStandardComplianceInspection.class);
public boolean myWarnAboutComments = true;
public boolean myWarnAboutNanInfinity = true;
public boolean myWarnAboutTrailingCommas = true;
public boolean myWarnAboutMultipleTopLevelValues = true;
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.ERROR;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!JsonDialectUtil.isStandardJson(holder.getFile())) return PsiElementVisitor.EMPTY_VISITOR;
return new StandardJsonValidatingElementVisitor(holder);
}
@Nullable
private static PsiElement findTrailingComma(@NotNull JsonContainer container, @NotNull IElementType ending) {
final PsiElement lastChild = container.getLastChild();
if (lastChild.getNode().getElementType() != ending) {
return null;
}
final PsiElement beforeEnding = PsiTreeUtil.skipWhitespacesAndCommentsBackward(lastChild);
if (beforeEnding != null && beforeEnding.getNode().getElementType() == JsonElementTypes.COMMA) {
return beforeEnding;
}
return null;
}
@Override
public JComponent createOptionsPanel() {
final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this);
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.comments"), "myWarnAboutComments");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.multiple.top.level.values"), "myWarnAboutMultipleTopLevelValues");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.trailing.comma"), "myWarnAboutTrailingCommas");
optionsPanel.addCheckbox(JsonBundle.message("inspection.compliance.option.nan.infinity"), "myWarnAboutNanInfinity");
return optionsPanel;
}
private static class AddDoubleQuotesFix implements LocalQuickFix {
@NotNull
@Override
public String getFamilyName() {
return JsonBundle.message("quickfix.add.double.quotes.desc");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
final String rawText = element.getText();
if (element instanceof JsonLiteral || element instanceof JsonReferenceExpression) {
String content = JsonPsiUtil.stripQuotes(rawText);
if (element instanceof JsonStringLiteral && rawText.startsWith("'")) {
content = escapeSingleQuotedStringContent(content);
}
final PsiElement replacement = new JsonElementGenerator(project).createValue("\"" + content + "\"");
CodeStyleManager.getInstance(project).performActionWithFormatterDisabled((Runnable)() -> element.replace(replacement));
}
else {
LOG.error("Quick fix was applied to unexpected element", rawText, element.getParent().getText());
}
}
@NotNull
private static String escapeSingleQuotedStringContent(@NotNull String content) {
final StringBuilder result = new StringBuilder();
boolean nextCharEscaped = false;
for (int i = 0; i < content.length(); i++) {
final char c = content.charAt(i);
if ((nextCharEscaped && c != '\'') || (!nextCharEscaped && c == '"')) {
result.append('\\');
}
if (c != '\\' || nextCharEscaped) {
result.append(c);
nextCharEscaped = false;
}
else {
nextCharEscaped = true;
}
}
if (nextCharEscaped) {
result.append('\\');
}
return result.toString();
}
}
protected class StandardJsonValidatingElementVisitor extends JsonElementVisitor {
private final ProblemsHolder myHolder;
private final static String MISSING_VALUE = "missingValue";
public StandardJsonValidatingElementVisitor(ProblemsHolder holder) {myHolder = holder;}
protected boolean allowComments() { return false; }
protected boolean allowSingleQuotes() { return false; }
protected boolean allowIdentifierPropertyNames() { return false; }
protected boolean allowTrailingCommas() { return false; }
protected boolean isValidPropertyName(@NotNull PsiElement literal) {
return literal instanceof JsonLiteral && JsonPsiUtil.getElementTextWithoutHostEscaping(literal).startsWith("\"");
}
@Override
public void visitComment(@NotNull PsiComment comment) {
if (!allowComments() && myWarnAboutComments) {
if (JsonStandardComplianceProvider.shouldWarnAboutComment(comment) &&
comment.getContainingFile().getLanguage() instanceof JsonLanguage) {
myHolder.registerProblem(comment, JsonBundle.message("inspection.compliance.msg.comments"));
}
}
}
@Override
public void visitStringLiteral(@NotNull JsonStringLiteral stringLiteral) {
if (!allowSingleQuotes() && JsonPsiUtil.getElementTextWithoutHostEscaping(stringLiteral).startsWith("'")) {
myHolder.registerProblem(stringLiteral, JsonBundle.message("inspection.compliance.msg.single.quoted.strings"),
new AddDoubleQuotesFix());
}
// May be illegal property key as well
super.visitStringLiteral(stringLiteral);
}
@Override
public void visitLiteral(@NotNull JsonLiteral literal) {
if (JsonPsiUtil.isPropertyKey(literal) && !isValidPropertyName(literal)) {
myHolder.registerProblem(literal, JsonBundle.message("inspection.compliance.msg.illegal.property.key"), new AddDoubleQuotesFix());
}
// for standard JSON, the inspection for NaN, Infinity and -Infinity is now configurable
if (!allowNanInfinity() && literal instanceof JsonNumberLiteral && myWarnAboutNanInfinity) {
final String text = JsonPsiUtil.getElementTextWithoutHostEscaping(literal);
if (StandardJsonLiteralChecker.INF.equals(text) ||
StandardJsonLiteralChecker.MINUS_INF.equals(text) ||
StandardJsonLiteralChecker.NAN.equals(text)) {
myHolder.registerProblem(literal, JsonBundle.message("syntax.error.illegal.floating.point.literal"));
}
}
super.visitLiteral(literal);
}
protected boolean allowNanInfinity() {
return false;
}
@Override
public void visitReferenceExpression(@NotNull JsonReferenceExpression reference) {
if (!allowIdentifierPropertyNames() || !JsonPsiUtil.isPropertyKey(reference) || !isValidPropertyName(reference)) {
if (!MISSING_VALUE.equals(reference.getText()) || !InjectedLanguageManager.getInstance(myHolder.getProject()).isInjectedFragment(myHolder.getFile())) {
myHolder.registerProblem(reference, JsonBundle.message("inspection.compliance.msg.bad.token"), new AddDoubleQuotesFix());
}
}
// May be illegal property key as well
super.visitReferenceExpression(reference);
}
@Override
public void visitArray(@NotNull JsonArray array) {
if (myWarnAboutTrailingCommas && !allowTrailingCommas() &&
JsonStandardComplianceProvider.shouldWarnAboutTrailingComma(array)) {
final PsiElement trailingComma = findTrailingComma(array, JsonElementTypes.R_BRACKET);
if (trailingComma != null) {
myHolder.registerProblem(trailingComma, JsonBundle.message("inspection.compliance.msg.trailing.comma"));
}
}
super.visitArray(array);
}
@Override
public void visitObject(@NotNull JsonObject object) {
if (myWarnAboutTrailingCommas && !allowTrailingCommas() &&
JsonStandardComplianceProvider.shouldWarnAboutTrailingComma(object)) {
final PsiElement trailingComma = findTrailingComma(object, JsonElementTypes.R_CURLY);
if (trailingComma != null) {
myHolder.registerProblem(trailingComma, JsonBundle.message("inspection.compliance.msg.trailing.comma"));
}
}
super.visitObject(object);
}
@Override
public void visitValue(@NotNull JsonValue value) {
if (value.getContainingFile() instanceof JsonFile) {
final JsonFile jsonFile = (JsonFile)value.getContainingFile();
if (myWarnAboutMultipleTopLevelValues && value.getParent() == jsonFile && value != jsonFile.getTopLevelValue()) {
myHolder.registerProblem(value, JsonBundle.message("inspection.compliance.msg.multiple.top.level.values"));
}
}
}
}
}
|
JSON: inline single usage of LOG in JsonStandardComplianceInspection
GitOrigin-RevId: 82063ea3e1eea156854fad852e6a1f1b3675d618
|
json/src/com/intellij/json/codeinsight/JsonStandardComplianceInspection.java
|
JSON: inline single usage of LOG in JsonStandardComplianceInspection
|
|
Java
|
apache-2.0
|
2bbada266dca9b94d904df7f0b7f0204fedfaf6a
| 0
|
Neoskai/greycat,datathings/greycat,Neoskai/greycat,datathings/greycat,Neoskai/greycat,electricalwind/greycat,electricalwind/greycat,datathings/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat,electricalwind/greycat,datathings/greycat,Neoskai/greycat,datathings/greycat,Neoskai/greycat,electricalwind/greycat,datathings/greycat
|
/**
* Copyright 2017 The GreyCat Authors. All rights reserved.
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 greycat.generator;
import greycat.Graph;
import greycat.language.*;
import greycat.language.Class;
import greycat.plugin.NodeFactory;
import greycat.plugin.Plugin;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.Visibility;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.JavaSource;
import org.jboss.forge.roaster.model.source.MethodSource;
class PluginClassGenerator {
static JavaSource generate(final String packageName, final String pluginName, final Model model) {
final JavaClassSource pluginClass = Roaster.create(JavaClassSource.class);
pluginClass.addImport(NodeFactory.class);
pluginClass.addImport(Graph.class);
pluginClass.setPackage(packageName);
pluginClass.setName(pluginName);
pluginClass.addInterface(Plugin.class);
pluginClass.addMethod().setReturnTypeVoid()
.setVisibility(Visibility.PUBLIC)
.setName("stop")
.setBody("")
.addAnnotation(Override.class);
StringBuilder startBodyBuilder = new StringBuilder();
for (Class classType : model.classes()) {
startBodyBuilder.append("\t\tgraph.nodeRegistry()\n")
.append("\t\t\t.getOrCreateDeclaration(").append(classType.name()).append(".NODE_NAME").append(")").append("\n")
.append("\t\t\t.setFactory(new NodeFactory() {\n" +
"\t\t\t\t\t@Override\n" +
"\t\t\t\t\tpublic greycat.Node create(long world, long time, long id, Graph graph) {\n" +
"\t\t\t\t\t\treturn new ").append(classType.name()).append("(world,time,id,graph);\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t});\n\n");
}
for (CustomType customType : model.customTypes()) {
startBodyBuilder.append("graph.typeRegistry().getOrCreateDeclaration(" + customType.name() + ".TYPE_NAME" + ").setFactory(new greycat.plugin.TypeFactory() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public Object wrap(final greycat.struct.EStructArray backend) {");
startBodyBuilder.append("return new " + customType.name() + "(backend);");
startBodyBuilder.append("}");
startBodyBuilder.append("});\n\n");
}
if (model.globalIndexes().length > 0) {
startBodyBuilder.append("graph.addConnectHook(new greycat.Callback<greycat.Callback<Boolean>>() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void on(greycat.Callback<Boolean> result) {");
startBodyBuilder.append("greycat.DeferCounter dc = graph.newCounter(" + model.globalIndexes().length + ");");
for (Index idx : model.globalIndexes()) {
StringBuilder paramsBuilder = new StringBuilder();
for (AttributeRef att : idx.attributes()) {
paramsBuilder.append(idx.name() + "." + att.ref().name().toUpperCase());
paramsBuilder.append(",");
}
paramsBuilder.deleteCharAt(paramsBuilder.length() - 1);
startBodyBuilder.append("graph.declareIndex(0, " + idx.name() + ".INDEX_NAME" + ", new greycat.Callback<greycat.NodeIndex>() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void on(greycat.NodeIndex result) {");
startBodyBuilder.append("dc.count();");
startBodyBuilder.append("}");
startBodyBuilder.append("}, " + paramsBuilder.toString() + ");\n\n");
}
startBodyBuilder.append("dc.then(new greycat.plugin.Job() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void run() {");
startBodyBuilder.append("result.on(true);");
startBodyBuilder.append("}");
startBodyBuilder.append("});");
startBodyBuilder.append("}");
startBodyBuilder.append("});");
}
MethodSource<JavaClassSource> startMethod = pluginClass.addMethod();
startMethod.setReturnTypeVoid()
.setVisibility(Visibility.PUBLIC)
.addAnnotation(Override.class);
startMethod.setBody(startBodyBuilder.toString());
startMethod.setName("start");
startMethod.addParameter("Graph", "graph");
return pluginClass;
}
}
|
modeling/generator/src/main/java/greycat/generator/PluginClassGenerator.java
|
/**
* Copyright 2017 The GreyCat Authors. All rights reserved.
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 greycat.generator;
import greycat.Graph;
import greycat.language.*;
import greycat.language.Class;
import greycat.plugin.NodeFactory;
import greycat.plugin.Plugin;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.Visibility;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.JavaSource;
import org.jboss.forge.roaster.model.source.MethodSource;
class PluginClassGenerator {
static JavaSource generate(final String packageName, final String pluginName, final Model model) {
final JavaClassSource pluginClass = Roaster.create(JavaClassSource.class);
pluginClass.addImport(NodeFactory.class);
pluginClass.addImport(Graph.class);
pluginClass.setPackage(packageName);
pluginClass.setName(pluginName);
pluginClass.addInterface(Plugin.class);
pluginClass.addMethod().setReturnTypeVoid()
.setVisibility(Visibility.PUBLIC)
.setName("stop")
.setBody("")
.addAnnotation(Override.class);
StringBuilder startBodyBuilder = new StringBuilder();
for (Class classType : model.classes()) {
startBodyBuilder.append("\t\tgraph.nodeRegistry()\n")
.append("\t\t\t.getOrCreateDeclaration(").append(classType.name()).append(".NODE_NAME").append(")").append("\n")
.append("\t\t\t.setFactory(new NodeFactory() {\n" +
"\t\t\t\t\t@Override\n" +
"\t\t\t\t\tpublic greycat.Node create(long world, long time, long id, Graph graph) {\n" +
"\t\t\t\t\t\treturn new ").append(classType.name()).append("(world,time,id,graph);\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t});\n\n");
}
for (CustomType customType : model.customTypes()) {
startBodyBuilder.append("graph.typeRegistry().getOrCreateDeclaration(" + customType.name() + ".TYPE_NAME" + ").setFactory(new greycat.plugin.TypeFactory() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public Object wrap(final greycat.struct.EStructArray backend) {");
startBodyBuilder.append("return new " + customType.name() + "(backend);");
startBodyBuilder.append("}");
startBodyBuilder.append("});\n\n");
}
startBodyBuilder.append("graph.addConnectHook(new greycat.Callback<greycat.Callback<Boolean>>() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void on(greycat.Callback<Boolean> result) {");
if (model.globalIndexes().length > 0) {
startBodyBuilder.append("greycat.DeferCounter dc = graph.newCounter(" + model.globalIndexes().length + ");");
for (Index idx : model.globalIndexes()) {
StringBuilder paramsBuilder = new StringBuilder();
for (AttributeRef att : idx.attributes()) {
paramsBuilder.append(idx.name() + "." + att.ref().name().toUpperCase());
paramsBuilder.append(",");
}
paramsBuilder.deleteCharAt(paramsBuilder.length() - 1);
startBodyBuilder.append("graph.declareIndex(0, " + idx.name() + ".INDEX_NAME" + ", new greycat.Callback<greycat.NodeIndex>() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void on(greycat.NodeIndex result) {");
startBodyBuilder.append("dc.count();");
startBodyBuilder.append("}");
startBodyBuilder.append("}, " + paramsBuilder.toString() + ");\n\n");
}
startBodyBuilder.append("dc.then(new greycat.plugin.Job() {");
startBodyBuilder.append("@Override\n");
startBodyBuilder.append("public void run() {");
startBodyBuilder.append("result.on(true);");
startBodyBuilder.append("}");
startBodyBuilder.append("});");
}
startBodyBuilder.append("}");
startBodyBuilder.append("});");
MethodSource<JavaClassSource> startMethod = pluginClass.addMethod();
startMethod.setReturnTypeVoid()
.setVisibility(Visibility.PUBLIC)
.addAnnotation(Override.class);
startMethod.setBody(startBodyBuilder.toString());
startMethod.setName("start");
startMethod.addParameter("Graph", "graph");
return pluginClass;
}
}
|
* modeling env bugfix: connectionHook is only generated if not empty
|
modeling/generator/src/main/java/greycat/generator/PluginClassGenerator.java
|
* modeling env bugfix: connectionHook is only generated if not empty
|
|
Java
|
apache-2.0
|
10014ed743114367c44accbe28390d3d6b4ecd11
| 0
|
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
|
/*******************************************************************************
* Copyright 2012
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.clarin.webanno.project.page;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.CHAIN_TYPE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFERENCE_RELATION_FEATURE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFERENCE_TYPE_FEATURE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.RELATION_TYPE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.SPAN_TYPE;
import static java.util.Arrays.asList;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.uima.cas.CAS;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.extensions.markup.html.form.select.Select;
import org.apache.wicket.extensions.markup.html.form.select.SelectOption;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.core.context.SecurityContextHolder;
import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService;
import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService;
import de.tudarmstadt.ukp.clarin.webanno.api.UserDao;
import de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer;
import de.tudarmstadt.ukp.clarin.webanno.model.LinkMode;
import de.tudarmstadt.ukp.clarin.webanno.model.MultiValueMode;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.model.TagSet;
import de.tudarmstadt.ukp.clarin.webanno.model.User;
import de.tudarmstadt.ukp.clarin.webanno.support.EntityModel;
import de.tudarmstadt.ukp.clarin.webanno.support.JSONUtil;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
/**
* A Panel Used to add Layers to a selected {@link Project} in the project settings page
*
*
*/
public class ProjectLayersPanel
extends Panel
{
private static final long serialVersionUID = -7870526462864489252L;
@SpringBean(name = "annotationService")
private AnnotationService annotationService;
@SpringBean(name = "documentRepository")
private RepositoryService repository;
@SpringBean(name = "userRepository")
private UserDao userRepository;
private final String FIRST = "first";
private final String NEXT = "next";
private LayerSelectionForm layerSelectionForm;
private FeatureSelectionForm featureSelectionForm;
private LayerDetailForm layerDetailForm;
private final FeatureDetailForm featureDetailForm;
private final ImportLayerForm importLayerForm;
private Select<AnnotationLayer> layerSelection;
private final IModel<Project> selectedProjectModel;
private final static List<String> PRIMITIVE_TYPES = asList(CAS.TYPE_NAME_STRING,
CAS.TYPE_NAME_INTEGER, CAS.TYPE_NAME_FLOAT, CAS.TYPE_NAME_BOOLEAN);
private List<String> spanTypes = new ArrayList<String>();
private String layerType = WebAnnoConst.SPAN_TYPE;
private List<FileUpload> uploadedFiles;
private FileUploadField fileUpload;
public ProjectLayersPanel(String id, final IModel<Project> aProjectModel)
{
super(id);
this.selectedProjectModel = aProjectModel;
layerSelectionForm = new LayerSelectionForm("layerSelectionForm");
featureSelectionForm = new FeatureSelectionForm("featureSelectionForm");
featureSelectionForm.setVisible(false);
featureSelectionForm.setOutputMarkupPlaceholderTag(true);
layerDetailForm = new LayerDetailForm("layerDetailForm");
layerDetailForm.setVisible(false);
layerDetailForm.setOutputMarkupPlaceholderTag(true);
featureDetailForm = new FeatureDetailForm("featureDetailForm");
featureDetailForm.setVisible(false);
featureDetailForm.setOutputMarkupPlaceholderTag(true);
add(layerSelectionForm);
add(featureSelectionForm);
add(layerDetailForm);
add(featureDetailForm);
importLayerForm = new ImportLayerForm("importLayerForm");
add(importLayerForm);
}
private class LayerSelectionForm
extends Form<SelectionModel>
{
private static final long serialVersionUID = -1L;
public LayerSelectionForm(String id)
{
super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel()));
add(new Button("create", new ResourceModel("label"))
{
private static final long serialVersionUID = -4482428496358679571L;
@Override
public void onSubmit()
{
if (selectedProjectModel.getObject().getId() == 0) {
error("Project not yet created. Please save project details first!");
}
else {
LayerSelectionForm.this.getModelObject().layerSelection = null;
layerDetailForm.setModelObject(new AnnotationLayer());
layerDetailForm.setVisible(true);
featureSelectionForm.setVisible(false);
featureDetailForm.setVisible(false);
}
}
});
final Map<AnnotationLayer, String> colors = new HashMap<AnnotationLayer, String>();
layerSelection = new Select<AnnotationLayer>("layerSelection");
ListView<AnnotationLayer> layers = new ListView<AnnotationLayer>("layers",
new LoadableDetachableModel<List<AnnotationLayer>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<AnnotationLayer> load()
{
Project project = selectedProjectModel.getObject();
if (project.getId() != 0) {
List<AnnotationLayer> layers = annotationService
.listAnnotationLayer(project);
AnnotationLayer tokenLayer = annotationService.getLayer(
Token.class.getName(), project);
layers.remove(tokenLayer);
for (AnnotationLayer layer : layers) {
if (layer.isBuiltIn() && layer.isEnabled()) {
colors.put(layer, "green");
}
else if (layer.isEnabled()) {
colors.put(layer, "blue");
}
else {
colors.put(layer, "red");
}
}
return layers;
}
return new ArrayList<AnnotationLayer>();
}
})
{
private static final long serialVersionUID = 8901519963052692214L;
@Override
protected void populateItem(final ListItem<AnnotationLayer> item)
{
item.add(new SelectOption<AnnotationLayer>("layer", new Model<AnnotationLayer>(
item.getModelObject()))
{
private static final long serialVersionUID = 3095089418860168215L;
@Override
public void onComponentTagBody(MarkupStream markupStream,
ComponentTag openTag)
{
replaceComponentTagBody(markupStream, openTag, item.getModelObject()
.getUiName());
}
}.add(new AttributeModifier("style", "color:"
+ colors.get(item.getModelObject()) + ";")));
}
};
add(layerSelection.add(layers));
layerSelection.setOutputMarkupId(true);
layerSelection.add(new OnChangeAjaxBehavior()
{
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
layerDetailForm.setModelObject(getModelObject().layerSelection);
layerDetailForm.setVisible(true);
LayerSelectionForm.this.setVisible(true);
featureSelectionForm.clearInput();
featureSelectionForm.setVisible(true);
layerDetailForm.setVisible(true);
featureDetailForm.setVisible(false);
layerType = getModelObject().layerSelection.getType();
aTarget.add(layerDetailForm);
aTarget.add(featureSelectionForm);
aTarget.add(featureDetailForm);
}
});
}
}
private class ImportLayerForm
extends Form<String>
{
private static final long serialVersionUID = -7777616763931128598L;
@SuppressWarnings({ "unchecked", "rawtypes" })
public ImportLayerForm(String id)
{
super(id);
add(fileUpload = new FileUploadField("content", new Model()));
add(new Button("import", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
uploadedFiles = fileUpload.getFileUploads();
Project project = selectedProjectModel.getObject();
String username = SecurityContextHolder.getContext().getAuthentication()
.getName();
User user = userRepository.get(username);
if (isEmpty(uploadedFiles)) {
error("Please choose file with layer details before uploading");
return;
}
else if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
for (FileUpload tagFile : uploadedFiles) {
InputStream tagInputStream;
try {
tagInputStream = tagFile.getInputStream();
String text = IOUtils.toString(tagInputStream, "UTF-8");
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exLayer = JSONUtil
.getJsonConverter()
.getObjectMapper()
.readValue(
text,
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer.class);
AnnotationLayer attachLayer = null;
if (exLayer.getAttachType() != null) {
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exAttachLayer = exLayer
.getAttachType();
createLayer(exAttachLayer, user, null);
attachLayer = annotationService.getLayer(exAttachLayer.getName(),
project);
}
createLayer(exLayer, user, attachLayer);
layerDetailForm.setModelObject(annotationService.getLayer(
exLayer.getName(), project));
layerDetailForm.setVisible(true);
featureSelectionForm.setVisible(true);
}
catch (IOException e) {
error("Error Importing TagSet " + ExceptionUtils.getRootCauseMessage(e));
}
}
featureDetailForm.setVisible(false);
}
private void createLayer(
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer aExLayer,
User aUser, AnnotationLayer aAttachLayer)
throws IOException
{
Project project = selectedProjectModel.getObject();
AnnotationLayer layer;
if (annotationService.existsLayer(aExLayer.getName(), aExLayer.getType(),
project)) {
layer = annotationService.getLayer(aExLayer.getName(),
selectedProjectModel.getObject());
ImportUtil.setLayer(annotationService, layer, aExLayer, project, aUser);
}
else {
layer = new AnnotationLayer();
ImportUtil.setLayer(annotationService, layer, aExLayer, project, aUser);
}
layer.setAttachType(aAttachLayer);
for (de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationFeature exfeature : aExLayer
.getFeatures()) {
de.tudarmstadt.ukp.clarin.webanno.model.export.TagSet exTagset = exfeature
.getTagSet();
TagSet tagSet = null;
if (exTagset != null
&& annotationService.existsTagSet(exTagset.getName(), project)) {
tagSet = annotationService.getTagSet(exTagset.getName(), project);
ImportUtil.createTagSet(tagSet, exTagset, project, aUser,
annotationService);
}
else if (exTagset != null) {
tagSet = new TagSet();
ImportUtil.createTagSet(tagSet, exTagset, project, aUser,
annotationService);
}
if (annotationService.existsFeature(exfeature.getName(), layer)) {
AnnotationFeature feature = annotationService.getFeature(
exfeature.getName(), layer);
feature.setTagset(tagSet);
ImportUtil.setFeature(annotationService, feature, exfeature, project,
aUser);
continue;
}
AnnotationFeature feature = new AnnotationFeature();
feature.setLayer(layer);
feature.setTagset(tagSet);
ImportUtil
.setFeature(annotationService, feature, exfeature, project, aUser);
}
}
});
}
}
public class SelectionModel
implements Serializable
{
private static final long serialVersionUID = -1L;
private AnnotationLayer layerSelection;
public AnnotationFeature feature;
}
private class LayerDetailForm
extends Form<AnnotationLayer>
{
private static final long serialVersionUID = -1L;
private Label name;
private TextField<String> uiName;
private static final String TYPE_PREFIX = "webanno.custom.";
private String layerName;
private DropDownChoice<String> layerTypes;
private DropDownChoice<AnnotationLayer> attachTypes;
private Label lockToTokenOffsetLabel;
private CheckBox lockToTokenOffset;
private Label allowStackingLabel;
private CheckBox allowStacking;
private Label crossSentenceLabel;
private CheckBox crossSentence;
private Label multipleTokensLabel;
private CheckBox multipleTokens;
private Label linkedListBehaviorLabel;
private CheckBox linkedListBehavior;
public LayerDetailForm(String id)
{
super(id, new CompoundPropertyModel<AnnotationLayer>(new EntityModel<AnnotationLayer>(
new AnnotationLayer())));
final Project project = selectedProjectModel.getObject();
add(uiName = (TextField<String>) new TextField<String>("uiName").setRequired(true));
uiName.add(new AjaxFormComponentUpdatingBehavior("onkeyup")
{
private static final long serialVersionUID = -1756244972577094229L;
@Override
protected void onUpdate(AjaxRequestTarget target)
{
String modelValue = StringUtils.capitalize(getModelObject().getUiName());
layerName = modelValue;
}
});
add(name = new Label("name")
{
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure()
{
setVisible(StringUtils.isNotBlank(LayerDetailForm.this.getModelObject()
.getName()));
};
});
add(new TextArea<String>("description").setOutputMarkupPlaceholderTag(true));
add(new CheckBox("enabled"));
add(layerTypes = (DropDownChoice<String>) new DropDownChoice<String>("type",
Arrays.asList(new String[] { SPAN_TYPE, RELATION_TYPE, CHAIN_TYPE }))
{
private static final long serialVersionUID = 1244555334843130802L;
@Override
public boolean isEnabled()
{
return LayerDetailForm.this.getModelObject().getId() == 0;
}
}.setRequired(true));
layerTypes.add(new AjaxFormComponentUpdatingBehavior("onchange")
{
private static final long serialVersionUID = 6790949494089940303L;
@Override
protected void onUpdate(AjaxRequestTarget target)
{
layerType = getModelObject().getType();
target.add(lockToTokenOffsetLabel);
target.add(lockToTokenOffset);
target.add(allowStackingLabel);
target.add(allowStacking);
target.add(crossSentenceLabel);
target.add(crossSentence);
target.add(multipleTokensLabel);
target.add(multipleTokens);
target.add(linkedListBehaviorLabel);
target.add(linkedListBehavior);
target.add(attachTypes);
}
});
attachTypes = (DropDownChoice<AnnotationLayer>) new DropDownChoice<AnnotationLayer>(
"attachType")
{
private static final long serialVersionUID = -6705445053442011120L;
{
setChoices(new LoadableDetachableModel<List<AnnotationLayer>>()
{
private static final long serialVersionUID = 1784646746122513331L;
@Override
protected List<AnnotationLayer> load()
{
List<AnnotationLayer> allLayers = annotationService
.listAnnotationLayer(project);
if (LayerDetailForm.this.getModelObject().getId() > 0) {
if (LayerDetailForm.this.getModelObject().getAttachType() == null) {
return new ArrayList<AnnotationLayer>();
}
return Arrays.asList(LayerDetailForm.this.getModelObject()
.getAttachType());
}
if (!layerType.equals(RELATION_TYPE)) {
return new ArrayList<AnnotationLayer>();
}
List<AnnotationLayer> attachTeypes = new ArrayList<AnnotationLayer>();
// remove a span layer which is already used as attach type for the
// other
List<AnnotationLayer> usedLayers = new ArrayList<AnnotationLayer>();
for (AnnotationLayer layer : allLayers) {
if (layer.getAttachType() != null) {
usedLayers.add(layer.getAttachType());
}
}
allLayers.removeAll(usedLayers);
for (AnnotationLayer layer : allLayers) {
if (layer.getType().equals(SPAN_TYPE) && !layer.isBuiltIn()) {
attachTeypes.add(layer);
}
}
return attachTeypes;
}
});
setChoiceRenderer(new ChoiceRenderer<AnnotationLayer>("uiName"));
}
@Override
protected void onConfigure()
{
setEnabled(LayerDetailForm.this.getModelObject().getId() == 0);
setNullValid(isVisible());
};
};
attachTypes.setOutputMarkupPlaceholderTag(true);
add(attachTypes);
// Behaviors of layers
add(new CheckBox("readonly"));
add(lockToTokenOffsetLabel = new Label("lockToTokenOffsetLabel",
"Lock to token offsets:")
{
private static final long serialVersionUID = -1290883833837327207L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relation layers or layers that attach to tokens
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType())
&& layer.getAttachFeature() == null);
setEnabled(!CHAIN_TYPE.equals(layer.getType()));
}
});
add(lockToTokenOffset = new CheckBox("lockToTokenOffset")
{
private static final long serialVersionUID = -4934708834659137207L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relation layers or layers that attach to tokens
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType())
&& layer.getAttachFeature() == null);
setEnabled(!CHAIN_TYPE.equals(layer.getType()));
}
});
add(allowStackingLabel = new Label("allowStackingLabel", "Allow stacking:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that have an attach feature (basically Dependency)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(allowStacking = new CheckBox("allowStacking")
{
private static final long serialVersionUID = 7800627916287273008L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(crossSentenceLabel = new Label("crossSentenceLabel",
"Allow crossing sentence boundary:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(crossSentence = new CheckBox("crossSentence")
{
private static final long serialVersionUID = -5986386642712152491L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(multipleTokensLabel = new Label("multipleTokensLabel", "Allow multiple tokens:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relations
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(multipleTokens = new CheckBox("multipleTokens")
{
private static final long serialVersionUID = 1319818165277559402L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relations
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(linkedListBehaviorLabel = new Label("linkedListBehaviorLabel",
"Behave like a linked list:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()) && CHAIN_TYPE.equals(layer.getType()));
}
});
add(linkedListBehavior = new CheckBox("linkedListBehavior")
{
private static final long serialVersionUID = 1319818165277559402L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()) && CHAIN_TYPE.equals(layer.getType()));
}
});
linkedListBehavior.add(new AjaxFormComponentUpdatingBehavior("onChange")
{
private static final long serialVersionUID = -2904306846882446294L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
featureSelectionForm.updateChoices();
aTarget.add(featureSelectionForm);
aTarget.add(featureDetailForm);
}
});
add(new Button("save", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
if (layer.isLockToTokenOffset() && layer.isMultipleTokens()) {
layer.setLockToTokenOffset(false);
}
if (layer.getId() == 0) {
layerName = layerName.replaceAll("\\W", "");
if(layerName.isEmpty() || !isAscii(layerName)){
error("Non ASCII characters can not be used as layer name!");
return;
}
if (annotationService.existsLayer(TYPE_PREFIX + layerName, layer.getType(),
project)) {
error("Only one Layer per project is allowed!");
return;
}
if (layer.getType().equals(RELATION_TYPE) && layer.getAttachType() == null) {
error("a relation layer need an attach type!");
return;
}
if ((TYPE_PREFIX + layerName).endsWith(".")) {
error("please give a proper layer name!");
return;
}
String username = SecurityContextHolder.getContext().getAuthentication()
.getName();
User user = userRepository.get(username);
layer.setProject(project);
try {
layer.setName(TYPE_PREFIX + layerName);
annotationService.createLayer(layer, user);
if (layer.getType().equals(WebAnnoConst.CHAIN_TYPE)) {
AnnotationFeature relationFeature = new AnnotationFeature();
relationFeature.setType(CAS.TYPE_NAME_STRING);
relationFeature.setName(COREFERENCE_RELATION_FEATURE);
relationFeature.setLayer(layer);
relationFeature.setEnabled(true);
relationFeature.setUiName("Reference Relation");
relationFeature.setProject(project);
annotationService.createFeature(relationFeature);
AnnotationFeature typeFeature = new AnnotationFeature();
typeFeature.setType(CAS.TYPE_NAME_STRING);
typeFeature.setName(COREFERENCE_TYPE_FEATURE);
typeFeature.setLayer(layer);
typeFeature.setEnabled(true);
typeFeature.setUiName("Reference Type");
typeFeature.setProject(project);
annotationService.createFeature(typeFeature);
}
}
catch (IOException e) {
error("unable to create Log file while creating this layer" + ":"
+ ExceptionUtils.getRootCauseMessage(e));
}
featureSelectionForm.setVisible(true);
}
}
});
add(new DownloadLink("export", new LoadableDetachableModel<File>()
{
private static final long serialVersionUID = 840863954694163375L;
@Override
protected File load()
{
File exportFile = null;
try {
exportFile = File.createTempFile("exportedLayer", ".json");
}
catch (IOException e1) {
error("Unable to create temporary File!!");
}
if (selectedProjectModel.getObject().getId() == 0) {
error("Project not yet created. Please save project details first!");
return null;
}
AnnotationLayer layer = layerDetailForm.getModelObject();
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exLayer = ImportUtil
.exportLayerDetails(null, null, layer, annotationService);
if (layer.getAttachType() != null) {
AnnotationLayer attachLayer = layer.getAttachType();
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exAttachLayer = ImportUtil
.exportLayerDetails(null, null, attachLayer, annotationService);
exLayer.setAttachType(exAttachLayer);
}
try {
JSONUtil.generateJson(exLayer, exportFile);
}
catch (IOException e) {
error("File Path not found or No permision to save the file!");
}
info("TagSets successfully exported to :" + exportFile.getAbsolutePath());
return exportFile;
}
}).setOutputMarkupId(true));
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
// layerDetailForm.setModelObject(new AnnotationLayer());
// layerSelectionForm.setModelObject(new SelectionModel());
// featureSelectionForm.setModelObject(new SelectionModel());
// featureDetailForm.setModelObject(new AnnotationFeature());
// layerDetailForm.setModelObject(null);
layerDetailForm.setVisible(false);
featureSelectionForm.setVisible(false);
featureDetailForm.setVisible(false);
}
});
}
}
public static boolean isAscii(String v)
{
CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
return asciiEncoder.canEncode(v);
}
private class FeatureDetailForm
extends Form<AnnotationFeature>
{
private static final long serialVersionUID = -1L;
DropDownChoice<TagSet> tagSet;
DropDownChoice<String> featureType;
public FeatureDetailForm(String id)
{
super(id, new CompoundPropertyModel<AnnotationFeature>(
new EntityModel<AnnotationFeature>(new AnnotationFeature())));
add(new TextField<String>("uiName").setRequired(true));
add(new TextArea<String>("description").setOutputMarkupPlaceholderTag(true));
add(new CheckBox("enabled"));
add(new CheckBox("visible"));
add(new CheckBox("remember"));
add(new CheckBox("hideUnconstraintFeature"));
spanTypes.add(CAS.TYPE_NAME_ANNOTATION);
for (AnnotationLayer spanLayer : annotationService
.listAnnotationLayer(selectedProjectModel.getObject())) {
if (spanLayer.getName().equals(Token.class.getName())) {
continue;
}
if (spanLayer.getType().equals(WebAnnoConst.SPAN_TYPE)) {
spanTypes.add(spanLayer.getName());
}
}
add(featureType = (DropDownChoice<String>) new DropDownChoice<String>("type")
{
private static final long serialVersionUID = 9029205407108101183L;
{
setRequired(true);
setNullValid(false);
setChoices(new LoadableDetachableModel<List<String>>()
{
private static final long serialVersionUID = -5732558926576750673L;
@Override
protected List<String> load()
{
if (getModelObject() != null) {
return Arrays.asList(getModelObject());
}
List<String> types = new ArrayList<String>(PRIMITIVE_TYPES);
types.addAll(spanTypes);
return types;
}
});
}
@Override
protected void onConfigure()
{
setEnabled(FeatureDetailForm.this.getModelObject().getId() == 0);
};
});
featureType.add(new AjaxFormComponentUpdatingBehavior("onChange")
{
private static final long serialVersionUID = -2904306846882446294L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
aTarget.add(tagSet);
}
});
add(tagSet = new DropDownChoice<TagSet>("tagset")
{
private static final long serialVersionUID = -6705445053442011120L;
{
setOutputMarkupPlaceholderTag(true);
setOutputMarkupId(true);
setChoiceRenderer(new ChoiceRenderer<TagSet>("name"));
setNullValid(true);
setChoices(new LoadableDetachableModel<List<TagSet>>()
{
private static final long serialVersionUID = 1784646746122513331L;
@Override
protected List<TagSet> load()
{
return annotationService.listTagSets(selectedProjectModel.getObject());
}
});
}
@Override
protected void onConfigure()
{
AnnotationFeature feature = FeatureDetailForm.this.getModelObject();
// Only display tagset choice for link features with role and string features
// Since we currently set the LinkRole only when saving, we have to rely on the
// feature type here.
setEnabled(CAS.TYPE_NAME_STRING.equals(feature.getType())
|| !PRIMITIVE_TYPES.contains(feature.getType()));
}
});
add(new Button("save", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
AnnotationFeature feature = FeatureDetailForm.this.getModelObject();
String name = feature.getUiName();
name = name.replaceAll("\\W", "");
if (layerDetailForm.getModelObject().getType().equals(RELATION_TYPE)
&& (name.equals(WebAnnoConst.FEAT_REL_SOURCE)
|| name.equals(WebAnnoConst.FEAT_REL_TARGET)
|| name.equals(FIRST) || name.equals(NEXT))) {
error("layer " + name + " is not allowed as a feature name");
return;
}
if (feature.getId() == 0) {
feature.setLayer(layerDetailForm.getModelObject());
feature.setProject(selectedProjectModel.getObject());
if (annotationService.existsFeature(feature.getName(), feature.getLayer())) {
error("This feature is already added for this layer!");
return;
}
if (annotationService.existsFeature(name, feature.getLayer())) {
error("this feature already exists!");
return;
}
feature.setName(name);
saveFeature(feature);
}
if (tagSet.getModelObject() != null) {
FeatureDetailForm.this.getModelObject().setTagset(tagSet.getModelObject());
}
}
});
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
featureDetailForm.setModelObject(new AnnotationFeature());
// FeatureDetailForm.this.setVisible(false);
}
});
}
}
private void saveFeature(AnnotationFeature aFeature)
{
// Set properties of link features since these are currently not configurable in the UI
if (!PRIMITIVE_TYPES.contains(aFeature.getType())) {
aFeature.setMode(MultiValueMode.ARRAY);
aFeature.setLinkMode(LinkMode.WITH_ROLE);
aFeature.setLinkTypeRoleFeatureName("role");
aFeature.setLinkTypeTargetFeatureName("target");
aFeature.setLinkTypeName(aFeature.getLayer().getName()
+ WordUtils.capitalize(aFeature.getName()) + "Link");
}
// If the feature is not a string feature or a link-with-role feature, force the tagset
// to null.
if (!(CAS.TYPE_NAME_STRING.equals(aFeature.getType()) || !PRIMITIVE_TYPES.contains(aFeature
.getType()))) {
aFeature.setTagset(null);
}
annotationService.createFeature(aFeature);
featureDetailForm.setVisible(false);
}
public class FeatureSelectionForm
extends Form<SelectionModel>
{
private static final long serialVersionUID = -1L;
private ListChoice<AnnotationFeature> feature;
public FeatureSelectionForm(String id)
{
super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel()));
add(feature = new ListChoice<AnnotationFeature>("feature")
{
private static final long serialVersionUID = 1L;
{
setChoices(regenerateModel());
setChoiceRenderer(new ChoiceRenderer<AnnotationFeature>()
{
private static final long serialVersionUID = 4610648616450168333L;
@Override
public Object getDisplayValue(AnnotationFeature aObject)
{
return aObject.getUiName() + " : ["
+ StringUtils.substringAfterLast(aObject.getType(), ".") + "]";
}
});
setNullValid(false);
}
@Override
protected void onSelectionChanged(AnnotationFeature aNewSelection)
{
if (aNewSelection != null) {
featureDetailForm.setModelObject(aNewSelection);
featureDetailForm.setVisible(true);
}
}
@Override
protected boolean wantOnSelectionChangedNotifications()
{
return true;
}
@Override
protected CharSequence getDefaultChoice(String aSelectedValue)
{
return "";
}
});
add(new Button("new", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
featureDetailForm.setDefaultModelObject(new AnnotationFeature());
featureDetailForm.setVisible(true);
}
@Override
public boolean isEnabled()
{
return layerDetailForm.getModelObject() != null
&& !layerDetailForm.getModelObject().isBuiltIn()
&& !layerDetailForm.getModelObject().getType().equals(CHAIN_TYPE);
}
});
}
private LoadableDetachableModel<List<AnnotationFeature>> regenerateModel()
{
return new LoadableDetachableModel<List<AnnotationFeature>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<AnnotationFeature> load()
{
List<AnnotationFeature> features = annotationService
.listAnnotationFeature(layerDetailForm.getModelObject());
if (CHAIN_TYPE.equals(layerDetailForm.getModelObject().getType())
&& !layerDetailForm.getModelObject().isLinkedListBehavior()) {
List<AnnotationFeature> filtered = new ArrayList<AnnotationFeature>();
for (AnnotationFeature f : features) {
if (!WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(f.getName())) {
filtered.add(f);
}
}
return filtered;
}
else {
return features;
}
}
};
}
public void updateChoices()
{
feature.setChoices(regenerateModel());
}
}
}
|
webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/page/ProjectLayersPanel.java
|
/*******************************************************************************
* Copyright 2012
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.clarin.webanno.project.page;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.CHAIN_TYPE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFERENCE_RELATION_FEATURE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFERENCE_TYPE_FEATURE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.RELATION_TYPE;
import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.SPAN_TYPE;
import static java.util.Arrays.asList;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.uima.cas.CAS;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.extensions.markup.html.form.select.Select;
import org.apache.wicket.extensions.markup.html.form.select.SelectOption;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.core.context.SecurityContextHolder;
import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService;
import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService;
import de.tudarmstadt.ukp.clarin.webanno.api.UserDao;
import de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature;
import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer;
import de.tudarmstadt.ukp.clarin.webanno.model.LinkMode;
import de.tudarmstadt.ukp.clarin.webanno.model.MultiValueMode;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.model.TagSet;
import de.tudarmstadt.ukp.clarin.webanno.model.User;
import de.tudarmstadt.ukp.clarin.webanno.support.EntityModel;
import de.tudarmstadt.ukp.clarin.webanno.support.JSONUtil;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
/**
* A Panel Used to add Layers to a selected {@link Project} in the project settings page
*
*
*/
public class ProjectLayersPanel
extends Panel
{
private static final long serialVersionUID = -7870526462864489252L;
@SpringBean(name = "annotationService")
private AnnotationService annotationService;
@SpringBean(name = "documentRepository")
private RepositoryService repository;
@SpringBean(name = "userRepository")
private UserDao userRepository;
private final String FIRST = "first";
private final String NEXT = "next";
private LayerSelectionForm layerSelectionForm;
private FeatureSelectionForm featureSelectionForm;
private LayerDetailForm layerDetailForm;
private final FeatureDetailForm featureDetailForm;
private final ImportLayerForm importLayerForm;
private Select<AnnotationLayer> layerSelection;
private final IModel<Project> selectedProjectModel;
private final static List<String> PRIMITIVE_TYPES = asList(CAS.TYPE_NAME_STRING,
CAS.TYPE_NAME_INTEGER, CAS.TYPE_NAME_FLOAT, CAS.TYPE_NAME_BOOLEAN);
private List<String> spanTypes = new ArrayList<String>();
private String layerType = WebAnnoConst.SPAN_TYPE;
private List<FileUpload> uploadedFiles;
private FileUploadField fileUpload;
public ProjectLayersPanel(String id, final IModel<Project> aProjectModel)
{
super(id);
this.selectedProjectModel = aProjectModel;
layerSelectionForm = new LayerSelectionForm("layerSelectionForm");
featureSelectionForm = new FeatureSelectionForm("featureSelectionForm");
featureSelectionForm.setVisible(false);
featureSelectionForm.setOutputMarkupPlaceholderTag(true);
layerDetailForm = new LayerDetailForm("layerDetailForm");
layerDetailForm.setVisible(false);
layerDetailForm.setOutputMarkupPlaceholderTag(true);
featureDetailForm = new FeatureDetailForm("featureDetailForm");
featureDetailForm.setVisible(false);
featureDetailForm.setOutputMarkupPlaceholderTag(true);
add(layerSelectionForm);
add(featureSelectionForm);
add(layerDetailForm);
add(featureDetailForm);
importLayerForm = new ImportLayerForm("importLayerForm");
add(importLayerForm);
}
private class LayerSelectionForm
extends Form<SelectionModel>
{
private static final long serialVersionUID = -1L;
public LayerSelectionForm(String id)
{
super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel()));
add(new Button("create", new ResourceModel("label"))
{
private static final long serialVersionUID = -4482428496358679571L;
@Override
public void onSubmit()
{
if (selectedProjectModel.getObject().getId() == 0) {
error("Project not yet created. Please save project details first!");
}
else {
LayerSelectionForm.this.getModelObject().layerSelection = null;
layerDetailForm.setModelObject(new AnnotationLayer());
layerDetailForm.setVisible(true);
featureSelectionForm.setVisible(false);
featureDetailForm.setVisible(false);
}
}
});
final Map<AnnotationLayer, String> colors = new HashMap<AnnotationLayer, String>();
layerSelection = new Select<AnnotationLayer>("layerSelection");
ListView<AnnotationLayer> layers = new ListView<AnnotationLayer>("layers",
new LoadableDetachableModel<List<AnnotationLayer>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<AnnotationLayer> load()
{
Project project = selectedProjectModel.getObject();
if (project.getId() != 0) {
List<AnnotationLayer> layers = annotationService
.listAnnotationLayer(project);
AnnotationLayer tokenLayer = annotationService.getLayer(
Token.class.getName(), project);
layers.remove(tokenLayer);
for (AnnotationLayer layer : layers) {
if (layer.isBuiltIn() && layer.isEnabled()) {
colors.put(layer, "green");
}
else if (layer.isEnabled()) {
colors.put(layer, "blue");
}
else {
colors.put(layer, "red");
}
}
return layers;
}
return new ArrayList<AnnotationLayer>();
}
})
{
private static final long serialVersionUID = 8901519963052692214L;
@Override
protected void populateItem(final ListItem<AnnotationLayer> item)
{
item.add(new SelectOption<AnnotationLayer>("layer", new Model<AnnotationLayer>(
item.getModelObject()))
{
private static final long serialVersionUID = 3095089418860168215L;
@Override
public void onComponentTagBody(MarkupStream markupStream,
ComponentTag openTag)
{
replaceComponentTagBody(markupStream, openTag, item.getModelObject()
.getUiName());
}
}.add(new AttributeModifier("style", "color:"
+ colors.get(item.getModelObject()) + ";")));
}
};
add(layerSelection.add(layers));
layerSelection.setOutputMarkupId(true);
layerSelection.add(new OnChangeAjaxBehavior()
{
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
layerDetailForm.setModelObject(getModelObject().layerSelection);
layerDetailForm.setVisible(true);
LayerSelectionForm.this.setVisible(true);
featureSelectionForm.clearInput();
featureSelectionForm.setVisible(true);
layerDetailForm.setVisible(true);
featureDetailForm.setVisible(false);
layerType = getModelObject().layerSelection.getType();
aTarget.add(layerDetailForm);
aTarget.add(featureSelectionForm);
aTarget.add(featureDetailForm);
}
});
}
}
private class ImportLayerForm
extends Form<String>
{
private static final long serialVersionUID = -7777616763931128598L;
@SuppressWarnings({ "unchecked", "rawtypes" })
public ImportLayerForm(String id)
{
super(id);
add(fileUpload = new FileUploadField("content", new Model()));
add(new Button("import", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
uploadedFiles = fileUpload.getFileUploads();
Project project = selectedProjectModel.getObject();
String username = SecurityContextHolder.getContext().getAuthentication()
.getName();
User user = userRepository.get(username);
if (isEmpty(uploadedFiles)) {
error("Please choose file with layer details before uploading");
return;
}
else if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
for (FileUpload tagFile : uploadedFiles) {
InputStream tagInputStream;
try {
tagInputStream = tagFile.getInputStream();
String text = IOUtils.toString(tagInputStream, "UTF-8");
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exLayer = JSONUtil
.getJsonConverter()
.getObjectMapper()
.readValue(
text,
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer.class);
AnnotationLayer attachLayer = null;
if (exLayer.getAttachType() != null) {
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exAttachLayer = exLayer
.getAttachType();
createLayer(exAttachLayer, user, null);
attachLayer = annotationService.getLayer(exAttachLayer.getName(),
project);
}
createLayer(exLayer, user, attachLayer);
layerDetailForm.setModelObject(annotationService.getLayer(
exLayer.getName(), project));
layerDetailForm.setVisible(true);
featureSelectionForm.setVisible(true);
}
catch (IOException e) {
error("Error Importing TagSet " + ExceptionUtils.getRootCauseMessage(e));
}
}
featureDetailForm.setVisible(false);
}
private void createLayer(
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer aExLayer,
User aUser, AnnotationLayer aAttachLayer)
throws IOException
{
Project project = selectedProjectModel.getObject();
AnnotationLayer layer;
if (annotationService.existsLayer(aExLayer.getName(), aExLayer.getType(),
project)) {
layer = annotationService.getLayer(aExLayer.getName(),
selectedProjectModel.getObject());
ImportUtil.setLayer(annotationService, layer, aExLayer, project, aUser);
}
else {
layer = new AnnotationLayer();
ImportUtil.setLayer(annotationService, layer, aExLayer, project, aUser);
}
layer.setAttachType(aAttachLayer);
for (de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationFeature exfeature : aExLayer
.getFeatures()) {
de.tudarmstadt.ukp.clarin.webanno.model.export.TagSet exTagset = exfeature
.getTagSet();
TagSet tagSet = null;
if (exTagset != null
&& annotationService.existsTagSet(exTagset.getName(), project)) {
tagSet = annotationService.getTagSet(exTagset.getName(), project);
ImportUtil.createTagSet(tagSet, exTagset, project, aUser,
annotationService);
}
else if (exTagset != null) {
tagSet = new TagSet();
ImportUtil.createTagSet(tagSet, exTagset, project, aUser,
annotationService);
}
if (annotationService.existsFeature(exfeature.getName(), layer)) {
AnnotationFeature feature = annotationService.getFeature(
exfeature.getName(), layer);
feature.setTagset(tagSet);
ImportUtil.setFeature(annotationService, feature, exfeature, project,
aUser);
continue;
}
AnnotationFeature feature = new AnnotationFeature();
feature.setLayer(layer);
feature.setTagset(tagSet);
ImportUtil
.setFeature(annotationService, feature, exfeature, project, aUser);
}
}
});
}
}
public class SelectionModel
implements Serializable
{
private static final long serialVersionUID = -1L;
private AnnotationLayer layerSelection;
public AnnotationFeature feature;
}
private class LayerDetailForm
extends Form<AnnotationLayer>
{
private static final long serialVersionUID = -1L;
private Label name;
private TextField<String> uiName;
private static final String TYPE_PREFIX = "webanno.custom.";
private String layerName;
private DropDownChoice<String> layerTypes;
private DropDownChoice<AnnotationLayer> attachTypes;
private Label lockToTokenOffsetLabel;
private CheckBox lockToTokenOffset;
private Label allowStackingLabel;
private CheckBox allowStacking;
private Label crossSentenceLabel;
private CheckBox crossSentence;
private Label multipleTokensLabel;
private CheckBox multipleTokens;
private Label linkedListBehaviorLabel;
private CheckBox linkedListBehavior;
public LayerDetailForm(String id)
{
super(id, new CompoundPropertyModel<AnnotationLayer>(new EntityModel<AnnotationLayer>(
new AnnotationLayer())));
final Project project = selectedProjectModel.getObject();
add(uiName = (TextField<String>) new TextField<String>("uiName").setRequired(true));
uiName.add(new AjaxFormComponentUpdatingBehavior("onkeyup")
{
private static final long serialVersionUID = -1756244972577094229L;
@Override
protected void onUpdate(AjaxRequestTarget target)
{
String modelValue = StringUtils.capitalize(getModelObject().getUiName());
layerName = modelValue;
}
});
add(name = new Label("name")
{
private static final long serialVersionUID = 1L;
@Override
protected void onConfigure()
{
setVisible(StringUtils.isNotBlank(LayerDetailForm.this.getModelObject()
.getName()));
};
});
add(new TextArea<String>("description").setOutputMarkupPlaceholderTag(true));
add(new CheckBox("enabled"));
add(layerTypes = (DropDownChoice<String>) new DropDownChoice<String>("type",
Arrays.asList(new String[] { SPAN_TYPE, RELATION_TYPE, CHAIN_TYPE }))
{
private static final long serialVersionUID = 1244555334843130802L;
@Override
public boolean isEnabled()
{
return LayerDetailForm.this.getModelObject().getId() == 0;
}
}.setRequired(true));
layerTypes.add(new AjaxFormComponentUpdatingBehavior("onchange")
{
private static final long serialVersionUID = 6790949494089940303L;
@Override
protected void onUpdate(AjaxRequestTarget target)
{
layerType = getModelObject().getType();
target.add(lockToTokenOffsetLabel);
target.add(lockToTokenOffset);
target.add(allowStackingLabel);
target.add(allowStacking);
target.add(crossSentenceLabel);
target.add(crossSentence);
target.add(multipleTokensLabel);
target.add(multipleTokens);
target.add(linkedListBehaviorLabel);
target.add(linkedListBehavior);
target.add(attachTypes);
}
});
attachTypes = (DropDownChoice<AnnotationLayer>) new DropDownChoice<AnnotationLayer>(
"attachType")
{
private static final long serialVersionUID = -6705445053442011120L;
{
setChoices(new LoadableDetachableModel<List<AnnotationLayer>>()
{
private static final long serialVersionUID = 1784646746122513331L;
@Override
protected List<AnnotationLayer> load()
{
List<AnnotationLayer> allLayers = annotationService
.listAnnotationLayer(project);
if (LayerDetailForm.this.getModelObject().getId() > 0) {
if (LayerDetailForm.this.getModelObject().getAttachType() == null) {
return new ArrayList<AnnotationLayer>();
}
return Arrays.asList(LayerDetailForm.this.getModelObject()
.getAttachType());
}
if (!layerType.equals(RELATION_TYPE)) {
return new ArrayList<AnnotationLayer>();
}
List<AnnotationLayer> attachTeypes = new ArrayList<AnnotationLayer>();
// remove a span layer which is already used as attach type for the
// other
List<AnnotationLayer> usedLayers = new ArrayList<AnnotationLayer>();
for (AnnotationLayer layer : allLayers) {
if (layer.getAttachType() != null) {
usedLayers.add(layer.getAttachType());
}
}
allLayers.removeAll(usedLayers);
for (AnnotationLayer layer : allLayers) {
if (layer.getType().equals(SPAN_TYPE) && !layer.isBuiltIn()) {
attachTeypes.add(layer);
}
}
return attachTeypes;
}
});
setChoiceRenderer(new ChoiceRenderer<AnnotationLayer>("uiName"));
}
@Override
protected void onConfigure()
{
setEnabled(LayerDetailForm.this.getModelObject().getId() == 0);
setNullValid(isVisible());
};
};
attachTypes.setOutputMarkupPlaceholderTag(true);
add(attachTypes);
// Behaviors of layers
add(new CheckBox("readonly"));
add(lockToTokenOffsetLabel = new Label("lockToTokenOffsetLabel",
"Lock to token offsets:")
{
private static final long serialVersionUID = -1290883833837327207L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relation layers or layers that attach to tokens
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType())
&& layer.getAttachFeature() == null);
setEnabled(!CHAIN_TYPE.equals(layer.getType()));
}
});
add(lockToTokenOffset = new CheckBox("lockToTokenOffset")
{
private static final long serialVersionUID = -4934708834659137207L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relation layers or layers that attach to tokens
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType())
&& layer.getAttachFeature() == null);
setEnabled(!CHAIN_TYPE.equals(layer.getType()));
}
});
add(allowStackingLabel = new Label("allowStackingLabel", "Allow stacking:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that have an attach feature (basically Dependency)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(allowStacking = new CheckBox("allowStacking")
{
private static final long serialVersionUID = 7800627916287273008L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(crossSentenceLabel = new Label("crossSentenceLabel",
"Allow crossing sentence boundary:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(crossSentence = new CheckBox("crossSentence")
{
private static final long serialVersionUID = -5986386642712152491L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(multipleTokensLabel = new Label("multipleTokensLabel", "Allow multiple tokens:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relations
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(multipleTokens = new CheckBox("multipleTokens")
{
private static final long serialVersionUID = 1319818165277559402L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
// Makes no sense for relations
setVisible(!isBlank(layer.getType()) && !RELATION_TYPE.equals(layer.getType()));
// Not configurable for chains
// Not configurable for layers that attach to tokens (currently that is the
// only layer on which we use the attach feature)
setEnabled(!CHAIN_TYPE.equals(layer.getType()) && layer.getAttachFeature() == null);
}
});
add(linkedListBehaviorLabel = new Label("linkedListBehaviorLabel",
"Behave like a linked list:")
{
private static final long serialVersionUID = -5354062154610496880L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()) && CHAIN_TYPE.equals(layer.getType()));
}
});
add(linkedListBehavior = new CheckBox("linkedListBehavior")
{
private static final long serialVersionUID = 1319818165277559402L;
{
setOutputMarkupPlaceholderTag(true);
}
@Override
protected void onConfigure()
{
super.onConfigure();
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
setVisible(!isBlank(layer.getType()) && CHAIN_TYPE.equals(layer.getType()));
}
});
linkedListBehavior.add(new AjaxFormComponentUpdatingBehavior("onChange")
{
private static final long serialVersionUID = -2904306846882446294L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
featureSelectionForm.updateChoices();
aTarget.add(featureSelectionForm);
aTarget.add(featureDetailForm);
}
});
add(new Button("save", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
AnnotationLayer layer = LayerDetailForm.this.getModelObject();
if (layer.isLockToTokenOffset() && layer.isMultipleTokens()) {
layer.setLockToTokenOffset(false);
}
if (layer.getId() == 0) {
layerName = layerName.replaceAll("\\W", "");
if(layerName.isEmpty() || !isAscii(layerName)){
error("Non ASCII characters can not be used as layer name!");
return;
}
if (annotationService.existsLayer(TYPE_PREFIX + layerName, layer.getType(),
project)) {
error("Only one Layer per project is allowed!");
return;
}
if (layer.getType().equals(RELATION_TYPE) && layer.getAttachType() == null) {
error("a relation layer need an attach type!");
return;
}
if ((TYPE_PREFIX + layerName).endsWith(".")) {
error("please give a proper layer name!");
return;
}
String username = SecurityContextHolder.getContext().getAuthentication()
.getName();
User user = userRepository.get(username);
layer.setProject(project);
try {
layer.setName(TYPE_PREFIX + layerName);
annotationService.createLayer(layer, user);
if (layer.getType().equals(WebAnnoConst.CHAIN_TYPE)) {
AnnotationFeature relationFeature = new AnnotationFeature();
relationFeature.setType(layer.getName());
relationFeature.setName(COREFERENCE_RELATION_FEATURE);
relationFeature.setLayer(layer);
relationFeature.setEnabled(true);
relationFeature.setUiName("Reference Relation");
relationFeature.setProject(project);
annotationService.createFeature(relationFeature);
AnnotationFeature typeFeature = new AnnotationFeature();
typeFeature.setType(layer.getName());
typeFeature.setName(COREFERENCE_TYPE_FEATURE);
typeFeature.setLayer(layer);
typeFeature.setEnabled(true);
typeFeature.setUiName("Reference Type");
typeFeature.setProject(project);
annotationService.createFeature(typeFeature);
}
}
catch (IOException e) {
error("unable to create Log file while creating this layer" + ":"
+ ExceptionUtils.getRootCauseMessage(e));
}
featureSelectionForm.setVisible(true);
}
}
});
add(new DownloadLink("export", new LoadableDetachableModel<File>()
{
private static final long serialVersionUID = 840863954694163375L;
@Override
protected File load()
{
File exportFile = null;
try {
exportFile = File.createTempFile("exportedLayer", ".json");
}
catch (IOException e1) {
error("Unable to create temporary File!!");
}
if (selectedProjectModel.getObject().getId() == 0) {
error("Project not yet created. Please save project details first!");
return null;
}
AnnotationLayer layer = layerDetailForm.getModelObject();
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exLayer = ImportUtil
.exportLayerDetails(null, null, layer, annotationService);
if (layer.getAttachType() != null) {
AnnotationLayer attachLayer = layer.getAttachType();
de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationLayer exAttachLayer = ImportUtil
.exportLayerDetails(null, null, attachLayer, annotationService);
exLayer.setAttachType(exAttachLayer);
}
try {
JSONUtil.generateJson(exLayer, exportFile);
}
catch (IOException e) {
error("File Path not found or No permision to save the file!");
}
info("TagSets successfully exported to :" + exportFile.getAbsolutePath());
return exportFile;
}
}).setOutputMarkupId(true));
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
// layerDetailForm.setModelObject(new AnnotationLayer());
// layerSelectionForm.setModelObject(new SelectionModel());
// featureSelectionForm.setModelObject(new SelectionModel());
// featureDetailForm.setModelObject(new AnnotationFeature());
// layerDetailForm.setModelObject(null);
layerDetailForm.setVisible(false);
featureSelectionForm.setVisible(false);
featureDetailForm.setVisible(false);
}
});
}
}
public static boolean isAscii(String v)
{
CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
return asciiEncoder.canEncode(v);
}
private class FeatureDetailForm
extends Form<AnnotationFeature>
{
private static final long serialVersionUID = -1L;
DropDownChoice<TagSet> tagSet;
DropDownChoice<String> featureType;
public FeatureDetailForm(String id)
{
super(id, new CompoundPropertyModel<AnnotationFeature>(
new EntityModel<AnnotationFeature>(new AnnotationFeature())));
add(new TextField<String>("uiName").setRequired(true));
add(new TextArea<String>("description").setOutputMarkupPlaceholderTag(true));
add(new CheckBox("enabled"));
add(new CheckBox("visible"));
add(new CheckBox("remember"));
add(new CheckBox("hideUnconstraintFeature"));
spanTypes.add(CAS.TYPE_NAME_ANNOTATION);
for (AnnotationLayer spanLayer : annotationService
.listAnnotationLayer(selectedProjectModel.getObject())) {
if (spanLayer.getName().equals(Token.class.getName())) {
continue;
}
if (spanLayer.getType().equals(WebAnnoConst.SPAN_TYPE)) {
spanTypes.add(spanLayer.getName());
}
}
add(featureType = (DropDownChoice<String>) new DropDownChoice<String>("type")
{
private static final long serialVersionUID = 9029205407108101183L;
{
setRequired(true);
setNullValid(false);
setChoices(new LoadableDetachableModel<List<String>>()
{
private static final long serialVersionUID = -5732558926576750673L;
@Override
protected List<String> load()
{
if (getModelObject() != null) {
return Arrays.asList(getModelObject());
}
List<String> types = new ArrayList<String>(PRIMITIVE_TYPES);
types.addAll(spanTypes);
return types;
}
});
}
@Override
protected void onConfigure()
{
setEnabled(FeatureDetailForm.this.getModelObject().getId() == 0);
};
});
featureType.add(new AjaxFormComponentUpdatingBehavior("onChange")
{
private static final long serialVersionUID = -2904306846882446294L;
@Override
protected void onUpdate(AjaxRequestTarget aTarget)
{
aTarget.add(tagSet);
}
});
add(tagSet = new DropDownChoice<TagSet>("tagset")
{
private static final long serialVersionUID = -6705445053442011120L;
{
setOutputMarkupPlaceholderTag(true);
setOutputMarkupId(true);
setChoiceRenderer(new ChoiceRenderer<TagSet>("name"));
setNullValid(true);
setChoices(new LoadableDetachableModel<List<TagSet>>()
{
private static final long serialVersionUID = 1784646746122513331L;
@Override
protected List<TagSet> load()
{
return annotationService.listTagSets(selectedProjectModel.getObject());
}
});
}
@Override
protected void onConfigure()
{
AnnotationFeature feature = FeatureDetailForm.this.getModelObject();
// Only display tagset choice for link features with role and string features
// Since we currently set the LinkRole only when saving, we have to rely on the
// feature type here.
setEnabled(CAS.TYPE_NAME_STRING.equals(feature.getType())
|| !PRIMITIVE_TYPES.contains(feature.getType()));
}
});
add(new Button("save", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
AnnotationFeature feature = FeatureDetailForm.this.getModelObject();
String name = feature.getUiName();
name = name.replaceAll("\\W", "");
if (layerDetailForm.getModelObject().getType().equals(RELATION_TYPE)
&& (name.equals(WebAnnoConst.FEAT_REL_SOURCE)
|| name.equals(WebAnnoConst.FEAT_REL_TARGET)
|| name.equals(FIRST) || name.equals(NEXT))) {
error("layer " + name + " is not allowed as a feature name");
return;
}
if (feature.getId() == 0) {
feature.setLayer(layerDetailForm.getModelObject());
feature.setProject(selectedProjectModel.getObject());
if (annotationService.existsFeature(feature.getName(), feature.getLayer())) {
error("This feature is already added for this layer!");
return;
}
if (annotationService.existsFeature(name, feature.getLayer())) {
error("this feature already exists!");
return;
}
feature.setName(name);
saveFeature(feature);
}
if (tagSet.getModelObject() != null) {
FeatureDetailForm.this.getModelObject().setTagset(tagSet.getModelObject());
}
}
});
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
featureDetailForm.setModelObject(new AnnotationFeature());
// FeatureDetailForm.this.setVisible(false);
}
});
}
}
private void saveFeature(AnnotationFeature aFeature)
{
// Set properties of link features since these are currently not configurable in the UI
if (!PRIMITIVE_TYPES.contains(aFeature.getType())) {
aFeature.setMode(MultiValueMode.ARRAY);
aFeature.setLinkMode(LinkMode.WITH_ROLE);
aFeature.setLinkTypeRoleFeatureName("role");
aFeature.setLinkTypeTargetFeatureName("target");
aFeature.setLinkTypeName(aFeature.getLayer().getName()
+ WordUtils.capitalize(aFeature.getName()) + "Link");
}
// If the feature is not a string feature or a link-with-role feature, force the tagset
// to null.
if (!(CAS.TYPE_NAME_STRING.equals(aFeature.getType()) || !PRIMITIVE_TYPES.contains(aFeature
.getType()))) {
aFeature.setTagset(null);
}
annotationService.createFeature(aFeature);
featureDetailForm.setVisible(false);
}
public class FeatureSelectionForm
extends Form<SelectionModel>
{
private static final long serialVersionUID = -1L;
private ListChoice<AnnotationFeature> feature;
public FeatureSelectionForm(String id)
{
super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel()));
add(feature = new ListChoice<AnnotationFeature>("feature")
{
private static final long serialVersionUID = 1L;
{
setChoices(regenerateModel());
setChoiceRenderer(new ChoiceRenderer<AnnotationFeature>()
{
private static final long serialVersionUID = 4610648616450168333L;
@Override
public Object getDisplayValue(AnnotationFeature aObject)
{
return aObject.getUiName() + " : ["
+ StringUtils.substringAfterLast(aObject.getType(), ".") + "]";
}
});
setNullValid(false);
}
@Override
protected void onSelectionChanged(AnnotationFeature aNewSelection)
{
if (aNewSelection != null) {
featureDetailForm.setModelObject(aNewSelection);
featureDetailForm.setVisible(true);
}
}
@Override
protected boolean wantOnSelectionChangedNotifications()
{
return true;
}
@Override
protected CharSequence getDefaultChoice(String aSelectedValue)
{
return "";
}
});
add(new Button("new", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
featureDetailForm.setDefaultModelObject(new AnnotationFeature());
featureDetailForm.setVisible(true);
}
@Override
public boolean isEnabled()
{
return layerDetailForm.getModelObject() != null
&& !layerDetailForm.getModelObject().isBuiltIn()
&& !layerDetailForm.getModelObject().getType().equals(CHAIN_TYPE);
}
});
}
private LoadableDetachableModel<List<AnnotationFeature>> regenerateModel()
{
return new LoadableDetachableModel<List<AnnotationFeature>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<AnnotationFeature> load()
{
List<AnnotationFeature> features = annotationService
.listAnnotationFeature(layerDetailForm.getModelObject());
if (CHAIN_TYPE.equals(layerDetailForm.getModelObject().getType())
&& !layerDetailForm.getModelObject().isLinkedListBehavior()) {
List<AnnotationFeature> filtered = new ArrayList<AnnotationFeature>();
for (AnnotationFeature f : features) {
if (!WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(f.getName())) {
filtered.add(f);
}
}
return filtered;
}
else {
return features;
}
}
};
}
public void updateChoices()
{
feature.setChoices(regenerateModel());
}
}
}
|
NO-ISSUES
referenceType and ReferenceRelation values should be of type String.
|
webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/page/ProjectLayersPanel.java
|
NO-ISSUES referenceType and ReferenceRelation values should be of type String.
|
|
Java
|
apache-2.0
|
943d27851270b0f0ffbbcbb8adc961d254a90f67
| 0
|
researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds
|
package won.bot.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import won.bot.framework.bot.base.EventBot;
import won.bot.framework.eventbot.EventListenerContext;
import won.bot.framework.eventbot.action.impl.mail.receive.*;
import won.bot.framework.eventbot.action.impl.mail.send.*;
import won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateNeedAction;
import won.bot.framework.eventbot.action.impl.wonmessage.CloseConnectionUriAction;
import won.bot.framework.eventbot.action.impl.wonmessage.OpenConnectionUriAction;
import won.bot.framework.eventbot.action.impl.wonmessage.SendMessageOnConnectionAction;
import won.bot.framework.eventbot.bus.EventBus;
import won.bot.framework.eventbot.event.impl.command.deactivate.DeactivateNeedCommandEvent;
import won.bot.framework.eventbot.event.impl.command.SendTextMessageOnConnectionEvent;
import won.bot.framework.eventbot.event.impl.mail.*;
import won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherNeedEvent;
import won.bot.framework.eventbot.listener.impl.ActionOnEventListener;
import javax.mail.internet.MimeMessage;
/**
* This Bot checks the E-Mails from a given set of configured E-Mail Adresses and creates Needs that represent these E-Mails
* In Future Implementations it will support the bidirectional communication between the node content and the email sender?!
* Created by fsuda on 27.09.2016.
*/
public class Mail2WonBot extends EventBot{
@Autowired
private MessageChannel receiveEmailChannel;
@Autowired
private MessageChannel sendEmailChannel;
@Autowired
MailContentExtractor mailContentExtractor;
@Autowired
WonMimeMessageGenerator mailGenerator;
private EventBus bus;
@Override
protected void initializeEventListeners() {
EventListenerContext ctx = getEventListenerContext();
mailGenerator.setEventListenerContext(ctx);
bus = getEventBus();
//Mail initiated events
bus.subscribe(MailReceivedEvent.class,
new ActionOnEventListener(
ctx,
"MailReceived",
new MailParserAction(ctx, mailContentExtractor)
));
bus.subscribe(CreateNeedFromMailEvent.class,
new ActionOnEventListener(
ctx,
"CreateNeedFromMailEvent",
new CreateNeedFromMailAction(ctx, mailContentExtractor)
));
bus.subscribe(WelcomeMailEvent.class, new ActionOnEventListener(
ctx,
"WelcomeMailAction",
new WelcomeMailAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(MailCommandEvent.class,
new ActionOnEventListener(
ctx,
"MailCommandEvent",
new MailCommandAction(ctx, mailContentExtractor)
));
bus.subscribe(SendTextMessageOnConnectionEvent.class,
new ActionOnEventListener(
ctx,
"SendTextMessage",
new SendMessageOnConnectionAction(ctx)
));
bus.subscribe(CloseConnectionEvent.class,
new ActionOnEventListener(
ctx,
"CloseCommandEvent",
new CloseConnectionUriAction(ctx)
));
bus.subscribe(DeactivateNeedCommandEvent.class,
new ActionOnEventListener(
ctx,
"DeactivateNeedEvent",
new DeactivateNeedAction(ctx)
));
bus.subscribe(OpenConnectionEvent.class,
new ActionOnEventListener(
ctx,
"OpenCommandEvent",
new OpenConnectionUriAction(ctx)
));
bus.subscribe(SubscribeUnsubscribeEvent.class,
new ActionOnEventListener(ctx, "SubscribeUnsubscribeEvent", new SubscribeUnsubscribeAction(ctx)));
//WON initiated Events
bus.subscribe(HintFromMatcherEvent.class,
new ActionOnEventListener(
ctx,
"HintReceived",
new Hint2MailParserAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(ConnectFromOtherNeedEvent.class,
new ActionOnEventListener(
ctx,
"ConnectReceived",
new Connect2MailParserAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(MessageFromOtherNeedEvent.class,
new ActionOnEventListener(
ctx,
"ReceivedTextMessage",
new Message2MailAction(mailGenerator, sendEmailChannel)
));
}
public void receive(MimeMessage message) {
bus.publish(new MailReceivedEvent(message));
}
public void setReceiveEmailChannel(MessageChannel receiveEmailChannel) {
this.receiveEmailChannel = receiveEmailChannel;
}
public void setSendEmailChannel(MessageChannel sendEmailChannel) {
this.sendEmailChannel = sendEmailChannel;
}
public void setMailGenerator(WonMimeMessageGenerator mailGenerator) {
this.mailGenerator = mailGenerator;
}
}
|
webofneeds/won-bot/src/main/java/won/bot/impl/Mail2WonBot.java
|
package won.bot.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import won.bot.framework.bot.base.EventBot;
import won.bot.framework.eventbot.EventListenerContext;
import won.bot.framework.eventbot.action.impl.mail.receive.*;
import won.bot.framework.eventbot.action.impl.mail.send.*;
import won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateNeedAction;
import won.bot.framework.eventbot.action.impl.wonmessage.CloseConnectionUriAction;
import won.bot.framework.eventbot.action.impl.wonmessage.OpenConnectionUriAction;
import won.bot.framework.eventbot.action.impl.wonmessage.SendMessageOnConnectionAction;
import won.bot.framework.eventbot.bus.EventBus;
import won.bot.framework.eventbot.event.impl.command.DeactivateNeedCommandEvent;
import won.bot.framework.eventbot.event.impl.command.SendTextMessageOnConnectionEvent;
import won.bot.framework.eventbot.event.impl.mail.*;
import won.bot.framework.eventbot.event.impl.needlifecycle.NeedDeactivatedEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherNeedEvent;
import won.bot.framework.eventbot.listener.impl.ActionOnEventListener;
import javax.mail.internet.MimeMessage;
/**
* This Bot checks the E-Mails from a given set of configured E-Mail Adresses and creates Needs that represent these E-Mails
* In Future Implementations it will support the bidirectional communication between the node content and the email sender?!
* Created by fsuda on 27.09.2016.
*/
public class Mail2WonBot extends EventBot{
@Autowired
private MessageChannel receiveEmailChannel;
@Autowired
private MessageChannel sendEmailChannel;
@Autowired
MailContentExtractor mailContentExtractor;
@Autowired
WonMimeMessageGenerator mailGenerator;
private EventBus bus;
@Override
protected void initializeEventListeners() {
EventListenerContext ctx = getEventListenerContext();
mailGenerator.setEventListenerContext(ctx);
bus = getEventBus();
//Mail initiated events
bus.subscribe(MailReceivedEvent.class,
new ActionOnEventListener(
ctx,
"MailReceived",
new MailParserAction(ctx, mailContentExtractor)
));
bus.subscribe(CreateNeedFromMailEvent.class,
new ActionOnEventListener(
ctx,
"CreateNeedFromMailEvent",
new CreateNeedFromMailAction(ctx, mailContentExtractor)
));
bus.subscribe(WelcomeMailEvent.class, new ActionOnEventListener(
ctx,
"WelcomeMailAction",
new WelcomeMailAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(MailCommandEvent.class,
new ActionOnEventListener(
ctx,
"MailCommandEvent",
new MailCommandAction(ctx, mailContentExtractor)
));
bus.subscribe(SendTextMessageOnConnectionEvent.class,
new ActionOnEventListener(
ctx,
"SendTextMessage",
new SendMessageOnConnectionAction(ctx)
));
bus.subscribe(CloseConnectionEvent.class,
new ActionOnEventListener(
ctx,
"CloseCommandEvent",
new CloseConnectionUriAction(ctx)
));
bus.subscribe(DeactivateNeedCommandEvent.class,
new ActionOnEventListener(
ctx,
"DeactivateNeedEvent",
new DeactivateNeedAction(ctx)
));
bus.subscribe(OpenConnectionEvent.class,
new ActionOnEventListener(
ctx,
"OpenCommandEvent",
new OpenConnectionUriAction(ctx)
));
bus.subscribe(SubscribeUnsubscribeEvent.class,
new ActionOnEventListener(ctx, "SubscribeUnsubscribeEvent", new SubscribeUnsubscribeAction(ctx)));
//WON initiated Events
bus.subscribe(HintFromMatcherEvent.class,
new ActionOnEventListener(
ctx,
"HintReceived",
new Hint2MailParserAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(ConnectFromOtherNeedEvent.class,
new ActionOnEventListener(
ctx,
"ConnectReceived",
new Connect2MailParserAction(mailGenerator, sendEmailChannel)
));
bus.subscribe(MessageFromOtherNeedEvent.class,
new ActionOnEventListener(
ctx,
"ReceivedTextMessage",
new Message2MailAction(mailGenerator, sendEmailChannel)
));
}
public void receive(MimeMessage message) {
bus.publish(new MailReceivedEvent(message));
}
public void setReceiveEmailChannel(MessageChannel receiveEmailChannel) {
this.receiveEmailChannel = receiveEmailChannel;
}
public void setSendEmailChannel(MessageChannel sendEmailChannel) {
this.sendEmailChannel = sendEmailChannel;
}
public void setMailGenerator(WonMimeMessageGenerator mailGenerator) {
this.mailGenerator = mailGenerator;
}
}
|
refactored package
|
webofneeds/won-bot/src/main/java/won/bot/impl/Mail2WonBot.java
|
refactored package
|
|
Java
|
apache-2.0
|
a98349a7bd1aaf7635dc3aff25bdfb18367d4877
| 0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
import com.yahoo.collections.Pair;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ContainerCluster;
import org.junit.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author baldersheim
* @author gjoranv
*/
public class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
" <jvm options='-XX:SoftRefLRUPolicyMSPerMB=2500' gc-options='-XX:+UseParNewGC' allocated-memory='45%'/>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("-XX:+UseParNewGC", qrStartConfig.jvm().gcopts());
assertEquals(45, qrStartConfig.jvm().heapSizeAsPercentageOfPhysicalMemory());
assertEquals("-XX:SoftRefLRUPolicyMSPerMB=2500", model.getContainerClusters().values().iterator().next().getContainers().get(0).getJvmOptions());
}
@Test
public void detect_conflicting_jvmgcoptions_in_jvmargs() {
assertFalse(ContainerModelBuilder.incompatibleGCOptions(""));
assertFalse(ContainerModelBuilder.incompatibleGCOptions("UseG1GC"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("-XX:+UseG1GC"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("abc -XX:+UseParNewGC xyz"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("-XX:CMSInitiatingOccupancyFraction=19"));
}
@Test
public void honours_jvm_gc_options() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <search/>",
" <nodes jvm-gc-options='-XX:+UseG1GC'>",
" <node hostalias='mockhost'/>",
" </nodes>",
"</container>" );
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("-XX:+UseG1GC", qrStartConfig.jvm().gcopts());
}
private static void verifyIgnoreJvmGCOptions(boolean isHosted) throws IOException, SAXException {
verifyIgnoreJvmGCOptionsIfJvmArgs("jvmargs", ContainerCluster.G1GC, isHosted);
verifyIgnoreJvmGCOptionsIfJvmArgs( "jvm-options", "-XX:+UseG1GC", isHosted);
}
private static void verifyIgnoreJvmGCOptionsIfJvmArgs(String jvmOptionsName, String expectedGC, boolean isHosted) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes jvm-gc-options='-XX:+UseG1GC' " + jvmOptionsName + "='-XX:+UseParNewGC'>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setHostedVespa(isHosted))
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals(expectedGC, qrStartConfig.jvm().gcopts());
}
@Test
public void ignores_jvmgcoptions_on_conflicting_jvmargs() throws IOException, SAXException {
verifyIgnoreJvmGCOptions(false);
verifyIgnoreJvmGCOptions(true);
}
private void verifyJvmGCOptions(boolean isHosted, String featureFlagDefault, String override, String expected) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes " + ((override == null) ? ">" : ("jvm-gc-options='" + override + "'>")) +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setJvmGCOptions(featureFlagDefault).setHostedVespa(isHosted))
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals(expected, qrStartConfig.jvm().gcopts());
}
@Test
public void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException {
verifyJvmGCOptions(false, null, null, ContainerCluster.G1GC);
verifyJvmGCOptions(true, null, null, ContainerCluster.PARALLEL_GC);
verifyJvmGCOptions(true, "", null, ContainerCluster.PARALLEL_GC);
verifyJvmGCOptions(false, "-XX:+UseG1GC", null, "-XX:+UseG1GC");
verifyJvmGCOptions(true, "-XX:+UseG1GC", null, "-XX:+UseG1GC");
verifyJvmGCOptions(false, null, "-XX:+UseG1GC", "-XX:+UseG1GC");
verifyJvmGCOptions(false, "-XX:+UseParallelGC", "-XX:+UseG1GC", "-XX:+UseG1GC");
verifyJvmGCOptions(false, null, "-XX:+UseParallelGC", "-XX:+UseParallelGC");
}
@Test
public void requireThatInvalidJvmGcOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmGcOptions(true,
"-XX:+ParallelGCThreads=8 foo bar",
"foo", "bar");
verifyLoggingOfJvmGcOptions(true,
"-XX:+UseCMSInitiatingOccupancyOnly foo bar",
"-XX:+UseCMSInitiatingOccupancyOnly", "foo", "bar");
verifyLoggingOfJvmGcOptions(true,
"-XX:+UseConcMarkSweepGC",
"-XX:+UseConcMarkSweepGC");
verifyLoggingOfJvmGcOptions(true,
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
verifyLoggingOfJvmGcOptions(false,
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
// Valid options, should not log anything
verifyLoggingOfJvmGcOptions(true, "-XX:+ParallelGCThreads=8");
verifyLoggingOfJvmGcOptions(true, "-XX:MaxTenuringThreshold"); // No + or - after colon
verifyLoggingOfJvmGcOptions(false, "-XX:+UseConcMarkSweepGC");
}
@Test
public void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true).failDeploymentWithInvalidJvmOptions(true),
new TestLogger(),
"gc-options",
"-XX:+ParallelGCThreads=8 foo bar");
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid JVM GC options in services.xml: bar,foo"));
}
}
private void verifyLoggingOfJvmGcOptions(boolean isHosted, String override, String... invalidOptions) throws IOException, SAXException {
verifyLoggingOfJvmOptions(isHosted, "gc-options", override, invalidOptions);
}
private void verifyLoggingOfJvmOptions(boolean isHosted, String optionName, String override, String... invalidOptions) throws IOException, SAXException {
TestLogger logger = new TestLogger();
buildModelWithJvmOptions(isHosted, logger, optionName, override);
List<String> strings = Arrays.asList(invalidOptions.clone());
// Verify that nothing is logged if there are no invalid options
if (strings.isEmpty()) {
assertEquals(0, logger.msgs.size());
return;
}
Collections.sort(strings);
Pair<Level, String> firstOption = logger.msgs.get(0);
assertEquals(Level.WARNING, firstOption.getFirst());
assertEquals("Invalid JVM " + (optionName.equals("gc-options") ? "GC " : "") +
"options in services.xml: " + String.join(",", strings), firstOption.getSecond());
}
private void buildModelWithJvmOptions(boolean isHosted, TestLogger logger, String optionName, String override) throws IOException, SAXException {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(isHosted), logger, optionName, override);
}
private void buildModelWithJvmOptions(TestProperties properties, TestLogger logger, String optionName, String override) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes>" +
" <jvm " + optionName + "='" + override + "'/>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage app = new MockApplicationPackage.Builder().withServices(servicesXml).build();
new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(app)
.deployLogger(logger)
.properties(properties)
.build());
}
@Test
public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
"options",
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
verifyLoggingOfJvmOptions(false,
"options",
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
// Valid options, should not log anything
verifyLoggingOfJvmOptions(true, "options", "-Xms2G");
verifyLoggingOfJvmOptions(true, "options", "-verbose:gc");
verifyLoggingOfJvmOptions(false, "options", "-Xms2G");
}
@Test
public void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true).failDeploymentWithInvalidJvmOptions(true),
new TestLogger(),
"options",
"-Xms2G foo bar");
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid JVM options in services.xml: bar,foo"));
}
}
}
|
config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.xml;
import com.yahoo.collections.Pair;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.builder.xml.test.DomBuilderTest;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.deploy.TestProperties;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.container.ContainerCluster;
import org.junit.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author baldersheim
* @author gjoranv
*/
public class JvmOptionsTest extends ContainerModelBuilderTestBase {
@Test
public void verify_jvm_tag_with_attributes() throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <search/>" +
" <nodes>" +
" <jvm options='-XX:SoftRefLRUPolicyMSPerMB=2500' gc-options='-XX:+UseParNewGC' allocated-memory='45%'/>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("-XX:+UseParNewGC", qrStartConfig.jvm().gcopts());
assertEquals(45, qrStartConfig.jvm().heapSizeAsPercentageOfPhysicalMemory());
assertEquals("-XX:SoftRefLRUPolicyMSPerMB=2500", model.getContainerClusters().values().iterator().next().getContainers().get(0).getJvmOptions());
}
@Test
public void detect_conflicting_jvmgcoptions_in_jvmargs() {
assertFalse(ContainerModelBuilder.incompatibleGCOptions(""));
assertFalse(ContainerModelBuilder.incompatibleGCOptions("UseG1GC"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("-XX:+UseG1GC"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("abc -XX:+UseParNewGC xyz"));
assertTrue(ContainerModelBuilder.incompatibleGCOptions("-XX:CMSInitiatingOccupancyFraction=19"));
}
@Test
public void honours_jvm_gc_options() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <search/>",
" <nodes jvm-gc-options='-XX:+UseG1GC'>",
" <node hostalias='mockhost'/>",
" </nodes>",
"</container>" );
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("-XX:+UseG1GC", qrStartConfig.jvm().gcopts());
}
private static void verifyIgnoreJvmGCOptions(boolean isHosted) throws IOException, SAXException {
verifyIgnoreJvmGCOptionsIfJvmArgs("jvmargs", ContainerCluster.G1GC, isHosted);
verifyIgnoreJvmGCOptionsIfJvmArgs( "jvm-options", "-XX:+UseG1GC", isHosted);
}
private static void verifyIgnoreJvmGCOptionsIfJvmArgs(String jvmOptionsName, String expectedGC, boolean isHosted) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes jvm-gc-options='-XX:+UseG1GC' " + jvmOptionsName + "='-XX:+UseParNewGC'>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setHostedVespa(isHosted))
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals(expectedGC, qrStartConfig.jvm().gcopts());
}
@Test
public void ignores_jvmgcoptions_on_conflicting_jvmargs() throws IOException, SAXException {
verifyIgnoreJvmGCOptions(false);
verifyIgnoreJvmGCOptions(true);
}
private void verifyJvmGCOptions(boolean isHosted, String featureFlagDefault, String override, String expected) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes " + ((override == null) ? ">" : ("jvm-gc-options='" + override + "'>")) +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
// Need to create VespaModel to make deploy properties have effect
final TestLogger logger = new TestLogger();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setJvmGCOptions(featureFlagDefault).setHostedVespa(isHosted))
.build());
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
model.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals(expected, qrStartConfig.jvm().gcopts());
}
@Test
public void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException {
verifyJvmGCOptions(false, null, null, ContainerCluster.G1GC);
verifyJvmGCOptions(true, null, null, ContainerCluster.PARALLEL_GC);
verifyJvmGCOptions(true, "", null, ContainerCluster.PARALLEL_GC);
verifyJvmGCOptions(false, "-XX:+UseG1GC", null, "-XX:+UseG1GC");
verifyJvmGCOptions(true, "-XX:+UseG1GC", null, "-XX:+UseG1GC");
verifyJvmGCOptions(false, null, "-XX:+UseG1GC", "-XX:+UseG1GC");
verifyJvmGCOptions(false, "-XX:+UseParallelGC", "-XX:+UseG1GC", "-XX:+UseG1GC");
verifyJvmGCOptions(false, null, "-XX:+UseParallelGC", "-XX:+UseParallelGC");
}
@Test
public void requireThatInvalidJvmGcOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmGcOptions(true,
"-XX:+ParallelGCThreads=8 foo bar",
"foo", "bar");
verifyLoggingOfJvmGcOptions(true,
"-XX:+UseCMSInitiatingOccupancyOnly foo bar",
"-XX:+UseCMSInitiatingOccupancyOnly", "foo", "bar");
verifyLoggingOfJvmGcOptions(true,
"-XX:+UseConcMarkSweepGC",
"-XX:+UseConcMarkSweepGC");
verifyLoggingOfJvmGcOptions(true,
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
verifyLoggingOfJvmGcOptions(false,
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
// Valid options, should not log anything
verifyLoggingOfJvmGcOptions(true, "-XX:+ParallelGCThreads=8");
verifyLoggingOfJvmGcOptions(true, "-XX:MaxTenuringThreshold"); // No + or - after colon
verifyLoggingOfJvmGcOptions(false, "-XX:+UseConcMarkSweepGC");
}
@Test
public void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true).failDeploymentWithInvalidJvmOptions(true),
new TestLogger(),
"gc-options",
"-XX:+ParallelGCThreads=8 foo bar");
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid JVM GC options in services.xml: bar,foo"));
}
}
private void verifyLoggingOfJvmGcOptions(boolean isHosted, String override, String... invalidOptions) throws IOException, SAXException {
verifyLoggingOfJvmOptions(isHosted, "gc-options", override, invalidOptions);
}
private void verifyLoggingOfJvmOptions(boolean isHosted, String optionName, String override, String... invalidOptions) throws IOException, SAXException {
TestLogger logger = new TestLogger();
buildModelWithJvmOptions(isHosted, logger, optionName, override);
List<String> strings = Arrays.asList(invalidOptions.clone());
if (strings.isEmpty()) return;
Collections.sort(strings);
Pair<Level, String> firstOption = logger.msgs.get(0);
assertEquals(Level.WARNING, firstOption.getFirst());
assertEquals("Invalid JVM " + (optionName.equals("gc-options") ? "GC " : "") +
"options in services.xml: " + String.join(",", strings), firstOption.getSecond());
}
private void buildModelWithJvmOptions(boolean isHosted, TestLogger logger, String optionName, String override) throws IOException, SAXException {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(isHosted), logger, optionName, override);
}
private void buildModelWithJvmOptions(TestProperties properties, TestLogger logger, String optionName, String override) throws IOException, SAXException {
String servicesXml =
"<container version='1.0'>" +
" <nodes>" +
" <jvm " + optionName + "='" + override + "'/>" +
" <node hostalias='mockhost'/>" +
" </nodes>" +
"</container>";
ApplicationPackage app = new MockApplicationPackage.Builder().withServices(servicesXml).build();
new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(app)
.deployLogger(logger)
.properties(properties)
.build());
}
@Test
public void requireThatJvmOptionsAreLogged() throws IOException, SAXException {
verifyLoggingOfJvmOptions(true,
"options",
"-Xms2G foo bar",
"foo", "bar");
verifyLoggingOfJvmOptions(true,
"options",
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
verifyLoggingOfJvmOptions(false,
"options",
"$(touch /tmp/hello-from-gc-options)",
"$(touch", "/tmp/hello-from-gc-options)");
// Valid options, should not log anything
verifyLoggingOfJvmOptions(true, "options", "-Xms2G");
verifyLoggingOfJvmOptions(true, "options", "-verbose:gc");
verifyLoggingOfJvmOptions(false, "options", "-Xms2G");
}
@Test
public void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException {
try {
buildModelWithJvmOptions(new TestProperties().setHostedVespa(true).failDeploymentWithInvalidJvmOptions(true),
new TestLogger(),
"options",
"-Xms2G foo bar");
fail();
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("Invalid JVM options in services.xml: bar,foo"));
}
}
}
|
Add test of no loggin of invalid options
|
config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java
|
Add test of no loggin of invalid options
|
|
Java
|
apache-2.0
|
216b972b6b09c0bb612d7f716cfec68ace9777ec
| 0
|
tgroh/beam,manuzhang/beam,apache/beam,wtanaka/beam,tgroh/beam,wtanaka/beam,lukecwik/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,apache/beam,mxm/incubator-beam,rangadi/incubator-beam,robertwb/incubator-beam,apache/beam,rangadi/beam,RyanSkraba/beam,staslev/beam,charlesccychen/beam,chamikaramj/beam,apache/beam,manuzhang/incubator-beam,robertwb/incubator-beam,manuzhang/incubator-beam,sammcveety/incubator-beam,lukecwik/incubator-beam,wangyum/beam,robertwb/incubator-beam,apache/beam,eljefe6a/incubator-beam,wangyum/beam,peihe/incubator-beam,robertwb/incubator-beam,jbonofre/beam,charlesccychen/beam,lukecwik/incubator-beam,tgroh/incubator-beam,RyanSkraba/beam,chamikaramj/beam,chamikaramj/beam,markflyhigh/incubator-beam,staslev/beam,lukecwik/incubator-beam,RyanSkraba/beam,markflyhigh/incubator-beam,RyanSkraba/beam,chamikaramj/beam,charlesccychen/incubator-beam,wangyum/beam,staslev/incubator-beam,peihe/incubator-beam,apache/beam,lukecwik/incubator-beam,rangadi/beam,manuzhang/beam,robertwb/incubator-beam,rangadi/beam,apache/beam,robertwb/incubator-beam,RyanSkraba/beam,charlesccychen/beam,manuzhang/beam,apache/beam,sammcveety/incubator-beam,jbonofre/incubator-beam,wangyum/beam,yk5/beam,robertwb/incubator-beam,amarouni/incubator-beam,charlesccychen/beam,staslev/beam,mxm/incubator-beam,lukecwik/incubator-beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,yk5/beam,charlesccychen/incubator-beam,iemejia/incubator-beam,chamikaramj/beam,chamikaramj/beam,rangadi/beam,robertwb/incubator-beam,chamikaramj/beam,rangadi/beam,lukecwik/incubator-beam,jbonofre/beam,charlesccychen/beam,markflyhigh/incubator-beam,tgroh/beam,iemejia/incubator-beam,markflyhigh/incubator-beam,staslev/incubator-beam,apache/beam,jbonofre/incubator-beam,chamikaramj/beam,RyanSkraba/beam,rangadi/beam,jbonofre/beam,wtanaka/beam,tgroh/incubator-beam,peihe/incubator-beam,charlesccychen/incubator-beam,tgroh/beam,rangadi/incubator-beam,chamikaramj/beam,chamikaramj/beam,sammcveety/incubator-beam,charlesccychen/beam,apache/beam,amarouni/incubator-beam,charlesccychen/beam,yk5/beam,rangadi/incubator-beam,apache/beam,eljefe6a/incubator-beam,robertwb/incubator-beam,rangadi/beam,eljefe6a/incubator-beam,jbonofre/beam,markflyhigh/incubator-beam
|
examples/java/src/main/java/org/apache/beam/examples/spanner/SpannerCSVLoader.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.beam.examples.spanner;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Operation;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerOptions;
import com.google.spanner.admin.database.v1.CreateDatabaseMetadata;
import java.util.Collections;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.spanner.SpannerIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PCollection;
/**
* Generalized bulk loader for importing CSV files into Spanner.
*
*/
public class SpannerCSVLoader {
/**
* Command options specification.
*/
private interface Options extends PipelineOptions {
@Description("Create a sample database")
@Default.Boolean(false)
boolean isCreateDatabase();
void setCreateDatabase(boolean createDatabase);
@Description("File to read from ")
@Validation.Required
String getInput();
void setInput(String value);
@Description("Instance ID to write to in Spanner")
@Validation.Required
String getInstanceId();
void setInstanceId(String value);
@Description("Database ID to write to in Spanner")
@Validation.Required
String getDatabaseId();
void setDatabaseId(String value);
@Description("Table name")
@Validation.Required
String getTable();
void setTable(String value);
}
/**
* Constructs and executes the processing pipeline based upon command options.
*/
public static void main(String[] args) throws Exception {
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
Pipeline p = Pipeline.create(options);
PCollection<String> lines = p.apply(TextIO.Read.from(options.getInput()));
PCollection<Mutation> mutations = lines
.apply(ParDo.of(new NaiveParseCsvFn(options.getTable())));
mutations
.apply(SpannerIO.writeTo(options.getInstanceId(), options.getDatabaseId()));
p.run().waitUntilFinish();
}
public static void createDatabase(Options options) {
Spanner client = SpannerOptions.getDefaultInstance().getService();
DatabaseAdminClient databaseAdminClient = client.getDatabaseAdminClient();
try {
databaseAdminClient.dropDatabase(options.getInstanceId(), options
.getDatabaseId());
} catch (SpannerException e) {
// Does not exist, ignore.
}
Operation<Database, CreateDatabaseMetadata> op = databaseAdminClient.createDatabase(
options.getInstanceId(), options
.getDatabaseId(), Collections.singleton("CREATE TABLE " + options.getTable() + " ("
+ " Key INT64,"
+ " Name STRING,"
+ " Email STRING,"
+ " Age INT,"
+ ") PRIMARY KEY (Key)"));
op.waitFor();
}
/**
* A DoFn that creates a Spanner Mutation for each CSV line.
*/
static class NaiveParseCsvFn extends DoFn<String, Mutation> {
private final String table;
NaiveParseCsvFn(String table) {
this.table = table;
}
@ProcessElement
public void processElement(ProcessContext c) {
String line = c.element();
String[] elements = line.split(",");
if (elements.length != 4) {
return;
}
Mutation mutation = Mutation.newInsertOrUpdateBuilder(table)
.set("Key").to(Long.valueOf(elements[0]))
.set("Name").to(elements[1])
.set("Email").to(elements[2])
.set("Age").to(Integer.valueOf(elements[3]))
.build();
c.output(mutation);
}
}
}
|
Delete SpannerCSVLoader
This is not appropriate for examples. SpannerIO should be well-javadoced
and integration tested.
|
examples/java/src/main/java/org/apache/beam/examples/spanner/SpannerCSVLoader.java
|
Delete SpannerCSVLoader
|
||
Java
|
bsd-2-clause
|
6affac0c6ec2aec52471904002f0bb4221842398
| 0
|
carat-project/carat,carat-project/carat,carat-project/carat,carat-project/carat,carat-project/carat
|
package edu.berkeley.cs.amplab.carat.android.protocol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import com.flurry.android.FlurryAgent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import edu.berkeley.cs.amplab.carat.android.CaratApplication;
import edu.berkeley.cs.amplab.carat.android.Constants;
import edu.berkeley.cs.amplab.carat.android.R;
import edu.berkeley.cs.amplab.carat.android.sampling.SamplingLibrary;
import edu.berkeley.cs.amplab.carat.thrift.CaratService;
import edu.berkeley.cs.amplab.carat.thrift.Feature;
import edu.berkeley.cs.amplab.carat.thrift.HogBugReport;
import edu.berkeley.cs.amplab.carat.thrift.ProcessInfo;
import edu.berkeley.cs.amplab.carat.thrift.Registration;
import edu.berkeley.cs.amplab.carat.thrift.Reports;
import edu.berkeley.cs.amplab.carat.thrift.Sample;
public class CommunicationManager {
private static final String TAG = "CommsManager";
private static final String DAEMONS_URL = "http://carat.cs.berkeley.edu/daemons.txt";
private static final String QUESTIONNAIRE_URL = "http://www.cs.helsinki.fi/u/lagerspe/caratapp/questionnaire-url.txt";
private CaratApplication a = null;
private boolean registered = false;
private boolean register = true;
private boolean newuuid = false;
private boolean timeBasedUuid = false;
private SharedPreferences p = null;
public CommunicationManager(CaratApplication a) {
this.a = a;
p = PreferenceManager.getDefaultSharedPreferences(this.a);
/*
* Either: 1. Never registered -> register 2. registered, but no stored
* uuid -> register 3. registered, with stored uuid, but uuid, model or
* os are different -> register 4. registered, all fields equal to
* stored -> do not register
*/
timeBasedUuid = p.getBoolean(Constants.PREFERENCE_TIME_BASED_UUID, false);
newuuid = p.getBoolean(Constants.PREFERENCE_NEW_UUID, false);
registered = !p.getBoolean(Constants.PREFERENCE_FIRST_RUN, true);
register = !registered;
String storedUuid = p.getString(CaratApplication.getRegisteredUuid(), null);
if (!register) {
if (storedUuid == null)
register = true;
else {
String storedOs = p.getString(Constants.REGISTERED_OS, null);
String storedModel = p.getString(Constants.REGISTERED_MODEL, null);
String uuid = storedUuid;
String os = SamplingLibrary.getOsVersion();
String model = SamplingLibrary.getModel();
if (storedUuid == null || os == null || model == null || storedModel == null || storedOs == null
|| uuid == null || !(storedOs.equals(os) && storedModel.equals(model))) {
// need to re-reg
register = true;
} else
register = false;
}
}
}
private void registerMe(CaratService.Client instance, String uuId, String os, String model) throws TException {
if (uuId == null || os == null || model == null) {
Log.e("registerMe", "Null uuId, os, or model given to registerMe!");
System.exit(1);
return;
}
Registration registration = new Registration(uuId);
registration.setPlatformId(model);
registration.setSystemVersion(os);
registration.setTimestamp(System.currentTimeMillis() / 1000.0);
registration.setKernelVersion(SamplingLibrary.getKernelVersion());
registration.setSystemDistribution(SamplingLibrary.getManufacturer() + ";" + SamplingLibrary.getBrand());
FlurryAgent.logEvent("Registering " + uuId + "," + model + "," + os);
instance.registerMe(registration);
}
public int uploadSamples(Collection<Sample> samples) {
CaratService.Client instance = null;
int succeeded = 0;
ArrayList<Sample> samplesLeft = new ArrayList<Sample>();
registerLocal();
try {
instance = ProtocolClient.open(a.getApplicationContext());
registerOnFirstRun(instance);
for (Sample s : samples) {
boolean success = false;
try {
success = instance.uploadSample(s);
} catch (Throwable th) {
Log.e(TAG, "Error uploading sample.", th);
}
if (success)
succeeded++;
else
samplesLeft.add(s);
}
safeClose(instance);
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
// Do not try again. It can cause a massive sample attack on the server.
return succeeded;
}
private void registerLocal() {
if (register) {
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
if (uuId == null) {
if (registered && (!newuuid && !timeBasedUuid)) {
uuId = SamplingLibrary.getAndroidId(a);
} else if (registered && !timeBasedUuid) {
// "new" uuid
uuId = SamplingLibrary.getUuid(a);
} else {
// Time-based ID scheme
uuId = SamplingLibrary.getTimeBasedUuid(a);
Log.d("CommunicationManager", "Generated a new time-based UUID: " + uuId);
// This needs to be saved now, so that if server
// communication
// fails we have a stable UUID.
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putBoolean(Constants.PREFERENCE_TIME_BASED_UUID, true).commit();
timeBasedUuid = true;
}
}
}
}
private void registerOnFirstRun(CaratService.Client instance) {
if (register) {
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
// Only use new uuid if reg'd after this version for the first time.
if (registered && (!newuuid && !timeBasedUuid)) {
uuId = SamplingLibrary.getAndroidId(a);
} else if (registered && !timeBasedUuid) {
// "new" uuid
uuId = SamplingLibrary.getUuid(a);
} else {
// Time-based ID scheme
if (uuId == null)
uuId = SamplingLibrary.getTimeBasedUuid(a);
Log.d("CommunicationManager", "Generated a new time-based UUID: " + uuId);
// This needs to be saved now, so that if server communication
// fails we have a stable UUID.
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putBoolean(Constants.PREFERENCE_TIME_BASED_UUID, true).commit();
timeBasedUuid = true;
}
String os = SamplingLibrary.getOsVersion();
String model = SamplingLibrary.getModel();
Log.d("CommunicationManager", "First run, registering this device: " + uuId + ", " + os + ", " + model);
try {
registerMe(instance, uuId, os, model);
p.edit().putBoolean(Constants.PREFERENCE_FIRST_RUN, false).commit();
register = false;
registered = true;
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putString(Constants.REGISTERED_OS, os).commit();
p.edit().putString(Constants.REGISTERED_MODEL, model).commit();
} catch (TException e) {
Log.e("CommunicationManager", "Registration failed, will try again next time: " + e);
e.printStackTrace();
}
}
}
/**
* Used by UiRefreshThread which needs to know about exceptions.
*
* @throws TException
*/
public void refreshAllReports() {
registerLocal();
// Do not refresh if not connected
if (!SamplingLibrary.networkAvailable(a.getApplicationContext()))
return;
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return;
// Establish connection
if (register) {
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
registerOnFirstRun(instance);
safeClose(instance);
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
}
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
String model = SamplingLibrary.getModel();
String OS = SamplingLibrary.getOsVersion();
// NOTE: Fake data for simulator
if (model.equals("sdk")) {
uuId = "97c542cd8e99d948"; // My S3
model = "GT-I9300";
OS = "4.0.4";
}
Log.d(TAG, "Getting reports for " + uuId + " model=" + model + " os=" + OS);
FlurryAgent.logEvent("Getting reports for " + uuId + "," + model + "," + OS);
int progress = 0;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_my_device), false);
boolean success = refreshMainReports(uuId, OS, model);
if (success) {
progress += 20;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_bugs), false);
Log.d(TAG, "Successfully got main report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_my_device), true);
Log.d(TAG, "Failed getting main report");
}
success = refreshBugReports(uuId, model);
if (success) {
progress += 20;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_hogs), false);
Log.d(TAG, "Successfully got bug report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_bugs), true);
Log.d(TAG, "Failed getting bug report");
}
// success = refreshSettingsReports(uuId, model);
//
// if (success) {
// progress += 20;
// CaratApplication.setActionProgress(progress, a.getString(R.string.tab_hogs), false);
// Log.d(TAG, "Successfully got settings report");
// } else {
// CaratApplication.setActionProgress(progress, a.getString(R.string.tab_settings), true);
// Log.d(TAG, "Failed getting settings report");
// }
success = refreshHogReports(uuId, model);
boolean bl = true;
if (System.currentTimeMillis() - CaratApplication.storage.getBlacklistFreshness() < Constants.FRESHNESS_TIMEOUT_BLACKLIST)
bl = false;
if (success) {
progress += 40; // changed to 40
CaratApplication.setActionProgress(progress,
bl ? a.getString(R.string.blacklist) : a.getString(R.string.finishing), false);
Log.d(TAG, "Successfully got hog report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_hogs), true);
Log.d(TAG, "Failed getting hog report");
}
// NOTE: Check for having a J-Score, and in case there is none, send the
// new message
Reports r = CaratApplication.storage.getReports();
if (r == null || r.jScoreWith == null || r.jScoreWith.expectedValue <= 0) {
success = getQuickHogsAndMaybeRegister(uuId, OS, model);
if (success)
Log.d(TAG, "Got quickHogs.");
else
Log.d(TAG, "Failed getting GuickHogs.");
}
if (bl) {
refreshBlacklist();
refreshQuestionnaireLink();
}
CaratApplication.storage.writeFreshness();
Log.d(TAG, "Wrote freshness");
}
private boolean refreshMainReports(String uuid, String os, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
Reports r = instance.getReports(uuid, getFeatures("Model", model, "OS", os));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
Log.d("CommunicationManager.refreshMainReports()",
"got the main report (action list)" + ", model=" + r.getModel()
+ ", jscore=" + r.getJScore() + ". Storing the report in the databse");
CaratApplication.storage.writeReports(r);
} else {
Log.d("CommunicationManager.refreshMainReports()",
"the fetched MAIN report is null");
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
return false;
}
private boolean refreshBugReports(String uuid, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Bug", "Model", model));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeBugReport(r);
Log.d("CommunicationManager.refreshBugReports()",
"got the bug list: " + r.getHbList().toString());
} else {
Log.d("CommunicationManager.refreshBugReports()",
"the fetched bug report is null");
}
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing bug reports.", th);
safeClose(instance);
}
return false;
}
private boolean refreshHogReports(String uuid, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Hog", "Model", model));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeHogReport(r);
Log.d("CommunicationManager.refreshHogReports()",
"got the hog list: " + r.getHbList().toString());
} else {
Log.d("CommunicationManager.refreshHogReports()",
"the fetched hog report is null");
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing hog reports.", th);
safeClose(instance);
}
return false;
}
// private boolean refreshSettingsReports(String uuid, String model) {
// if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
// return false;
// CaratService.Client instance = null;
// try {
// instance = ProtocolClient.open(a.getApplicationContext());
// HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Settings", "Model", model));
//
// if (r != null) {
// CaratApplication.storage.writeSettingsReport(r);
// Log.d("CommunicationManager.refreshSettingsReports()",
// "got the settings list: " + r.getHbList().toString());
// } else {
// Log.d("CommunicationManager.refreshSettingsReports()",
// "the fetched settings report is null");
// }
// // Assume freshness written by caller.
// // s.writeFreshness();
// safeClose(instance);
// return true;
// } catch (Throwable th) {
// Log.e(TAG, "Error refreshing settings reports.", th);
// safeClose(instance);
// }
// return false;
// }
private void refreshBlacklist() {
// I/O, let's do it on the background.
new Thread() {
public void run() {
final List<String> blacklist = new ArrayList<String>();
final List<String> globlist = new ArrayList<String>();
try {
URL u = new URL(DAEMONS_URL);
URLConnection c = u.openConnection();
InputStream is = c.getInputStream();
if (is != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String s = rd.readLine();
while (s != null) {
// Optimization for android: Only add names that
// have a dot
// Does not work, since for example "system" has no
// dots.
blacklist.add(s);
if (s.endsWith("*") || s.startsWith("*"))
globlist.add(s);
s = rd.readLine();
}
rd.close();
Log.v(TAG, "Downloaded blacklist: " + blacklist);
Log.v(TAG, "Downloaded globlist: " + globlist);
CaratApplication.storage.writeBlacklist(blacklist);
// List of *something or something* expressions:
if (globlist.size() > 0)
CaratApplication.storage.writeGloblist(globlist);
}
} catch (Throwable th) {
Log.e(TAG, "Could not retrieve blacklist!", th);
}
// So we don't try again too often.
CaratApplication.storage.writeBlacklistFreshness();
}
}.start();
}
private void refreshQuestionnaireLink() {
// I/O, let's do it on the background.
new Thread() {
public void run() {
String s = null;
try {
URL u = new URL(QUESTIONNAIRE_URL);
URLConnection c = u.openConnection();
InputStream is = c.getInputStream();
if (is != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
s = rd.readLine();
rd.close();
if (s != null && s.length() > 7 && s.startsWith("http"))
CaratApplication.storage.writeQuestionnaireUrl(s);
else
CaratApplication.storage.writeQuestionnaireUrl(" ");
}
} catch (Throwable th) {
Log.e(TAG, "Could not retrieve blacklist!", th);
}
}
}.start();
}
private boolean getQuickHogsAndMaybeRegister(String uuid, String os, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getQuickHogsFreshness() < Constants.FRESHNESS_TIMEOUT_QUICKHOGS)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
Registration registration = new Registration(uuid);
registration.setPlatformId(model);
registration.setSystemVersion(os);
registration.setTimestamp(System.currentTimeMillis() / 1000.0);
List<ProcessInfo> pi = SamplingLibrary.getRunningAppInfo(a.getApplicationContext());
List<String> processList = new ArrayList<String>();
for (ProcessInfo p : pi)
processList.add(p.pName);
HogBugReport r = instance.getQuickHogsAndMaybeRegister(registration, processList);
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeHogReport(r);
CaratApplication.storage.writeQuickHogsFreshness();
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
return false;
}
public static void safeClose(CaratService.Client c) {
if (c == null)
return;
TProtocol i = c.getInputProtocol();
TProtocol o = c.getOutputProtocol();
if (i != null) {
TTransport it = i.getTransport();
if (it != null)
it.close();
}
if (o != null) {
TTransport it = o.getTransport();
if (it != null)
it.close();
}
}
private List<Feature> getFeatures(String key1, String val1, String key2, String val2) {
List<Feature> features = new ArrayList<Feature>();
if (key1 == null || val1 == null || key2 == null || val2 == null) {
Log.e("getFeatures", "Null key or value given to getFeatures!");
System.exit(1);
return features;
}
Feature feature = new Feature();
feature.setKey(key1);
feature.setValue(val1);
features.add(feature);
feature = new Feature();
feature.setKey(key2);
feature.setValue(val2);
features.add(feature);
return features;
}
}
|
app/android/src/edu/berkeley/cs/amplab/carat/android/protocol/CommunicationManager.java
|
package edu.berkeley.cs.amplab.carat.android.protocol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import com.flurry.android.FlurryAgent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import edu.berkeley.cs.amplab.carat.android.CaratApplication;
import edu.berkeley.cs.amplab.carat.android.Constants;
import edu.berkeley.cs.amplab.carat.android.R;
import edu.berkeley.cs.amplab.carat.android.sampling.SamplingLibrary;
import edu.berkeley.cs.amplab.carat.thrift.CaratService;
import edu.berkeley.cs.amplab.carat.thrift.Feature;
import edu.berkeley.cs.amplab.carat.thrift.HogBugReport;
import edu.berkeley.cs.amplab.carat.thrift.ProcessInfo;
import edu.berkeley.cs.amplab.carat.thrift.Registration;
import edu.berkeley.cs.amplab.carat.thrift.Reports;
import edu.berkeley.cs.amplab.carat.thrift.Sample;
public class CommunicationManager {
private static final String TAG = "CommsManager";
private static final String DAEMONS_URL = "http://carat.cs.berkeley.edu/daemons.txt";
private static final String QUESTIONNAIRE_URL = "http://www.cs.helsinki.fi/u/lagerspe/caratapp/questionnaire-url.txt";
private CaratApplication a = null;
private boolean registered = false;
private boolean register = true;
private boolean newuuid = false;
private boolean timeBasedUuid = false;
private SharedPreferences p = null;
public CommunicationManager(CaratApplication a) {
this.a = a;
p = PreferenceManager.getDefaultSharedPreferences(this.a);
/*
* Either: 1. Never registered -> register 2. registered, but no stored
* uuid -> register 3. registered, with stored uuid, but uuid, model or
* os are different -> register 4. registered, all fields equal to
* stored -> do not register
*/
timeBasedUuid = p.getBoolean(Constants.PREFERENCE_TIME_BASED_UUID, false);
newuuid = p.getBoolean(Constants.PREFERENCE_NEW_UUID, false);
registered = !p.getBoolean(Constants.PREFERENCE_FIRST_RUN, true);
register = !registered;
String storedUuid = p.getString(CaratApplication.getRegisteredUuid(), null);
if (!register) {
if (storedUuid == null)
register = true;
else {
String storedOs = p.getString(Constants.REGISTERED_OS, null);
String storedModel = p.getString(Constants.REGISTERED_MODEL, null);
String uuid = storedUuid;
String os = SamplingLibrary.getOsVersion();
String model = SamplingLibrary.getModel();
if (storedUuid == null || os == null || model == null || storedModel == null || storedOs == null
|| uuid == null || !(storedOs.equals(os) && storedModel.equals(model))) {
// need to re-reg
register = true;
} else
register = false;
}
}
}
private void registerMe(CaratService.Client instance, String uuId, String os, String model) throws TException {
if (uuId == null || os == null || model == null) {
Log.e("registerMe", "Null uuId, os, or model given to registerMe!");
System.exit(1);
return;
}
Registration registration = new Registration(uuId);
registration.setPlatformId(model);
registration.setSystemVersion(os);
registration.setTimestamp(System.currentTimeMillis() / 1000.0);
registration.setKernelVersion(SamplingLibrary.getKernelVersion());
registration.setSystemDistribution(SamplingLibrary.getManufacturer() + ";" + SamplingLibrary.getBrand());
FlurryAgent.logEvent("Registering " + uuId + "," + model + "," + os);
instance.registerMe(registration);
}
public int uploadSamples(Collection<Sample> samples) {
CaratService.Client instance = null;
int succeeded = 0;
ArrayList<Sample> samplesLeft = new ArrayList<Sample>();
registerLocal();
try {
instance = ProtocolClient.open(a.getApplicationContext());
registerOnFirstRun(instance);
for (Sample s : samples) {
boolean success = false;
try {
success = instance.uploadSample(s);
} catch (Throwable th) {
Log.e(TAG, "Error uploading sample.", th);
}
if (success)
succeeded++;
else
samplesLeft.add(s);
}
safeClose(instance);
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
// Do not try again. It can cause a massive sample attack on the server.
return succeeded;
}
private void registerLocal() {
if (register) {
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
if (uuId == null) {
if (registered && (!newuuid && !timeBasedUuid)) {
uuId = SamplingLibrary.getAndroidId(a);
} else if (registered && !timeBasedUuid) {
// "new" uuid
uuId = SamplingLibrary.getUuid(a);
} else {
// Time-based ID scheme
uuId = SamplingLibrary.getTimeBasedUuid(a);
Log.d("CommunicationManager", "Generated a new time-based UUID: " + uuId);
// This needs to be saved now, so that if server
// communication
// fails we have a stable UUID.
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putBoolean(Constants.PREFERENCE_TIME_BASED_UUID, true).commit();
timeBasedUuid = true;
}
}
}
}
private void registerOnFirstRun(CaratService.Client instance) {
if (register) {
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
// Only use new uuid if reg'd after this version for the first time.
if (registered && (!newuuid && !timeBasedUuid)) {
uuId = SamplingLibrary.getAndroidId(a);
} else if (registered && !timeBasedUuid) {
// "new" uuid
uuId = SamplingLibrary.getUuid(a);
} else {
// Time-based ID scheme
if (uuId == null)
uuId = SamplingLibrary.getTimeBasedUuid(a);
Log.d("CommunicationManager", "Generated a new time-based UUID: " + uuId);
// This needs to be saved now, so that if server communication
// fails we have a stable UUID.
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putBoolean(Constants.PREFERENCE_TIME_BASED_UUID, true).commit();
timeBasedUuid = true;
}
String os = SamplingLibrary.getOsVersion();
String model = SamplingLibrary.getModel();
Log.d("CommunicationManager", "First run, registering this device: " + uuId + ", " + os + ", " + model);
try {
registerMe(instance, uuId, os, model);
p.edit().putBoolean(Constants.PREFERENCE_FIRST_RUN, false).commit();
register = false;
registered = true;
p.edit().putString(CaratApplication.getRegisteredUuid(), uuId).commit();
p.edit().putString(Constants.REGISTERED_OS, os).commit();
p.edit().putString(Constants.REGISTERED_MODEL, model).commit();
} catch (TException e) {
Log.e("CommunicationManager", "Registration failed, will try again next time: " + e);
e.printStackTrace();
}
}
}
/**
* Used by UiRefreshThread which needs to know about exceptions.
*
* @throws TException
*/
public void refreshAllReports() {
registerLocal();
// Do not refresh if not connected
if (!SamplingLibrary.networkAvailable(a.getApplicationContext()))
return;
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return;
// Establish connection
if (register) {
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
registerOnFirstRun(instance);
safeClose(instance);
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
}
String uuId = p.getString(CaratApplication.getRegisteredUuid(), null);
String model = SamplingLibrary.getModel();
String OS = SamplingLibrary.getOsVersion();
// NOTE: Fake data for simulator
if (model.equals("sdk")) {
uuId = "97c542cd8e99d948"; // My S3
model = "GT-I9300";
OS = "4.0.4";
}
Log.d(TAG, "Getting reports for " + uuId + " model=" + model + " os=" + OS);
FlurryAgent.logEvent("Getting reports for " + uuId + "," + model + "," + OS);
int progress = 0;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_my_device), false);
boolean success = refreshMainReports(uuId, OS, model);
if (success) {
progress += 20;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_bugs), false);
Log.d(TAG, "Successfully got main report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_my_device), true);
Log.d(TAG, "Failed getting main report");
}
success = refreshBugReports(uuId, model);
if (success) {
progress += 20;
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_settings), false);
Log.d(TAG, "Successfully got bug report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_bugs), true);
Log.d(TAG, "Failed getting bug report");
}
// success = refreshSettingsReports(uuId, model);
//
// if (success) {
// progress += 20;
// CaratApplication.setActionProgress(progress, a.getString(R.string.tab_hogs), false);
// Log.d(TAG, "Successfully got settings report");
// } else {
// CaratApplication.setActionProgress(progress, a.getString(R.string.tab_settings), true);
// Log.d(TAG, "Failed getting settings report");
// }
success = refreshHogReports(uuId, model);
boolean bl = true;
if (System.currentTimeMillis() - CaratApplication.storage.getBlacklistFreshness() < Constants.FRESHNESS_TIMEOUT_BLACKLIST)
bl = false;
if (success) {
progress += 40; // changed to 40
CaratApplication.setActionProgress(progress,
bl ? a.getString(R.string.blacklist) : a.getString(R.string.finishing), false);
Log.d(TAG, "Successfully got hog report");
} else {
CaratApplication.setActionProgress(progress, a.getString(R.string.tab_hogs), true);
Log.d(TAG, "Failed getting hog report");
}
// NOTE: Check for having a J-Score, and in case there is none, send the
// new message
Reports r = CaratApplication.storage.getReports();
if (r == null || r.jScoreWith == null || r.jScoreWith.expectedValue <= 0) {
success = getQuickHogsAndMaybeRegister(uuId, OS, model);
if (success)
Log.d(TAG, "Got quickHogs.");
else
Log.d(TAG, "Failed getting GuickHogs.");
}
if (bl) {
refreshBlacklist();
refreshQuestionnaireLink();
}
CaratApplication.storage.writeFreshness();
Log.d(TAG, "Wrote freshness");
}
private boolean refreshMainReports(String uuid, String os, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
Reports r = instance.getReports(uuid, getFeatures("Model", model, "OS", os));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
Log.d("CommunicationManager.refreshMainReports()",
"got the main report (action list)" + ", model=" + r.getModel()
+ ", jscore=" + r.getJScore() + ". Storing the report in the databse");
CaratApplication.storage.writeReports(r);
} else {
Log.d("CommunicationManager.refreshMainReports()",
"the fetched MAIN report is null");
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
return false;
}
private boolean refreshBugReports(String uuid, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Bug", "Model", model));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeBugReport(r);
Log.d("CommunicationManager.refreshBugReports()",
"got the bug list: " + r.getHbList().toString());
} else {
Log.d("CommunicationManager.refreshBugReports()",
"the fetched bug report is null");
}
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing bug reports.", th);
safeClose(instance);
}
return false;
}
private boolean refreshHogReports(String uuid, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Hog", "Model", model));
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeHogReport(r);
Log.d("CommunicationManager.refreshHogReports()",
"got the hog list: " + r.getHbList().toString());
} else {
Log.d("CommunicationManager.refreshHogReports()",
"the fetched hog report is null");
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing hog reports.", th);
safeClose(instance);
}
return false;
}
// private boolean refreshSettingsReports(String uuid, String model) {
// if (System.currentTimeMillis() - CaratApplication.storage.getFreshness() < Constants.FRESHNESS_TIMEOUT)
// return false;
// CaratService.Client instance = null;
// try {
// instance = ProtocolClient.open(a.getApplicationContext());
// HogBugReport r = instance.getHogOrBugReport(uuid, getFeatures("ReportType", "Settings", "Model", model));
//
// if (r != null) {
// CaratApplication.storage.writeSettingsReport(r);
// Log.d("CommunicationManager.refreshSettingsReports()",
// "got the settings list: " + r.getHbList().toString());
// } else {
// Log.d("CommunicationManager.refreshSettingsReports()",
// "the fetched settings report is null");
// }
// // Assume freshness written by caller.
// // s.writeFreshness();
// safeClose(instance);
// return true;
// } catch (Throwable th) {
// Log.e(TAG, "Error refreshing settings reports.", th);
// safeClose(instance);
// }
// return false;
// }
private void refreshBlacklist() {
// I/O, let's do it on the background.
new Thread() {
public void run() {
final List<String> blacklist = new ArrayList<String>();
final List<String> globlist = new ArrayList<String>();
try {
URL u = new URL(DAEMONS_URL);
URLConnection c = u.openConnection();
InputStream is = c.getInputStream();
if (is != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String s = rd.readLine();
while (s != null) {
// Optimization for android: Only add names that
// have a dot
// Does not work, since for example "system" has no
// dots.
blacklist.add(s);
if (s.endsWith("*") || s.startsWith("*"))
globlist.add(s);
s = rd.readLine();
}
rd.close();
Log.v(TAG, "Downloaded blacklist: " + blacklist);
Log.v(TAG, "Downloaded globlist: " + globlist);
CaratApplication.storage.writeBlacklist(blacklist);
// List of *something or something* expressions:
if (globlist.size() > 0)
CaratApplication.storage.writeGloblist(globlist);
}
} catch (Throwable th) {
Log.e(TAG, "Could not retrieve blacklist!", th);
}
// So we don't try again too often.
CaratApplication.storage.writeBlacklistFreshness();
}
}.start();
}
private void refreshQuestionnaireLink() {
// I/O, let's do it on the background.
new Thread() {
public void run() {
String s = null;
try {
URL u = new URL(QUESTIONNAIRE_URL);
URLConnection c = u.openConnection();
InputStream is = c.getInputStream();
if (is != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
s = rd.readLine();
rd.close();
if (s != null && s.length() > 7 && s.startsWith("http"))
CaratApplication.storage.writeQuestionnaireUrl(s);
else
CaratApplication.storage.writeQuestionnaireUrl(" ");
}
} catch (Throwable th) {
Log.e(TAG, "Could not retrieve blacklist!", th);
}
}
}.start();
}
private boolean getQuickHogsAndMaybeRegister(String uuid, String os, String model) {
if (System.currentTimeMillis() - CaratApplication.storage.getQuickHogsFreshness() < Constants.FRESHNESS_TIMEOUT_QUICKHOGS)
return false;
CaratService.Client instance = null;
try {
instance = ProtocolClient.open(a.getApplicationContext());
Registration registration = new Registration(uuid);
registration.setPlatformId(model);
registration.setSystemVersion(os);
registration.setTimestamp(System.currentTimeMillis() / 1000.0);
List<ProcessInfo> pi = SamplingLibrary.getRunningAppInfo(a.getApplicationContext());
List<String> processList = new ArrayList<String>();
for (ProcessInfo p : pi)
processList.add(p.pName);
HogBugReport r = instance.getQuickHogsAndMaybeRegister(registration, processList);
// Assume multiple invocations, do not close
// ProtocolClient.close();
if (r != null) {
CaratApplication.storage.writeHogReport(r);
CaratApplication.storage.writeQuickHogsFreshness();
}
// Assume freshness written by caller.
// s.writeFreshness();
safeClose(instance);
return true;
} catch (Throwable th) {
Log.e(TAG, "Error refreshing main reports.", th);
safeClose(instance);
}
return false;
}
public static void safeClose(CaratService.Client c) {
if (c == null)
return;
TProtocol i = c.getInputProtocol();
TProtocol o = c.getOutputProtocol();
if (i != null) {
TTransport it = i.getTransport();
if (it != null)
it.close();
}
if (o != null) {
TTransport it = o.getTransport();
if (it != null)
it.close();
}
}
private List<Feature> getFeatures(String key1, String val1, String key2, String val2) {
List<Feature> features = new ArrayList<Feature>();
if (key1 == null || val1 == null || key2 == null || val2 == null) {
Log.e("getFeatures", "Null key or value given to getFeatures!");
System.exit(1);
return features;
}
Feature feature = new Feature();
feature.setKey(key1);
feature.setValue(val1);
features.add(feature);
feature = new Feature();
feature.setKey(key2);
feature.setValue(val2);
features.add(feature);
return features;
}
}
|
changed the incorrect message when refreshing the reports
|
app/android/src/edu/berkeley/cs/amplab/carat/android/protocol/CommunicationManager.java
|
changed the incorrect message when refreshing the reports
|
|
Java
|
mit
|
7bef3a54ba625d7135dfc3ce94bf2b46973a36e2
| 0
|
Lothy/elysium-single-threaded
|
package org.moparscape.elysium;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.moparscape.elysium.net.Session;
import org.moparscape.elysium.net.codec.ElysiumPipelineFactory;
import org.moparscape.elysium.task.SessionPulseTask;
import org.moparscape.elysium.util.SplittableCopyOnWriteArrayList;
import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by IntelliJ IDEA.
*
* @author lothy
*/
public class Server {
private static final Server INSTANCE;
private static final int TASK_THREADS = 4;
private final ExecutorService nettyBossService = Executors.newSingleThreadExecutor();
private final ExecutorService nettyWorkerService = Executors.newFixedThreadPool(2);
private final ScheduledExecutorService taskExecutorService = Executors.newScheduledThreadPool(TASK_THREADS);
private final ExecutorService dataExecutorService = Executors.newSingleThreadExecutor();
private final SplittableCopyOnWriteArrayList<Session> sessions = new SplittableCopyOnWriteArrayList<Session>(1500);
private final ServerBootstrap bootstrap;
private volatile long timestamp = System.nanoTime() / 1000000;
private volatile long lastPulse = 0L;
private volatile boolean running = false;
static {
INSTANCE = new Server();
}
private Server() {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("CPU cores: " + cores);
this.bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(nettyBossService, nettyWorkerService));
this.bootstrap.setPipelineFactory(new ElysiumPipelineFactory());
this.bootstrap.bind(new InetSocketAddress(43594));
}
private void gameLoop() {
System.out.println("Game loop started");
ParentLoop:
while (true) {
try {
while (running) {
// Update the cached timestamp, and see if more than 600ms have passed
// If 600ms have passed then do another update; otherwise, sleep and try again
timestamp = (System.nanoTime() / 1000000);
if (timestamp - lastPulse < 600) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.err.println("Error occurred while sleeping between game pulses");
}
continue;
}
pulseSessions(); // This function blocks until all sessions have finished
processEvents(); // This function blocks until all events have been processed
processClients(); // This function blocks until all updating has finished
// Update the time that the last pulse took place before finishing
lastPulse = timestamp;
}
// If we reach this point then shutdown has been triggered.
// Break out of the parent loop so that the application can cleanup and shut down
break ParentLoop;
} catch (Exception e) {
System.out.println("Game loop exception: " + e.getCause());
}
}
// TODO: Implement shutdown procedure and cleanup here
}
private void pulseSessions() throws ExecutionException, InterruptedException {
// Allow each Session to handle its packet queue
List<Iterable<Session>> sessionPartitions = sessions.divide(TASK_THREADS);
List<SessionPulseTask> sessionPulseTasks = new LinkedList<SessionPulseTask>();
for (Iterable<Session> s : sessionPartitions) {
sessionPulseTasks.add(new SessionPulseTask(s));
}
// By calling get() on each of the futures that were returned, we block until
// all of the sessions have finished processing their packet queues.
List<Future<Void>> futureList = taskExecutorService.invokeAll(sessionPulseTasks);
for (Future<Void> f : futureList) {
f.get();
}
}
private void processEvents() {
}
private void processClients() {
}
public long getTimestamp() {
return timestamp;
}
public void registerSession(Session session) {
sessions.add(session);
}
public void unregisterSession(Session session) {
sessions.remove(session);
}
public Future<?> submitTask(Runnable r) {
return taskExecutorService.submit(r);
}
public void shutdown() {
running = false;
}
private void shutdown0() {
// Shut the executors down so that the program can exit
}
public static Server getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Server server = Server.getInstance();
System.out.println("Server has started. :)");
// Enter the game loop, and stay there until shutdown
server.gameLoop();
}
}
|
src/org/moparscape/elysium/Server.java
|
package org.moparscape.elysium;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.moparscape.elysium.net.Session;
import org.moparscape.elysium.net.codec.ElysiumPipelineFactory;
import org.moparscape.elysium.task.SessionPulseTask;
import org.moparscape.elysium.util.SplittableCopyOnWriteArrayList;
import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by IntelliJ IDEA.
*
* @author lothy
*/
public class Server {
private static final Server INSTANCE;
private static final int TASK_THREADS = 4;
private final ExecutorService nettyBossService = Executors.newFixedThreadPool(1);
private final ExecutorService nettyWorkerService = Executors.newFixedThreadPool(2);
private final ScheduledExecutorService taskExecutorService = Executors.newScheduledThreadPool(TASK_THREADS);
private final ExecutorService dataExecutorService = Executors.newFixedThreadPool(1);
private final SplittableCopyOnWriteArrayList<Session> sessions = new SplittableCopyOnWriteArrayList<Session>(1500);
private final ServerBootstrap bootstrap;
private volatile long timestamp = System.nanoTime() / 1000000;
private volatile long lastPulse = 0L;
private volatile boolean running = false;
static {
INSTANCE = new Server();
}
private Server() {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("CPU cores: " + cores);
this.bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(nettyBossService, nettyWorkerService));
this.bootstrap.setPipelineFactory(new ElysiumPipelineFactory());
this.bootstrap.bind(new InetSocketAddress(43594));
}
private void gameLoop() {
System.out.println("Game loop started");
while (true) {
try {
while (running) {
// Update the cached timestamp, and see if more than 600ms have passed
// If 600ms have passed then do another update; otherwise, sleep and try again
timestamp = (System.nanoTime() / 1000000);
if (timestamp - lastPulse < 600) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.err.println("Error occurred while sleeping between game pulses");
}
continue;
}
pulseSessions(); // This function blocks until all sessions have finished
processEvents(); // This function blocks until all events have been processed
processClients(); // This function blocks until all updating has finished
// Update the time that the last pulse took place before finishing
lastPulse = timestamp;
}
} catch (Exception e) {
System.out.println("Game loop exception: " + e.getCause());
}
}
}
private void pulseSessions() throws ExecutionException, InterruptedException {
// Allow each Session to handle its packet queue
List<Iterable<Session>> sessionPartitions = sessions.divide(TASK_THREADS);
List<SessionPulseTask> sessionPulseTasks = new LinkedList<SessionPulseTask>();
for (Iterable<Session> s : sessionPartitions) {
sessionPulseTasks.add(new SessionPulseTask(s));
}
// By calling get() on each of the futures that were returned, we block until
// all of the sessions have finished processing their packet queues.
List<Future<Void>> futureList = taskExecutorService.invokeAll(sessionPulseTasks);
for (Future<Void> f : futureList) {
f.get();
}
}
private void processEvents() {
}
private void processClients() {
}
public long getTimestamp() {
return timestamp;
}
public void registerSession(Session session) {
sessions.add(session);
}
public void unregisterSession(Session session) {
sessions.remove(session);
}
public Future<?> submitTask(Runnable r) {
return taskExecutorService.submit(r);
}
public void shutdown() {
running = false;
}
private void shutdown0() {
// Shut the executors down so that the program can exit
}
public static Server getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Server server = Server.getInstance();
System.out.println("Server has started. :)");
// Enter the game loop, and stay there until shutdown
server.gameLoop();
}
}
|
Gave outer loop in gameLoop method a label, and gameLoop will now break out of the outer loop if running is false -- previously it would remain in an infinite loop that just didn't execute the game pulse code.
|
src/org/moparscape/elysium/Server.java
|
Gave outer loop in gameLoop method a label, and gameLoop will now break out of the outer loop if running is false -- previously it would remain in an infinite loop that just didn't execute the game pulse code.
|
|
Java
|
mit
|
c8f65ea745ae429a55a7bbde5c3cb687cb3d0d41
| 0
|
RMRobotics/FTC_5421_2015-2016,RMRobotics/FTC_5421_2015-2016
|
package com.qualcomm.ftcrobotcontroller;
import java.util.Calendar;
/**
* Created by Simon on 12/31/2015.
*/
public class AutoState extends RMOpMode {
private String state = "begin"
@Override
public void init() {
super.init();
}
public void calculate() {
while (state != "end") {
switch (state) {
case "begin":
state = "center";
case "center":
System.out.println("Moving forward");
motorMap.get("DriveLeftOne").setDesiredPower(1.0);
motorMap.get("DriveLeftTwo").setDesiredPower(1.0);
motorMap.get("DriveRightOne").setDesiredPower(1.0);
motorMap.get("DriveRightTwo").setDesiredPower(1.0);
state = STATE2;
if (someQuitCheck == true) state = QUIT;
break;
case STATE2:
System.out.println("Doing Task 2");
/* Check conditions and possibly modify state */
state = STATE1;
if (someQuitCheck == true) state = QUIT;
break;
default:
break;
} // end switch
} // end while
}
}
|
FtcRobotController/src/main/java/com/qualcomm/ftcrobotcontroller/AutoState.java
|
package com.qualcomm.ftcrobotcontroller;
import java.util.Calendar;
/**
* Created by Simon on 12/31/2015.
*/
public class AutoState extends RMOpMode {
final int END = 0;
final int MOVEFORWARD = 1;
final int MOVEBACKWARD = 2;
final int TURNLEFT = 3;
final int TURNRIGHT = 4;
final int WAIT = 5;
@Override
public void init() {
super.init();
}
public void calculate() {
int state = 5;
while (state != END) {
switch (state) {
case MOVEFORWARD:
System.out.println("Moving forward");
motorMap.get("DriveLeftOne").setDesiredPower(1.0);
motorMap.get("DriveLeftTwo").setDesiredPower(1.0);
motorMap.get("DriveRightOne").setDesiredPower(1.0);
motorMap.get("DriveRightTwo").setDesiredPower(1.0);
state = STATE2;
if (someQuitCheck == true) state = QUIT;
break;
case STATE2:
System.out.println("Doing Task 2");
/* Check conditions and possibly modify state */
state = STATE1;
if (someQuitCheck == true) state = QUIT;
break;
default:
break;
} // end switch
} // end while
}
}
|
Add string case
|
FtcRobotController/src/main/java/com/qualcomm/ftcrobotcontroller/AutoState.java
|
Add string case
|
|
Java
|
mit
|
c7b4ced7ed65981b918e715b374f0ee51953e80a
| 0
|
AMarones/Brazilian-Commons
|
package br.com.m4u.commons.brazilian.library.components.editext;
import android.content.Context;
import android.util.AttributeSet;
import br.com.m4u.commons.brazilian.library.Constants;
import br.com.m4u.commons.brazilian.library.watchers.DocumentTextWatcher;
import br.com.m4u.commons.brazilian.library.watchers.PhoneTextWatcher;
import br.com.m4u.commons.brazilian.library.watchers.TypeWatcher;
/**
* Created by Alexandre on 05/03/15.
*/
public class BrazilianEditText extends android.widget.EditText {
/**
* XML Attribute
*/
private static final String EDITTEXT_ATTRIBUTE_TEXT_WATCHER = "textWatcher";
public BrazilianEditText(Context context) {
super(context);
}
public BrazilianEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setTextWatcher(context, attrs);
}
public BrazilianEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTextWatcher(context, attrs);
}
/**
* XML methods
*
* @param ctx
* @param attrs
*/
private void setTextWatcher(Context ctx, AttributeSet attrs) {
String stringTextWatcher = attrs.getAttributeValue(Constants.URL_SCHEMA,
EDITTEXT_ATTRIBUTE_TEXT_WATCHER);
if (stringTextWatcher.equalsIgnoreCase("cpf")) {
addTextChangedListener(new DocumentTextWatcher(this, TypeWatcher.CPF));
}
if (stringTextWatcher.equalsIgnoreCase("phone")) {
addTextChangedListener(new PhoneTextWatcher(this));
}
}
public String getTextValueNumber() {
String stringWithoutMask = this.getText().toString();
stringWithoutMask = stringWithoutMask.replaceAll("[^0-9]", "");
return stringWithoutMask;
}
}
|
library/src/main/java/br/com/m4u/commons/brazilian/library/components/editext/BrazilianEditText.java
|
package br.com.m4u.commons.brazilian.library.components.editext;
import android.content.Context;
import android.util.AttributeSet;
import br.com.m4u.commons.brazilian.library.Constants;
import br.com.m4u.commons.brazilian.library.watchers.DocumentTextWatcher;
import br.com.m4u.commons.brazilian.library.watchers.PhoneTextWatcher;
import br.com.m4u.commons.brazilian.library.watchers.TypeWatcher;
/**
* Created by Alexandre on 05/03/15.
*/
public class BrazilianEditText extends android.widget.EditText {
/**
* XML Attribute
*/
private static final String EDITTEXT_ATTRIBUTE_TEXT_WATCHER = "textWatcher";
public BrazilianEditText(Context context) {
super(context);
}
public BrazilianEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setTextWatcher(context, attrs);
}
public BrazilianEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTextWatcher(context, attrs);
}
/**
* XML methods
*
* @param ctx
* @param attrs
*/
private void setTextWatcher(Context ctx, AttributeSet attrs) {
String stringTextWatcher = attrs.getAttributeValue(Constants.URL_SCHEMA,
EDITTEXT_ATTRIBUTE_TEXT_WATCHER);
if (stringTextWatcher.equalsIgnoreCase("cpf")) {
addTextChangedListener(new DocumentTextWatcher(this, TypeWatcher.CPF));
}
if (stringTextWatcher.equalsIgnoreCase("phone")) {
addTextChangedListener(new PhoneTextWatcher(this));
}
}
}
|
creating new method to get text value number (without mak)
|
library/src/main/java/br/com/m4u/commons/brazilian/library/components/editext/BrazilianEditText.java
|
creating new method to get text value number (without mak)
|
|
Java
|
mit
|
bedd5dd5848a38557e9d9e806fd38295c22e3189
| 0
|
BloodWorkXGaming/ExNihiloCreatio,BloodWorkXGaming/ExNihiloCreatio
|
package exnihilocreatio.compatibility.jei.crucible;
import exnihilocreatio.ModBlocks;
import exnihilocreatio.blocks.BlockCrucibleStone;
import exnihilocreatio.util.BlockInfo;
import exnihilocreatio.util.RenderTickCounter;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.fluids.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// Credit goes to >>>> https://github.com/thraaawn/CompactMachines/blob/1.12.1/src/main/java/org/dave/compactmachines3/jei/MultiblockRecipeWrapper.java
public class HeatSourcesRecipe implements IRecipeWrapper {
private final List<ItemStack> inputs;
private final BlockInfo blockInfo;
private final String heatAmountString;
public HeatSourcesRecipe(BlockInfo blockInfo, int heatAmount) {
this.blockInfo = blockInfo;
ItemStack item = blockInfo.getItemStack();
if (item.isEmpty()) {
Fluid fluid = null;
Block block = blockInfo.getBlock();
if (block instanceof IFluidBlock) {
fluid = ((IFluidBlock) block).getFluid();
}
if (block == Blocks.LAVA || block == Blocks.FLOWING_LAVA) {
fluid = FluidRegistry.LAVA;
}
if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) {
fluid = FluidRegistry.WATER;
}
if (fluid != null) {
item = FluidUtil.getFilledBucket(new FluidStack(fluid, 1000));
}
if (block == Blocks.FIRE) {
item = new ItemStack(Items.FLINT_AND_STEEL, 1);
}
}
inputs = new ArrayList<>(Collections.singleton(item));
heatAmountString = String.valueOf(heatAmount) + "x";
}
@Override
public void getIngredients(IIngredients ingredients) {
ingredients.setInputs(ItemStack.class, inputs);
}
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) {
minecraft.fontRenderer.drawString(heatAmountString, 24, 12, Color.gray.getRGB());
// int reqX = (int) Math.ceil((float)(maxPos.getX() - minPos.getX() +2) / 2.0f);
// int reqZ = (int) Math.ceil((float)(maxPos.getZ() - minPos.getZ() +2) / 2.0f);
GlStateManager.pushMatrix();
GlStateManager.translate(0F, 0F, 216.5F);
// minecraft.fontRenderer.drawString(recipe.getDimensionsString(), 153-mc.fontRenderer.getStringWidth(recipe.getDimensionsString()), 19 * 5 + 10, 0x444444);
GlStateManager.popMatrix();
float angle = RenderTickCounter.renderTicks * 45.0f / 128.0f;
// When we want to render translucent blocks we might need this
BlockRendererDispatcher blockrendererdispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher();
// Init GlStateManager
TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();
textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
textureManager.getTexture(TextureMap.LOCATION_BLOCKS_TEXTURE).setBlurMipmap(false, false);
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
GlStateManager.enableAlpha();
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.1f);
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
GlStateManager.disableFog();
GlStateManager.disableLighting();
RenderHelper.disableStandardItemLighting();
GlStateManager.enableBlend();
GlStateManager.enableCull();
GlStateManager.enableAlpha();
if (Minecraft.isAmbientOcclusionEnabled()) {
GlStateManager.shadeModel(7425);
} else {
GlStateManager.shadeModel(7424);
}
GlStateManager.pushMatrix();
// Center on recipe area
GlStateManager.translate(70, 30, 20);
// Shift it a bit down so one can properly see 3d
GlStateManager.rotate(-25.0f, 1.0f, 0.0f, 0.0f);
// Rotate per our calculated time
GlStateManager.rotate(angle, 0.0f, 1.0f, 0.0f);
// Scale down to gui scale
GlStateManager.scale(16.0f, -16.0f, 16.0f);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.setTranslation(-.5, 0, -.5);
GlStateManager.enableCull();
IBlockState crucible = ModBlocks.crucibleStone.getDefaultState().withProperty(BlockCrucibleStone.FIRED, true);
IBlockState state = blockInfo.getBlock().getDefaultState();
BlockPos pos = new BlockPos(0, 0, 0);
/*if (blockInfo.getBlock() instanceof IFluidBlock || blockInfo.getBlock() instanceof BlockLiquid) {
pos = pos.up();
}*/
// Aaaand render
buffer.begin(7, DefaultVertexFormats.BLOCK);
GlStateManager.disableAlpha();
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.SOLID, crucible, new BlockPos(0, 1, 0), minecraft.world);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.SOLID, state, pos, minecraft.world);
GlStateManager.enableAlpha();
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.CUTOUT_MIPPED, state, pos, minecraft.world);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.CUTOUT, state, pos, minecraft.world);
GlStateManager.shadeModel(7425);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.TRANSLUCENT, state, pos, minecraft.world);
tessellator.draw();
buffer.setTranslation(0, 0, 0);
GlStateManager.popMatrix();
}
@SideOnly(Side.CLIENT)
public void renderBlock(BlockRendererDispatcher blockrendererdispatcher, BufferBuilder buffer, BlockRenderLayer renderLayer, IBlockState blockState, BlockPos pos, IBlockAccess access) {
if (!blockState.getBlock().canRenderInLayer(blockState, renderLayer)) {
return;
}
ForgeHooksClient.setRenderLayer(renderLayer);
try {
blockrendererdispatcher.renderBlock(blockState, pos, access, buffer);
} catch (Exception e) {
e.printStackTrace();
}
ForgeHooksClient.setRenderLayer(null);
}
}
|
src/main/java/exnihilocreatio/compatibility/jei/crucible/HeatSourcesRecipe.java
|
package exnihilocreatio.compatibility.jei.crucible;
import exnihilocreatio.ModBlocks;
import exnihilocreatio.blocks.BlockCrucibleStone;
import exnihilocreatio.util.BlockInfo;
import exnihilocreatio.util.RenderTickCounter;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.fluids.*;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// Credit goes to >>>> https://github.com/thraaawn/CompactMachines/blob/1.12.1/src/main/java/org/dave/compactmachines3/jei/MultiblockRecipeWrapper.java
public class HeatSourcesRecipe implements IRecipeWrapper {
private final List<ItemStack> inputs;
private final BlockInfo blockInfo;
private final String heatAmountString;
public HeatSourcesRecipe(BlockInfo blockInfo, int heatAmount) {
this.blockInfo = blockInfo;
ItemStack item = blockInfo.getItemStack();
if (item.isEmpty()) {
Fluid fluid = null;
Block block = blockInfo.getBlock();
if (block instanceof IFluidBlock) {
fluid = ((IFluidBlock) block).getFluid();
}
if (block == Blocks.LAVA || block == Blocks.FLOWING_LAVA) {
fluid = FluidRegistry.LAVA;
}
if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) {
fluid = FluidRegistry.WATER;
}
if (fluid != null) {
item = FluidUtil.getFilledBucket(new FluidStack(fluid, 1000));
}
if (block == Blocks.FIRE) {
item = new ItemStack(Items.FLINT_AND_STEEL, 1);
}
}
inputs = new ArrayList<>(Collections.singleton(item));
heatAmountString = String.valueOf(heatAmount) + "x";
}
@Override
public void getIngredients(IIngredients ingredients) {
ingredients.setInputs(ItemStack.class, inputs);
}
@Override
@SideOnly(Side.CLIENT)
public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) {
minecraft.fontRenderer.drawString(heatAmountString, 24, 12, Color.gray.getRGB());
// int reqX = (int) Math.ceil((float)(maxPos.getX() - minPos.getX() +2) / 2.0f);
// int reqZ = (int) Math.ceil((float)(maxPos.getZ() - minPos.getZ() +2) / 2.0f);
GlStateManager.pushMatrix();
GlStateManager.translate(0F, 0F, 216.5F);
// minecraft.fontRenderer.drawString(recipe.getDimensionsString(), 153-mc.fontRenderer.getStringWidth(recipe.getDimensionsString()), 19 * 5 + 10, 0x444444);
GlStateManager.popMatrix();
float angle = RenderTickCounter.renderTicks * 45.0f / 128.0f;
// When we want to render translucent blocks we might need this
BlockRendererDispatcher blockrendererdispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher();
// Init GlStateManager
TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();
textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
textureManager.getTexture(TextureMap.LOCATION_BLOCKS_TEXTURE).setBlurMipmap(false, false);
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
GlStateManager.enableAlpha();
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.1f);
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
GlStateManager.disableFog();
GlStateManager.disableLighting();
RenderHelper.disableStandardItemLighting();
GlStateManager.enableBlend();
GlStateManager.enableCull();
GlStateManager.enableAlpha();
if (Minecraft.isAmbientOcclusionEnabled()) {
GlStateManager.shadeModel(7425);
} else {
GlStateManager.shadeModel(7424);
}
GlStateManager.pushMatrix();
// Center on recipe area
GlStateManager.translate(70, 30, 20);
// Shift it a bit down so one can properly see 3d
GlStateManager.rotate(-25.0f, 1.0f, 0.0f, 0.0f);
// Rotate per our calculated time
GlStateManager.rotate(angle, 0.0f, 1.0f, 0.0f);
// Scale down to gui scale
GlStateManager.scale(16.0f, -16.0f, 16.0f);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.setTranslation(-.5, 0, -.5);
GlStateManager.enableCull();
IBlockState crucible = ModBlocks.crucibleStone.getDefaultState().withProperty(BlockCrucibleStone.FIRED, true);
IBlockState state = blockInfo.getBlock().getDefaultState();
BlockPos pos = new BlockPos(0, 0, 0);
// Aaaand render
buffer.begin(7, DefaultVertexFormats.BLOCK);
GlStateManager.disableAlpha();
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.SOLID, crucible, new BlockPos(0, 1, 0), minecraft.world);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.SOLID, state, pos, minecraft.world);
GlStateManager.enableAlpha();
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.CUTOUT_MIPPED, state, pos, minecraft.world);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.CUTOUT, state, pos, minecraft.world);
GlStateManager.shadeModel(7425);
this.renderBlock(blockrendererdispatcher, buffer, BlockRenderLayer.TRANSLUCENT, state, pos, minecraft.world);
tessellator.draw();
buffer.setTranslation(0, 0, 0);
GlStateManager.popMatrix();
}
@SideOnly(Side.CLIENT)
public void renderBlock(BlockRendererDispatcher blockrendererdispatcher, BufferBuilder buffer, BlockRenderLayer renderLayer, IBlockState blockState, BlockPos pos, IBlockAccess access) {
if (!blockState.getBlock().canRenderInLayer(blockState, renderLayer)) {
return;
}
ForgeHooksClient.setRenderLayer(renderLayer);
try {
blockrendererdispatcher.renderBlock(blockState, pos, access, buffer);
} catch (Exception e) {
e.printStackTrace();
}
ForgeHooksClient.setRenderLayer(null);
}
}
|
somehow sides of fluid is not rendering....
|
src/main/java/exnihilocreatio/compatibility/jei/crucible/HeatSourcesRecipe.java
|
somehow sides of fluid is not rendering....
|
|
Java
|
mit
|
4d339017628ecc31ecc87873f11d5f87c7a24862
| 0
|
CyclopsMC/IntegratedTunnels
|
package org.cyclops.integratedtunnels.part.aspect.operator;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.Direction;
import net.minecraftforge.common.capabilities.Capability;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeItemStack;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypeLong;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
import org.cyclops.integratedtunnels.capability.network.ItemNetworkConfig;
import org.cyclops.integrateddynamics.core.evaluate.operator.OperatorBase.SafeVariablesGetter;
/**
* @author rubensworks
*/
public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
public PositionedOperatorIngredientIndexItem() {
this(null, Direction.NORTH, -1);
}
public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
}
@Override
protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
return ItemNetworkConfig.CAPABILITY;
}
public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
@Override
public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
.map(index -> index.getQuantity(itemStack.getRawValue()))
.orElse(0L));
}
}
}
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
|
package org.cyclops.integratedtunnels.part.aspect.operator;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.Direction;
import net.minecraftforge.common.capabilities.Capability;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeItemStack;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypeLong;
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
import org.cyclops.integratedtunnels.capability.network.ItemNetworkConfig;
import org.cyclops.integrateddynamics.core.evaluate.operator.OperatorBase.SafeVariablesGetter;
/**
* @author rubensworks
*/
public class PositionedOperatorIngredientIndexItem extends PositionedOperatorIngredientIndex<ItemStack, Integer> {
public PositionedOperatorIngredientIndexItem(DimPos pos, Direction side, int channel) {
super("countbyitem", new Function(), ValueTypes.OBJECT_ITEMSTACK, ValueTypes.LONG, pos, side, channel);
}
@Override
protected Capability<? extends IPositionedAddonsNetworkIngredients<ItemStack, Integer>> getNetworkCapability() {
return ItemNetworkConfig.CAPABILITY;
}
public static class Function extends PositionedOperatorIngredientIndex.Function<ItemStack, Integer> {
@Override
public IValue evaluate(SafeVariablesGetter variables) throws EvaluationException {
ValueObjectTypeItemStack.ValueItemStack itemStack = variables.getValue(0, ValueTypes.OBJECT_ITEMSTACK);
return ValueTypeLong.ValueLong.of(getOperator().getChannelIndex()
.map(index -> index.getQuantity(itemStack.getRawValue()))
.orElse(0L));
}
}
}
|
Fix materialization failure of operator-based network aspects
Closes CyclopsMC/IntegratedDynamics#1177
|
src/main/java/org/cyclops/integratedtunnels/part/aspect/operator/PositionedOperatorIngredientIndexItem.java
|
Fix materialization failure of operator-based network aspects
|
|
Java
|
mit
|
e0e13b97e27ae4d678907d5cbd58719c62b9c1fe
| 0
|
yitzih/Chess
|
//package chess.tests.model.pieces;
//
//
//import chess.model.ChessGame;
//import chess.model.Color;
//import chess.model.pieces.*;
//import org.junit.Before;
//import org.junit.Test;
//
//import java.util.ArrayList;
//import java.util.List;
//import chess.model.Vector;
//
//import static org.junit.Assert.*;
//
///**
// * Current tests as of 3/27/16:
// * Each corner
// * Being on the different edges
// * Being in the center with no pieces around it
// * Being in the center with a few piece around it
// * Being in the center with it blocked from every piece
// *
// * Still needs testing for:
// * Castling (ensure that it can't if blocked or one of the pieces already moved)
// * Moving into a check
// * Moving through a check (when castling)
// *
// */
//public class KingTest {
//
// private ChessGame game;
//
// @Before
// public void setUp() {
// //set up a new empty chess game model for each test
// game = new ChessGame(false);
// }
//
// @Test
// public void LegalMovesWhenKingIsInTheTopLeftCorner() {
// final int X = 0;
// final int Y = 0;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(0, 1));
// whatResultsShouldBe.add(new Vector(1, 0));
// whatResultsShouldBe.add(new Vector(1, 1));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsInTheTopRightCorner() {
// final int X = 7;
// final int Y = 0;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(7, 1));
// whatResultsShouldBe.add(new Vector(6, 0));
// whatResultsShouldBe.add(new Vector(6, 1));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsInTheBottomLeftCorner() {
// final int X = 0;
// final int Y = 7;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(0, 6));
// whatResultsShouldBe.add(new Vector(1, 6));
// whatResultsShouldBe.add(new Vector(1, 7));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsInTheBottomRightCorner() {
// final int X = 7;
// final int Y = 7;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(6, 6));
// whatResultsShouldBe.add(new Vector(6, 7));
// whatResultsShouldBe.add(new Vector(7, 6));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsOnTheTopEdge() {
// final int X = 4;
// final int Y = 0;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(0, 3));
// whatResultsShouldBe.add(new Vector(0, 5));
// whatResultsShouldBe.add(new Vector(1, 3));
// whatResultsShouldBe.add(new Vector(1, 4));
// whatResultsShouldBe.add(new Vector(1, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsOnTheBottomEdge() {
// final int X = 4;
// final int Y = 7;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(7, 3));
// whatResultsShouldBe.add(new Vector(7, 5));
// whatResultsShouldBe.add(new Vector(6, 3));
// whatResultsShouldBe.add(new Vector(6, 4));
// whatResultsShouldBe.add(new Vector(6, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsOnTheRightEdge() {
// final int X = 7;
// final int Y = 4;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(7, 3));
// whatResultsShouldBe.add(new Vector(7, 5));
// whatResultsShouldBe.add(new Vector(6, 3));
// whatResultsShouldBe.add(new Vector(6, 4));
// whatResultsShouldBe.add(new Vector(6, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsOnTheLeftEdge() {
// final int X = 0;
// final int Y = 4;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(0, 3));
// whatResultsShouldBe.add(new Vector(0, 5));
// whatResultsShouldBe.add(new Vector(1, 3));
// whatResultsShouldBe.add(new Vector(1, 4));
// whatResultsShouldBe.add(new Vector(1, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsInMiddle() {
// final int X = 4;
// final int Y = 4;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(3, 3));
// whatResultsShouldBe.add(new Vector(3, 4));
// whatResultsShouldBe.add(new Vector(3, 5));
// whatResultsShouldBe.add(new Vector(4, 3));
// whatResultsShouldBe.add(new Vector(4, 5));
// whatResultsShouldBe.add(new Vector(5, 3));
// whatResultsShouldBe.add(new Vector(5, 4));
// whatResultsShouldBe.add(new Vector(5, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
// @Test
// public void LegalMovesWhenKingIsInMiddleAndHasPiecesInItsPath() {
// final int X = 4;
// final int Y = 4;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// game.getBoard()[Y - 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X + 1].getPosition()));
// game.getBoard()[Y][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X - 1].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// List<Vector> whatResultsShouldBe = new ArrayList<>();
// whatResultsShouldBe.add(new Vector(3, 3));
// whatResultsShouldBe.add(new Vector(3, 5));
// whatResultsShouldBe.add(new Vector(4, 3));
// whatResultsShouldBe.add(new Vector(4, 5));
// whatResultsShouldBe.add(new Vector(5, 4));
// whatResultsShouldBe.add(new Vector(5, 5));
//
// assertTrue(legalMoves.size() == whatResultsShouldBe.size());
// assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
// }
//
//
//
// @Test
// public void LegalMovesWhenKingIsInMiddleAndIsCompletelySurrounded() {
// final int X = 4;
// final int Y = 4;
//
// game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
// game.getBoard()[Y - 1][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X - 1].getPosition()));
// game.getBoard()[Y - 1][X].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X].getPosition()));
// game.getBoard()[Y - 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X + 1].getPosition()));
// game.getBoard()[Y][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X - 1].getPosition()));
// game.getBoard()[Y][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X + 1].getPosition()));
// game.getBoard()[Y + 1][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X - 1].getPosition()));
// game.getBoard()[Y + 1][X].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X].getPosition()));
// game.getBoard()[Y + 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X + 1].getPosition()));
// List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
//
// assertTrue(legalMoves.size() == 0);
// }
//}
|
src/chess/tests/model/pieces/KingTest.java
|
package chess.tests.model.pieces;
import chess.model.ChessGame;
import chess.model.Color;
import chess.model.pieces.*;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import chess.model.Vector;
import static org.junit.Assert.*;
/**
* Current tests as of 3/27/16:
* Each corner
* Being on the different edges
* Being in the center with no pieces around it
* Being in the center with a few piece around it
* Being in the center with it blocked from every piece
*
* Still needs testing for:
* Castling (ensure that it can't if blocked or one of the pieces already moved)
* Moving into a check
* Moving through a check (when castling)
*
*/
public class KingTest {
private ChessGame game;
@Before
public void setUp() {
//set up a new empty chess game model for each test
game = new ChessGame(false);
}
@Test
public void LegalMovesWhenKingIsInTheTopLeftCorner() {
final int X = 0;
final int Y = 0;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(0, 1));
whatResultsShouldBe.add(new Vector(1, 0));
whatResultsShouldBe.add(new Vector(1, 1));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInTheTopRightCorner() {
final int X = 7;
final int Y = 0;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(7, 1));
whatResultsShouldBe.add(new Vector(6, 0));
whatResultsShouldBe.add(new Vector(6, 1));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInTheBottomLeftCorner() {
final int X = 0;
final int Y = 7;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(0, 6));
whatResultsShouldBe.add(new Vector(1, 6));
whatResultsShouldBe.add(new Vector(1, 7));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInTheBottomRightCorner() {
final int X = 7;
final int Y = 7;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(6, 6));
whatResultsShouldBe.add(new Vector(6, 7));
whatResultsShouldBe.add(new Vector(7, 6));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsOnTheTopEdge() {
final int X = 4;
final int Y = 0;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(0, 3));
whatResultsShouldBe.add(new Vector(0, 5));
whatResultsShouldBe.add(new Vector(1, 3));
whatResultsShouldBe.add(new Vector(1, 4));
whatResultsShouldBe.add(new Vector(1, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsOnTheBottomEdge() {
final int X = 4;
final int Y = 7;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(7, 3));
whatResultsShouldBe.add(new Vector(7, 5));
whatResultsShouldBe.add(new Vector(6, 3));
whatResultsShouldBe.add(new Vector(6, 4));
whatResultsShouldBe.add(new Vector(6, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsOnTheRightEdge() {
final int X = 7;
final int Y = 4;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(7, 3));
whatResultsShouldBe.add(new Vector(7, 5));
whatResultsShouldBe.add(new Vector(6, 3));
whatResultsShouldBe.add(new Vector(6, 4));
whatResultsShouldBe.add(new Vector(6, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsOnTheLeftEdge() {
final int X = 0;
final int Y = 4;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(0, 3));
whatResultsShouldBe.add(new Vector(0, 5));
whatResultsShouldBe.add(new Vector(1, 3));
whatResultsShouldBe.add(new Vector(1, 4));
whatResultsShouldBe.add(new Vector(1, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInMiddle() {
final int X = 4;
final int Y = 4;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(3, 3));
whatResultsShouldBe.add(new Vector(3, 4));
whatResultsShouldBe.add(new Vector(3, 5));
whatResultsShouldBe.add(new Vector(4, 3));
whatResultsShouldBe.add(new Vector(4, 5));
whatResultsShouldBe.add(new Vector(5, 3));
whatResultsShouldBe.add(new Vector(5, 4));
whatResultsShouldBe.add(new Vector(5, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInMiddleAndHasPiecesInItsPath() {
final int X = 4;
final int Y = 4;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
game.getBoard()[Y - 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X + 1].getPosition()));
game.getBoard()[Y][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X - 1].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
List<Vector> whatResultsShouldBe = new ArrayList<>();
whatResultsShouldBe.add(new Vector(3, 3));
whatResultsShouldBe.add(new Vector(3, 5));
whatResultsShouldBe.add(new Vector(4, 3));
whatResultsShouldBe.add(new Vector(4, 5));
whatResultsShouldBe.add(new Vector(5, 4));
whatResultsShouldBe.add(new Vector(5, 5));
assertTrue(legalMoves.size() == whatResultsShouldBe.size());
assertTrue(whatResultsShouldBe.containsAll(legalMoves) && legalMoves.containsAll(whatResultsShouldBe));
}
@Test
public void LegalMovesWhenKingIsInMiddleAndIsCompletelySurrounded() {
final int X = 4;
final int Y = 4;
game.getBoard()[Y][X].setPiece(new King(Color.BLACK, game.getBoard()[Y][X].getPosition()));
game.getBoard()[Y - 1][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X - 1].getPosition()));
game.getBoard()[Y - 1][X].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X].getPosition()));
game.getBoard()[Y - 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y - 1][X + 1].getPosition()));
game.getBoard()[Y][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X - 1].getPosition()));
game.getBoard()[Y][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y][X + 1].getPosition()));
game.getBoard()[Y + 1][X - 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X - 1].getPosition()));
game.getBoard()[Y + 1][X].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X].getPosition()));
game.getBoard()[Y + 1][X + 1].setPiece(new Pawn(Color.BLACK, game.getBoard()[Y + 1][X + 1].getPosition()));
List<Vector> legalMoves = game.getLegalMoves(game.getBoard()[Y][X].getPiece());
assertTrue(legalMoves.size() == 0);
}
}
|
commented out... needs to be redone
|
src/chess/tests/model/pieces/KingTest.java
|
commented out... needs to be redone
|
|
Java
|
mit
|
fba919f167b6a2b0df6431295f881bb7b86324d3
| 0
|
raeffu/codingbat
|
package codingbat.logic2;
/*
* We want to make a row of bricks that is goal inches long.
* We have a number of small bricks (1 inch each)
* and big bricks (5 inches each).
* Return true if it is possible to make the goal by choosing
* from the given bricks.
* This is a little harder than it looks and can be done without any loops.
* See also: Introduction to MakeBricks
*
* makeBricks(3, 1, 8) = true
* makeBricks(3, 1, 9) = false
* makeBricks(3, 2, 10) = true
*/
public class MakeBricksTest {
public static void main(String[] args) {
MakeBricksTest test = new MakeBricksTest();
System.out.println(">" + test.makeBricks(3, 1, 8) + "<");
System.out.println(">" + test.makeBricks(3, 1, 9) + "<");
System.out.println(">" + test.makeBricks(3, 2, 10) + "<");
}
public boolean makeBricks(int small, int big, int goal) {
int inchBig = big*5;
if (inchBig == 0) {
return goal <= small;
}
if (small + inchBig < goal) {
return false;
}
while (goal%inchBig == goal) {
inchBig -= 5;
}
if (goal%inchBig <= small) {
return true;
}
return false;
}
}
|
src/codingbat/logic2/MakeBricksTest.java
|
package codingbat.logic2;
/*
* We want to make a row of bricks that is goal inches long.
* We have a number of small bricks (1 inch each)
* and big bricks (5 inches each).
* Return true if it is possible to make the goal by choosing
* from the given bricks.
* This is a little harder than it looks and can be done without any loops.
* See also: Introduction to MakeBricks
*
* makeBricks(3, 1, 8) = true
* makeBricks(3, 1, 9) = false
* makeBricks(3, 2, 10) = true
*/
public class MakeBricksTest {
public static void main(String[] args) {
MakeBricksTest test = new MakeBricksTest();
System.out.println(">" + test.makeBricks(3, 1, 8) + "<");
System.out.println(">" + test.makeBricks(3, 1, 9) + "<");
System.out.println(">" + test.makeBricks(3, 2, 10) + "<");
}
public boolean makeBricks(int small, int big, int goal) {
// if (goal == small || big*5 == goal) {
// return true;
// }
// else if (small + (big*5) < goal) {
// return false;
// }
//
//
return false;
}
}
|
add makeBricks task
|
src/codingbat/logic2/MakeBricksTest.java
|
add makeBricks task
|
|
Java
|
agpl-3.0
|
0ea78ff83416177a371fa0f5b805c955f869449f
| 0
|
lzpfmh/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,lzpfmh/actor-platform,lzpfmh/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,lzpfmh/actor-platform,y0ke/actor-platform,y0ke/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,y0ke/actor-platform,y0ke/actor-platform,y0ke/actor-platform,lzpfmh/actor-platform,lzpfmh/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform
|
package im.actor.core.js.utils;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.safehtml.shared.UriUtils;
import im.actor.runtime.markdown.*;
import java.util.ArrayList;
public class HtmlMarkdownUtils {
public static String processText(String markdown, int mode) {
MDDocument doc = new MarkdownParser(mode).processDocument(markdown);
ArrayList<String> renderedSections = new ArrayList<String>();
for (MDSection section : doc.getSections()) {
renderedSections.add(renderSection(section));
}
StringBuilder builder = new StringBuilder();
for (String section : renderedSections) {
builder.append("<p>");
builder.append(section);
builder.append("</p>");
}
return builder.toString();
}
public static String renderSection(MDSection section) {
if (section.getType() == MDSection.TYPE_CODE) {
return renderCode(section.getCode());
} else if (section.getType() == MDSection.TYPE_TEXT) {
return renderText(section.getText());
} else {
return "";
}
}
public static String renderCode(MDCode code) {
return "<pre><code>" + SafeHtmlUtils.htmlEscape(code.getCode()) + "</pre></code>";
}
public static String renderText(MDText[] texts) {
StringBuilder builder = new StringBuilder();
for (MDText text : texts) {
if (text instanceof MDRawText) {
final MDRawText rawText = (MDRawText) text;
builder.append(SafeHtmlUtils.htmlEscape(rawText.getRawText()).replace("\n", "<br/>"));
} else if (text instanceof MDSpan) {
final MDSpan span = (MDSpan) text;
builder.append(spanElement(span.getSpanType(), renderText(span.getChild())));
} else if (text instanceof MDUrl) {
final MDUrl url = (MDUrl) text;
builder.append(urlElement(url));
}
}
return builder.toString();
}
private static String spanElement(int type, String innerHTML) {
if (type == MDSpan.TYPE_BOLD) {
return "<b>" + innerHTML + "</b>";
} else if (type == MDSpan.TYPE_ITALIC) {
return "<i>" + innerHTML + "</i>";
} else {
return innerHTML;
}
}
private static String urlElement(MDUrl url) {
String href = UriUtils.sanitizeUri(url.getUrl());
if (href != "#" && !href.contains("://")) {
href = "http://" + href;
}
return "<a " +
"target=\"_blank\" " +
"onClick=\"window.messenger.handleLinkClick(event)\" " +
"href=\"" + href + "\">" +
SafeHtmlUtils.htmlEscape(url.getUrlTitle()) +
"</a>";
}
}
|
actor-apps/core-js/src/main/java/im/actor/core/js/utils/HtmlMarkdownUtils.java
|
package im.actor.core.js.utils;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.safehtml.shared.UriUtils;
import im.actor.runtime.markdown.*;
import java.util.ArrayList;
public class HtmlMarkdownUtils {
public static String processText(String markdown, int mode) {
MDDocument doc = new MarkdownParser(mode).processDocument(markdown);
ArrayList<String> renderedSections = new ArrayList<String>();
for (MDSection section : doc.getSections()) {
renderedSections.add(renderSection(section));
}
StringBuilder builder = new StringBuilder();
for (String section : renderedSections) {
builder.append("<p>");
builder.append(section);
builder.append("</p>");
}
return builder.toString();
}
public static String renderSection(MDSection section) {
if (section.getType() == MDSection.TYPE_CODE) {
return renderCode(section.getCode());
} else if (section.getType() == MDSection.TYPE_TEXT) {
return renderText(section.getText());
} else {
return "";
}
}
public static String renderCode(MDCode code) {
return "<pre><code>" + SafeHtmlUtils.htmlEscape(code.getCode()) + "</pre></code>";
}
public static String renderText(MDText[] texts) {
StringBuilder builder = new StringBuilder();
for (MDText text : texts) {
if (text instanceof MDRawText) {
final MDRawText rawText = (MDRawText) text;
builder.append(SafeHtmlUtils.htmlEscape(rawText.getRawText()).replace("\n", "<br/>"));
} else if (text instanceof MDSpan) {
final MDSpan span = (MDSpan) text;
builder.append(spanElement(span.getSpanType(), renderText(span.getChild())));
} else if (text instanceof MDUrl) {
final MDUrl url = (MDUrl) text;
builder.append(urlElement(url));
}
}
return builder.toString();
}
private static String spanElement(int type, String innerHTML) {
if (type == MDSpan.TYPE_BOLD) {
return "<b>" + innerHTML + "</b>";
} else if (type == MDSpan.TYPE_ITALIC) {
return "<i>" + innerHTML + "</i>";
} else {
return innerHTML;
}
}
private static String urlElement(MDUrl url) {
return "<a " +
"target=\"_blank\" " +
"onClick=\"window.messenger.handleLinkClick(event)\" " +
"href=\"" + UriUtils.sanitizeUri(url.getUrl()) + "\">" +
SafeHtmlUtils.htmlEscape(url.getUrlTitle()) +
"</a>";
}
}
|
fix(web): fixed relative urls
|
actor-apps/core-js/src/main/java/im/actor/core/js/utils/HtmlMarkdownUtils.java
|
fix(web): fixed relative urls
|
|
Java
|
agpl-3.0
|
eab9d8dcd7f4bc8ff50fbc3575e146be8b8ce57a
| 0
|
jotomo/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS,jotomo/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS
|
package info.nightscout.androidaps.plugins.PumpCombo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.monkey.d.ruffy.ruffy.driver.IRuffyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import de.jotomo.ruffyscripter.RuffyScripter;
import de.jotomo.ruffyscripter.commands.BolusCommand;
import de.jotomo.ruffyscripter.commands.CancelTbrCommand;
import de.jotomo.ruffyscripter.commands.Command;
import de.jotomo.ruffyscripter.commands.CommandResult;
import de.jotomo.ruffyscripter.commands.SetTbrCommand;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DateUtil;
/**
* Created by mike on 05.08.2016.
*/
public class ComboPlugin implements PluginBase, PumpInterface {
private static Logger log = LoggerFactory.getLogger(ComboPlugin.class);
boolean fragmentEnabled = false;
boolean fragmentVisible = false;
PumpDescription pumpDescription = new PumpDescription();
// TODO quick hack until pump state is more thoroughly supported
int activeTbrPercentage = -1;
private RuffyScripter ruffyScripter;
private Date lastCmdTime = new Date(0);
private ServiceConnection mRuffyServiceConnection;
private static PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult();
static {
OPERATION_NOT_SUPPORTED.success = false;
OPERATION_NOT_SUPPORTED.enacted = false;
OPERATION_NOT_SUPPORTED.comment = "Requested operation not supported by pump";
}
public ComboPlugin() {
definePumpCapabilities();
bindRuffyService();
MainApp.bus().register(this);
}
private void bindRuffyService() {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent()
.setComponent(new ComponentName(
// this must be the base package of the app (check package attribute in
// manifest element in the manifest file of the providing app)
"org.monkey.d.ruffy.ruffy",
// full path to the driver
// in the logs this service is mentioned as (note the slash)
// "org.monkey.d.ruffy.ruffy/.driver.Ruffy"
"org.monkey.d.ruffy.ruffy.driver.Ruffy"
));
context.startService(intent);
mRuffyServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ruffyScripter = new RuffyScripter(IRuffyService.Stub.asInterface(service));
log.debug("ruffy serivce connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
log.debug("ruffy service disconnected");
}
};
boolean success = context.bindService(intent, mRuffyServiceConnection, Context.BIND_AUTO_CREATE);
if (!success) {
log.error("Binding to ruffy service failed");
}
}
private void definePumpCapabilities() {
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
pumpDescription.isExtendedBolusCapable = false; // TODO
pumpDescription.extendedBolusStep = 0.1d;
pumpDescription.extendedBolusDurationStep = 15;
pumpDescription.extendedBolusMaxDuration = 12 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = 500;
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 15;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = false; // TODO
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.0d;
pumpDescription.isRefillingCapable = false;
}
@Override
public String getFragmentClass() {
return ComboFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.combopump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.combopump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
return type == PUMP && fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PUMP && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PUMP) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PUMP) this.fragmentVisible = fragmentVisible;
}
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public boolean isInitialized() {
// TODO
// hm, lastCmdDate > 0, like the DanaR does it?
return true; // scripter does this as needed; ruffyScripter != null;
}
@Override
public boolean isSuspended() {
return false;
}
// TODO
@Override
public boolean isBusy() {
return ruffyScripter.isPumpBusy();
}
// TODO
@Override
public int setNewBasalProfile(Profile profile) {
return FAILED;
}
// TODO
@Override
public boolean isThisProfileSet(Profile profile) {
return false;
}
// TODO
@Override
public Date lastDataTime() {
return lastCmdTime;
}
// TODO
@Override
public void refreshDataFromPump(String reason) {
log.debug("RefreshDataFromPump called");
// this is called regulary from keepalive
// TODO how often is this called? use this to run checks regularly, e.g.
// recheck active TBR, basal rate to ensure nothing broke?
}
// TODO uses profile values for the time being
// this get's called mulitple times a minute, must absolutely be cached
@Override
public double getBaseBasalRate() {
Profile profile = MainApp.getConfigBuilder().getProfile();
Double basal = profile.getBasal();
log.trace("getBaseBasalrate returning " + basal);
return basal;
}
// TODO rewrite this crap into something comprehensible
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
log.debug("deliver treatment called with dbi: " + detailedBolusInfo);
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
detailedBolusInfo.insulin = configBuilderPlugin.applyBolusConstraints(detailedBolusInfo.insulin);
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
PumpEnactResult result = new PumpEnactResult();
if (detailedBolusInfo.insulin > 0) {
CommandResult bolusCmdResult = runCommand(new BolusCommand(detailedBolusInfo.insulin));
result.success = bolusCmdResult.success;
result.enacted = bolusCmdResult.enacted;
// TODO if no error occurred, the requested bolus is what the pump delievered,
// that has been checked. If an error occurred, we should check how much insulin
// was delivered, e.g. when the cartridge went empty mid-bolus
result.bolusDelivered = detailedBolusInfo.insulin;
result.comment = bolusCmdResult.message;
} else {
// TODO the ui freezes when the calculator issues a carb-only treatment
// so just wait, yeah, this is dumb. for now; proper fix via GL#10
// info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog.scheduleDismiss()
SystemClock.sleep(6000);
result.success = true;
result.enacted = false;
}
if (result.enacted) {
result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.date = new Date().getTime();
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
}
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
result.success = false;
result.bolusDelivered = 0d;
result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input");
return result;
}
}
private CommandResult runCommand(Command command) {
// TODO use this to dispatch methods to a service thread, like DanaRs executionService
try {
return ruffyScripter.runCommand(command);
} finally {
lastCmdTime = new Date();
ruffyScripter.disconnect();
}
}
@Override
public void stopBolusDelivering() {
// there's no way to stop the combo once delivery has started
// but before that, we could interrupt the command thread ... pause
// till pump times out or raises an error
}
// Note: AAPS calls this only to enact OpenAPS recommendations
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate/ getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) {
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
}
if (activeTbrPercentage != -1 && Math.abs(activeTbrPercentage - roundedPercentage) <= 20) {
log.debug("Not bothering the pump for a small TBR change from " + activeTbrPercentage + "% -> " + roundedPercentage + "%");
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = true;
pumpEnactResult.enacted = false;
pumpEnactResult.percent = activeTbrPercentage;
pumpEnactResult.comment = "TBR change too small, skipping";
return pumpEnactResult;
}
int stepSize = pumpDescription.tempDurationStep;
if (durationInMinutes > stepSize) {
log.debug("Reducing requested duration of " + durationInMinutes + "m to minimal duration supported by the pump: " + stepSize + "m");
durationInMinutes = stepSize;
}
return setTempBasalPercent(roundedPercentage, durationInMinutes);
}
// Note: AAPS calls this only for setting a temp basal issued by the user
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
if (percent % 10 != 0) {
int rounded = percent;
while (rounded % 10 != 0) rounded = rounded - 1;
log.debug("Rounded requested percentage from " + percent + " to " + rounded);
percent = rounded;
}
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
CommandResult commandResult = runCommand(new SetTbrCommand(percent, durationInMinutes));
if (commandResult.enacted) {
TemporaryBasal tempStart = new TemporaryBasal(System.currentTimeMillis());
tempStart.durationInMinutes = durationInMinutes;
tempStart.percentRate = percent;
tempStart.isAbsolute = false;
tempStart.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStart);
activeTbrPercentage = percent;
}
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
pumpEnactResult.isPercent = true;
// Combo would have bailed if this wasn't set properly. Maybe we should
// have the command return this anyways ...
pumpEnactResult.percent = percent;
pumpEnactResult.duration = durationInMinutes;
return pumpEnactResult;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return OPERATION_NOT_SUPPORTED;
}
@Override
public PumpEnactResult cancelTempBasal() {
log.debug("cancelTempBasal called");
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
CommandResult commandResult = runCommand(new CancelTbrCommand());
if(commandResult.enacted) {
TemporaryBasal tempStop = new TemporaryBasal(System.currentTimeMillis());
tempStop.durationInMinutes = 0; // ending temp basal
tempStop.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStop);
activeTbrPercentage = 100;
}
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
pumpEnactResult.isTempCancel = true;
return pumpEnactResult;
}
// TODO
@Override
public PumpEnactResult cancelExtendedBolus() {
return OPERATION_NOT_SUPPORTED;
}
// TODO
// cache as much as possible - every time we interact with the pump it vibrates at the end
@Override
public JSONObject getJSONStatus() {
JSONObject pump = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
status.put("status", "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
status.put("timestamp", DateUtil.toISOString(new Date()));
// more info here .... look at dana plugin
pump.put("status", status);
pump.put("extended", extended);
pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
}
return pump;
}
// TODO
@Override
public String deviceID() {
// Serial number here
return "Combo";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return deviceID();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
@SuppressWarnings("UnusedParameters")
@Subscribe
public void onStatusEvent(final EventAppExit e) {
MainApp.instance().getApplicationContext().unbindService(mRuffyServiceConnection);
}
}
// If you want update fragment call
// MainApp.bus().post(new EventComboPumpUpdateGUI());
// fragment should fetch data from plugin and display status, buttons etc ...
|
app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java
|
package info.nightscout.androidaps.plugins.PumpCombo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.monkey.d.ruffy.ruffy.driver.IRuffyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import de.jotomo.ruffyscripter.RuffyScripter;
import de.jotomo.ruffyscripter.commands.BolusCommand;
import de.jotomo.ruffyscripter.commands.CancelTbrCommand;
import de.jotomo.ruffyscripter.commands.Command;
import de.jotomo.ruffyscripter.commands.CommandResult;
import de.jotomo.ruffyscripter.commands.SetTbrCommand;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DateUtil;
/**
* Created by mike on 05.08.2016.
*/
public class ComboPlugin implements PluginBase, PumpInterface {
private static Logger log = LoggerFactory.getLogger(ComboPlugin.class);
boolean fragmentEnabled = false;
boolean fragmentVisible = false;
PumpDescription pumpDescription = new PumpDescription();
// TODO quick hack until pump state is more thoroughly supported
int activeTbrPercentage = -1;
private RuffyScripter ruffyScripter;
private Date lastCmdTime = new Date(0);
private ServiceConnection mRuffyServiceConnection;
private static PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult();
static {
OPERATION_NOT_SUPPORTED.success = false;
OPERATION_NOT_SUPPORTED.enacted = false;
OPERATION_NOT_SUPPORTED.comment = "Requested operation not supported by pump";
}
public ComboPlugin() {
definePumpCapabilities();
bindRuffyService();
MainApp.bus().register(this);
}
private void bindRuffyService() {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent()
.setComponent(new ComponentName(
// this must be the base package of the app (check package attribute in
// manifest element in the manifest file of the providing app)
"org.monkey.d.ruffy.ruffy",
// full path to the driver
// in the logs this service is mentioned as (note the slash)
// "org.monkey.d.ruffy.ruffy/.driver.Ruffy"
"org.monkey.d.ruffy.ruffy.driver.Ruffy"
));
context.startService(intent);
mRuffyServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ruffyScripter = new RuffyScripter(IRuffyService.Stub.asInterface(service));
log.debug("ruffy serivce connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
log.debug("ruffy service disconnected");
}
};
boolean success = context.bindService(intent, mRuffyServiceConnection, Context.BIND_AUTO_CREATE);
if (!success) {
log.error("Binding to ruffy service failed");
}
}
private void definePumpCapabilities() {
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
pumpDescription.isExtendedBolusCapable = false; // TODO
pumpDescription.extendedBolusStep = 0.1d;
pumpDescription.extendedBolusDurationStep = 15;
pumpDescription.extendedBolusMaxDuration = 12 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = 500;
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 15;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = false; // TODO
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.0d;
pumpDescription.isRefillingCapable = false;
}
@Override
public String getFragmentClass() {
return ComboFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.combopump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.combopump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
return type == PUMP && fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PUMP && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PUMP) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PUMP) this.fragmentVisible = fragmentVisible;
}
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public boolean isInitialized() {
// TODO
// hm, lastCmdDate > 0, like the DanaR does it?
return true; // scripter does this as needed; ruffyScripter != null;
}
@Override
public boolean isSuspended() {
return false;
}
// TODO
@Override
public boolean isBusy() {
return ruffyScripter.isPumpBusy();
}
// TODO
@Override
public int setNewBasalProfile(Profile profile) {
return FAILED;
}
// TODO
@Override
public boolean isThisProfileSet(Profile profile) {
return false;
}
// TODO
@Override
public Date lastDataTime() {
return lastCmdTime;
}
// TODO
@Override
public void refreshDataFromPump(String reason) {
log.debug("RefreshDataFromPump called");
// this is called regulary from keepalive
// TODO how often is this called? use this to run checks regularly, e.g.
// recheck active TBR, basal rate to ensure nothing broke?
}
// TODO uses profile values for the time being
// this get's called mulitple times a minute, must absolutely be cached
@Override
public double getBaseBasalRate() {
Profile profile = MainApp.getConfigBuilder().getProfile();
Double basal = profile.getBasal();
log.trace("getBaseBasalrate returning " + basal);
return basal;
}
// TODO rewrite this crap into something comprehensible
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
log.debug("deliver treatment called with dbi: " + detailedBolusInfo);
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
detailedBolusInfo.insulin = configBuilderPlugin.applyBolusConstraints(detailedBolusInfo.insulin);
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
PumpEnactResult result = new PumpEnactResult();
if (detailedBolusInfo.insulin > 0) {
CommandResult bolusCmdResult = runCommand(new BolusCommand(detailedBolusInfo.insulin));
result.success = bolusCmdResult.success;
result.enacted = bolusCmdResult.enacted;
// TODO if no error occurred, the requested bolus is what the pump delievered,
// that has been checked. If an error occurred, we should check how much insulin
// was delivered, e.g. when the cartridge went empty mid-bolus
result.bolusDelivered = detailedBolusInfo.insulin;
result.comment = bolusCmdResult.message;
} else {
// TODO the ui freezes when the calculator issues a carb-only treatment
// so just wait, yeah, this is dumb. for now; proper fix via GL#10
// info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog.scheduleDismiss()
SystemClock.sleep(6000);
result.success = true;
result.enacted = false;
}
if (result.enacted) {
result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.date = new Date().getTime();
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
}
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
result.success = false;
result.bolusDelivered = 0d;
result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input");
return result;
}
}
private CommandResult runCommand(Command command) {
// TODO use this to dispatch methods to a service thread, like DanaRs executionService
try {
return ruffyScripter.runCommand(command);
} finally {
lastCmdTime = new Date();
ruffyScripter.disconnect();
}
}
@Override
public void stopBolusDelivering() {
// there's no way to stop the combo once delivery has started
// but before that, we could interrupt the command thread ... pause
// till pump times out or raises an error
}
// Note: AAPS calls this only to enact OpenAPS recommendations
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate/ getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) {
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
}
if (activeTbrPercentage != -1 && Math.abs(activeTbrPercentage - roundedPercentage) <= 20) {
log.debug("Not bothering the pump for a small TBR change from " + activeTbrPercentage + "% -> " + roundedPercentage + "%");
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = true;
pumpEnactResult.enacted = false;
pumpEnactResult.percent = activeTbrPercentage;
pumpEnactResult.comment = "TBR change too small, skipping";
return pumpEnactResult;
}
int stepSize = pumpDescription.tempPercentStep;
if (durationInMinutes > stepSize) {
log.debug("Reducing requested duration of " + durationInMinutes + "m to minimal duration supported by the pump: " + stepSize + "m");
durationInMinutes = stepSize;
}
return setTempBasalPercent(roundedPercentage, durationInMinutes);
}
// Note: AAPS calls this only for setting a temp basal issued by the user
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
if (percent % 10 != 0) {
int rounded = percent;
while (rounded % 10 != 0) rounded = rounded - 1;
log.debug("Rounded requested percentage from " + percent + " to " + rounded);
percent = rounded;
}
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
CommandResult commandResult = runCommand(new SetTbrCommand(percent, durationInMinutes));
if (commandResult.enacted) {
TemporaryBasal tempStart = new TemporaryBasal(System.currentTimeMillis());
tempStart.durationInMinutes = durationInMinutes;
tempStart.percentRate = percent;
tempStart.isAbsolute = false;
tempStart.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStart);
activeTbrPercentage = percent;
}
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
pumpEnactResult.isPercent = true;
// Combo would have bailed if this wasn't set properly. Maybe we should
// have the command return this anyways ...
pumpEnactResult.percent = percent;
pumpEnactResult.duration = durationInMinutes;
return pumpEnactResult;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return OPERATION_NOT_SUPPORTED;
}
@Override
public PumpEnactResult cancelTempBasal() {
log.debug("cancelTempBasal called");
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
CommandResult commandResult = runCommand(new CancelTbrCommand());
if(commandResult.enacted) {
TemporaryBasal tempStop = new TemporaryBasal(System.currentTimeMillis());
tempStop.durationInMinutes = 0; // ending temp basal
tempStop.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStop);
activeTbrPercentage = 100;
}
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
pumpEnactResult.isTempCancel = true;
return pumpEnactResult;
}
// TODO
@Override
public PumpEnactResult cancelExtendedBolus() {
return OPERATION_NOT_SUPPORTED;
}
// TODO
// cache as much as possible - every time we interact with the pump it vibrates at the end
@Override
public JSONObject getJSONStatus() {
JSONObject pump = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
status.put("status", "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
status.put("timestamp", DateUtil.toISOString(new Date()));
// more info here .... look at dana plugin
pump.put("status", status);
pump.put("extended", extended);
pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
}
return pump;
}
// TODO
@Override
public String deviceID() {
// Serial number here
return "Combo";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return deviceID();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
@SuppressWarnings("UnusedParameters")
@Subscribe
public void onStatusEvent(final EventAppExit e) {
MainApp.instance().getApplicationContext().unbindService(mRuffyServiceConnection);
}
}
// If you want update fragment call
// MainApp.bus().post(new EventComboPumpUpdateGUI());
// fragment should fetch data from plugin and display status, buttons etc ...
|
Fix reducing duration of OpenAPS TBRs
|
app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java
|
Fix reducing duration of OpenAPS TBRs
|
|
Java
|
agpl-3.0
|
82cfb7ada623403e15444d99c2b4532b60ff126f
| 0
|
VietOpenCPS/opencps-v2,VietOpenCPS/opencps-v2
|
package org.opencps.api.controller.impl;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.dao.orm.Disjunction;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
import com.liferay.portal.kernel.dao.orm.ProjectionList;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.UserLocalServiceUtil;
import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.TimeZoneUtil;
import com.liferay.portal.kernel.util.Validator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.opencps.adminconfig.model.AdminConfig;
import org.opencps.adminconfig.service.AdminConfigLocalServiceUtil;
import org.opencps.api.constants.ConstantUtils;
import org.opencps.api.controller.AdminConfigManagement;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.springframework.http.HttpStatus;
import backend.admin.config.whiteboard.BundleLoader;
import backend.auth.api.exception.BusinessExceptionImpl;
public class AdminConfigManagementImpl implements AdminConfigManagement {
private static String convertDateToString(Date date) {
DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(_TIMESTAMP);
if (Validator.isNull(date) || Validator.isNull(_TIMESTAMP)) {
return StringPool.BLANK;
}
dateFormat.setTimeZone(TimeZoneUtil.getTimeZone(ConstantUtils.TIMEZONE_ASIA_HOCHIMINH));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return dateFormat.format(calendar.getTime());
}
public static final String _TIMESTAMP = "dd/MM/yyyy HH:mm";
private static final Log _log = LogFactoryUtil.getLog(AdminConfigManagementImpl.class);
private static final String TYPE = "type";
private static final String CMD = "cmd";
private static final String GET = "get";
private static final String DELETE = "delete";
private static final String ADMIN = "admin";
private static final String API = "api";
private static final String BUNDLE_NAME = "bundle_name";
private static final String SERVICE_UTIL_NAME = "service_util_name";
private static final String MODEL_NAME = "model_name";
private static final String DATA = "data";
private static final String ID = "id";
private static final String STATUS = "status";
private static final String CODE = "code";
private static final String CONFIG = "config";
private static final String FILTER = "filter";
private static final String RESPONE = "respone";
private static final String COMPARE = "compare";
private static final String COUNTER = "counter";
private static final String END = "end";
private static final String START = "start";
private static final String COMPANY_ID = "companyId";
private static final String DYNAMIC_QUERY = "dynamicQuery";
private static final String RESPONSE_TYPE = "responeType";
private static final String DETAIL = "detail";
private static final String TITLE = "title";
private static final String COLUMN = "column";
private static final String COLUMNS = "columns";
private static final String LIST_TABLE_MENU = "listTableMenu";
private static final String PUBLIC_MANAGER = "publicManager";
private static final String MENU = "menu";
private static final String NAME = "name";
private static final String VALUE_FILTER = "value_filter";
private static final String NUMBER = "number";
private static final String AUTO_COMPLETE = "autocomplete";
private static final String TYPE_INT = "int";
private static final String DATA_TYPE = "data_type";
private static final String KEY = "key";
private static final String CHECK_BOX = "checkbox";
private static final String QUERY_LIKE = "like";
private static final String COMPARE_LT = "lt";
private static final String COMPARE_LE = "le";
private static final String COMPARE_GT = "gt";
private static final String COMPARE_GE = "ge";
private static final String LOCAL_ACCESSS = "localaccess";
private static final String P_AUTH = "Token";
private static final String USER_REQUEST_ID = "userid";
private static final String USER_ID = "USER_ID";
private static final String CLASSNAME_WORKING_UNIT = "opencps_workingunit";
private static final String CLASSNAME_APPLICANT = "opencps_applicant";
private static final String HEARDER_NAME = "headersName";
private static final String DETAIL_COLUMN = "detailColumns";
private static final String EXT_FORM = "extForm";
private static final String DEPENDENCY_TITLE = "dependency_title";
private static final String DEPENDENCY_LINK = "dependency_link";
private static final String DYNAMIC_COUNT = "dynamicQueryCount";
private static final String PROCESS_DELETE = "adminProcessDelete";
// private static final String PROCESS_DATA = "adminProcessData";
private static final String HEADERS = "headers";
private static final String CLASSNAME_EMPLOYEE = "opencps_employee";
private static final String ACCEPT = "Accept";
@Override
public Response onMessage(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User u,
ServiceContext serviceContext, String text) {
JSONObject messageData = JSONFactoryUtil.createJSONObject();
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
//String portalURL = PortalUtil.getPortalURL(request);
try {
JSONObject message = JSONFactoryUtil.createJSONObject(text);
_log.debug("SOCKET MESSAGE: " + message.toJSONString());
try {
if (message.getString(TYPE).equals(ADMIN)) {
String code = message.getString(CODE);
AdminConfig adminConfig = AdminConfigLocalServiceUtil.fetchByCode(code);
String bunderStr;
String modelStr;
String serviceUtilStr;
if (Validator.isNull(adminConfig)) {
bunderStr = message.getString(BUNDLE_NAME);
modelStr = message.getString(MODEL_NAME);
serviceUtilStr = message.getString(SERVICE_UTIL_NAME);
} else {
bunderStr = adminConfig.getBundleName();
modelStr = adminConfig.getModelName();
serviceUtilStr = adminConfig.getServiceUtilName();
}
BundleLoader bundleLoader = new BundleLoader(bunderStr != null ? bunderStr : StringPool.BLANK);
Class<?> model = bundleLoader.getClassLoader().loadClass(modelStr != null ? modelStr : StringPool.BLANK);
Method method = null;
int lengColumns = 0;
if (message.getString(CMD).equals(GET)) {
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr != null ? serviceUtilStr : StringPool.BLANK).getMethod(DYNAMIC_QUERY);
DynamicQuery dynamicQuery = (DynamicQuery) method.invoke(model);
if (Validator.isNotNull(adminConfig) && !DETAIL.equals(message.getString(RESPONSE_TYPE))) {
String columns = adminConfig.getColumns();
JSONArray arraysColumn = JSONFactoryUtil.createJSONArray(columns);
if (arraysColumn.length() > 0) {
lengColumns = arraysColumn.length();
ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
for (int i = 0; i < arraysColumn.length(); i++) {
JSONObject column = arraysColumn.getJSONObject(i);
projectionList.add(ProjectionFactoryUtil.property(column.getString(COLUMN)));
}
if (LIST_TABLE_MENU.equals(message.getString(RESPONE))) {
projectionList.add(ProjectionFactoryUtil.property(PUBLIC_MANAGER));
}
dynamicQuery.setProjection(projectionList);
}
} else if (MENU.equals(message.getString(RESPONSE_TYPE))) {
ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
projectionList.add(ProjectionFactoryUtil.property(CODE));
projectionList.add(ProjectionFactoryUtil.property(NAME));
dynamicQuery.setProjection(projectionList);
}
if (Validator.isNotNull(message.getJSONArray(FILTER))
&& message.getJSONArray(FILTER).length() > 0) {
for (int i = 0; i < message.getJSONArray(FILTER).length(); i++) {
JSONObject filter = message.getJSONArray(FILTER).getJSONObject(i);
if (Validator.isNotNull(filter.getString(VALUE_FILTER))
&& filter.getString(VALUE_FILTER).length() > 0) {
if (StringPool.EQUAL.equals(filter.getString(COMPARE))) {
if (NUMBER.equals(filter.getString(TYPE)) || AUTO_COMPLETE.equals(filter.getString(TYPE))) {
if (filter.getBoolean(TYPE_INT)) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getInt(VALUE_FILTER)));
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getLong(VALUE_FILTER)));
}
} else if (CHECK_BOX.equals(filter.getString(TYPE))) {
if (TYPE_INT.equals(filter.getString(DATA_TYPE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getBoolean(VALUE_FILTER) ? 1 : 0));
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getBoolean(VALUE_FILTER)));
}
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getString(VALUE_FILTER)));
}
} else if (QUERY_LIKE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(
PropertyFactoryUtil.forName(filter.getString(KEY)).like(StringPool.PERCENT
+ filter.getString(VALUE_FILTER) + StringPool.PERCENT));
} else if (COMPARE_LT.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.lt(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_LE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.le(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_GT.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.gt(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_GE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.ge(filter.getLong(VALUE_FILTER)));
}
}
}
}
if (groupId > 0 && adminConfig.getGroupFilter()) {
Disjunction disjunction = RestrictionsFactoryUtil.disjunction();
if (Validator.isNotNull(code)
&& (CLASSNAME_WORKING_UNIT.equals(code) || CLASSNAME_APPLICANT.equals(code))) {
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, groupId));
} else {
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, 0l));
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, groupId));
}
dynamicQuery.add(disjunction);
}
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(DYNAMIC_QUERY,
DynamicQuery.class, int.class, int.class);
messageData.put(STATUS, HttpStatus.OK);
JSONObject headersObj = JSONFactoryUtil.createJSONObject(adminConfig.getHeadersName());
// System.out.println("code: " + code.equals("opencps_employee"));
_log.debug("code: " + "opencps_employee".equalsIgnoreCase(code));
if (message.getBoolean(CONFIG)) {
JSONObject config = JSONFactoryUtil.createJSONObject();
config.put(CODE, adminConfig.getCode());
config.put(NAME, adminConfig.getName());
config.put(HEARDER_NAME, headersObj.getJSONArray(HEADERS));
config.put(COLUMNS, adminConfig.getColumns());
config.put(DETAIL_COLUMN, adminConfig.getDetailColumns());
config.put(EXT_FORM, adminConfig.getExtForm());
config.put(DEPENDENCY_TITLE, headersObj.get(DEPENDENCY_TITLE));
config.put(DEPENDENCY_LINK, headersObj.get(DEPENDENCY_LINK));
messageData.put(message.getString(RESPONE), config);
} else if (message.getBoolean(COUNTER)) {
Method methodCounter = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(DYNAMIC_COUNT,
DynamicQuery.class);
messageData.put(message.getString(RESPONE), methodCounter.invoke(model, dynamicQuery));
} else {
int start = Validator.isNotNull(message.getString(START)) ? message.getInt(START) : 0;
int end = Validator.isNotNull(message.getString(END)) ? message.getInt(END) : 1;
if (CLASSNAME_EMPLOYEE.equals(code)) {
@SuppressWarnings("unchecked")
List<Object[]> employees = (List<Object[]>) method.invoke(model, dynamicQuery, start, end);
_log.debug("employees: " + employees);
if (lengColumns > 0) {
for (Object[] obj: employees) {
_log.debug("obj[lengColumns - 1]: " + obj[lengColumns - 1]);
if (Validator.isNotNull(obj[lengColumns - 1])) {
long userIdMapping = (long) obj[lengColumns - 1];
User user = UserLocalServiceUtil.fetchUser(userIdMapping);
if (user != null && user.getLoginDate() != null) {
obj[lengColumns - 1] = convertDateToString(user.getLoginDate());
}
}
}
}
// System.out.println("employees.employees()" + employees);
messageData.put(message.getString(RESPONE), employees);
} else {
messageData.put(message.getString(RESPONE), method.invoke(model, dynamicQuery, start, end));
}
}
messageData.put(TITLE, headersObj.getString(TITLE));
} else {
if (message.getString(CMD).equals(DELETE)) {
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(PROCESS_DELETE,
Long.class);
messageData.put(message.getString(RESPONE), method.invoke(model, message.getLong(ID)));
messageData.put(STATUS, HttpStatus.OK);
} else {
// method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(PROCESS_DATA,
// JSONObject.class);
JSONObject postData = message.getJSONObject(DATA);
postData.put(Field.GROUP_ID, groupId);
postData.put(COMPANY_ID, company.getCompanyId());
postData.put(Field.USER_ID, u.getUserId());
postData.put(Field.USER_NAME, u.getFullName());
messageData.put(STATUS, HttpStatus.OK);
}
}
} else if (message.getString(TYPE).equals(API)) {
// RestTemplate restTemplate = new RestTemplate();
//
// restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
//
// org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
//
// headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
//
// JSONObject headerObject = message.getJSONObject("headers");
//
// JSONArray keys = headerObject.names();
//
// for (int i = 0; i < keys.length(); ++i) {
//
// String key = keys.getString(i);
// String value = headerObject.getString(key);
//
// headers.set(key, value);
//
// }
// headers.set("localaccess", headerObject.getString("Token"));
// headers.set("userid", headerObject.getString("USER_ID"));
//
// HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
//
// HttpEntity<String> response = restTemplate.exchange(portalURL + message.getString("api"),
// HttpMethod.GET, entity, String.class);
//
// String resultString = response.getBody();
//
// JSONArray responeData = JSONFactoryUtil.createJSONArray();
// try {
// responeData = JSONFactoryUtil.createJSONObject(resultString).getJSONArray("data");
// } catch (Exception e) {
// _log.debug(e);
// responeData = JSONFactoryUtil.createJSONArray(resultString);
// }
// messageData.put(message.getString(RESPONE), responeData);
//
// messageData.put(STATUS, HttpStatus.OK);
// String apiUrl = StringPool.BLANK;
String apiUrl;
StringBuilder sb = new StringBuilder();
try
{
URL urlVal = null;
apiUrl = OpenCPSConfigUtil.getAdminProxyUrl() + message.getString(API);
urlVal = new URL(apiUrl);
JSONObject headerObject = message.getJSONObject(HEADERS);
HttpURLConnection conn = (HttpURLConnection) urlVal.openConnection();
JSONArray keys = headerObject.names();
for (int i = 0; i < keys.length(); ++i) {
String key = keys.getString(i);
String value = headerObject.getString(key);
conn.setRequestProperty(key, value);
}
conn.setRequestProperty(LOCAL_ACCESSS, headerObject.getString(P_AUTH));
conn.setRequestProperty(USER_REQUEST_ID, headerObject.getString(USER_ID));
conn.setRequestMethod(message.getString(CMD).toUpperCase());
conn.setRequestProperty(ACCEPT, ConstantUtils.CONTENT_TYPE_JSON);
conn.setRequestProperty(ConstantUtils.CONTENT_TYPE,
ConstantUtils.CONTENT_TYPE_JSON);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(OpenCPSConfigUtil.getRestConnectionTimeout());
conn.setReadTimeout(OpenCPSConfigUtil.getRestReadTimeout());
BufferedReader brf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int cp;
while ((cp = brf.read()) != -1) {
sb.append((char) cp);
}
JSONArray responeData = JSONFactoryUtil.createJSONArray();
try {
responeData = JSONFactoryUtil.createJSONObject(sb.toString()).getJSONArray(ConstantUtils.DATA);
} catch (Exception e) {
_log.debug(e);
responeData = JSONFactoryUtil.createJSONArray(sb.toString());
}
messageData.put(message.getString(RESPONE), responeData);
messageData.put(STATUS, HttpStatus.OK);
conn.disconnect();
}
catch(IOException e)
{
_log.debug("Something went wrong while reading/writing in stream!!");
_log.debug(e);
}
}
messageData.put(RESPONE, message.getString(RESPONE));
messageData.put(CMD, message.getString(CMD));
} catch (Exception e) {
_log.debug(e);
messageData.put(STATUS, HttpStatus.INTERNAL_SERVER_ERROR);
messageData.put(RESPONE, message.getString(RESPONE));
messageData.put(CMD, message.getString(CMD));
}
messageData.put(TYPE, message.getString(TYPE));
return Response.status(HttpURLConnection.HTTP_OK).entity(messageData.toJSONString()).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
}
|
modules/backend-api-rest/src/main/java/org/opencps/api/controller/impl/AdminConfigManagementImpl.java
|
package org.opencps.api.controller.impl;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.dao.orm.Disjunction;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
import com.liferay.portal.kernel.dao.orm.ProjectionList;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.UserLocalServiceUtil;
import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.TimeZoneUtil;
import com.liferay.portal.kernel.util.Validator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.opencps.adminconfig.model.AdminConfig;
import org.opencps.adminconfig.service.AdminConfigLocalServiceUtil;
import org.opencps.api.constants.ConstantUtils;
import org.opencps.api.controller.AdminConfigManagement;
import org.opencps.dossiermgt.action.util.OpenCPSConfigUtil;
import org.opencps.dossiermgt.action.util.ReadFilePropertiesUtils;
import org.springframework.http.HttpStatus;
import backend.admin.config.whiteboard.BundleLoader;
import backend.auth.api.exception.BusinessExceptionImpl;
public class AdminConfigManagementImpl implements AdminConfigManagement {
private static String convertDateToString(Date date) {
DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(_TIMESTAMP);
if (Validator.isNull(date) || Validator.isNull(_TIMESTAMP)) {
return StringPool.BLANK;
}
dateFormat.setTimeZone(TimeZoneUtil.getTimeZone(ConstantUtils.TIMEZONE_ASIA_HOCHIMINH));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return dateFormat.format(calendar.getTime());
}
public static final String _TIMESTAMP = "dd/MM/yyyy HH:mm";
private static final Log _log = LogFactoryUtil.getLog(AdminConfigManagementImpl.class);
private static final String TYPE = "type";
private static final String CMD = "cmd";
private static final String GET = "get";
private static final String DELETE = "delete";
private static final String ADMIN = "admin";
private static final String API = "api";
private static final String BUNDLE_NAME = "bundle_name";
private static final String SERVICE_UTIL_NAME = "service_util_name";
private static final String MODEL_NAME = "model_name";
private static final String DATA = "data";
private static final String ID = "id";
private static final String STATUS = "status";
private static final String CODE = "code";
private static final String CONFIG = "config";
private static final String FILTER = "filter";
private static final String RESPONE = "respone";
private static final String COMPARE = "compare";
private static final String COUNTER = "counter";
private static final String END = "end";
private static final String START = "start";
private static final String COMPANY_ID = "companyId";
private static final String DYNAMIC_QUERY = "dynamicQuery";
private static final String RESPONSE_TYPE = "responeType";
private static final String DETAIL = "detail";
private static final String TITLE = "title";
private static final String COLUMN = "column";
private static final String LIST_TABLE_MENU = "listTableMenu";
private static final String PUBLIC_MANAGER = "publicManager";
private static final String MENU = "menu";
private static final String NAME = "name";
private static final String VALUE_FILTER = "value_filter";
private static final String NUMBER = "number";
private static final String AUTO_COMPLETE = "autocomplete";
private static final String TYPE_INT = "int";
private static final String DATA_TYPE = "data_type";
private static final String KEY = "key";
private static final String CHECK_BOX = "checkbox";
private static final String QUERY_LIKE = "like";
private static final String COMPARE_LT = "lt";
private static final String COMPARE_LE = "le";
private static final String COMPARE_GT = "gt";
private static final String COMPARE_GE = "ge";
private static final String LOCAL_ACCESSS = "localaccess";
private static final String P_AUTH = "Token";
private static final String USER_REQUEST_ID = "userid";
private static final String USER_ID = "USER_ID";
private static final String CLASSNAME_WORKING_UNIT = "opencps_workingunit";
private static final String CLASSNAME_APPLICANT = "opencps_applicant";
private static final String HEARDER_NAME = "headersName";
private static final String DETAIL_COLUMN = "detailColumns";
private static final String EXT_FORM = "extForm";
private static final String DEPENDENCY_TITLE = "dependency_title";
private static final String DEPENDENCY_LINK = "dependency_link";
private static final String DYNAMIC_COUNT = "dynamicQueryCount";
private static final String PROCESS_DELETE = "adminProcessDelete";
// private static final String PROCESS_DATA = "adminProcessData";
private static final String HEADERS = "headers";
private static final String CLASSNAME_EMPLOYEE = "opencps_employee";
private static final String ACCEPT = "Accept";
@Override
public Response onMessage(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User u,
ServiceContext serviceContext, String text) {
JSONObject messageData = JSONFactoryUtil.createJSONObject();
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
//String portalURL = PortalUtil.getPortalURL(request);
try {
JSONObject message = JSONFactoryUtil.createJSONObject(text);
_log.debug("SOCKET MESSAGE: " + message.toJSONString());
try {
if (message.getString(TYPE).equals(ADMIN)) {
String code = message.getString(CODE);
AdminConfig adminConfig = AdminConfigLocalServiceUtil.fetchByCode(code);
String bunderStr;
String modelStr;
String serviceUtilStr;
if (Validator.isNull(adminConfig)) {
bunderStr = message.getString(BUNDLE_NAME);
modelStr = message.getString(MODEL_NAME);
serviceUtilStr = message.getString(SERVICE_UTIL_NAME);
} else {
bunderStr = adminConfig.getBundleName();
modelStr = adminConfig.getModelName();
serviceUtilStr = adminConfig.getServiceUtilName();
}
BundleLoader bundleLoader = new BundleLoader(bunderStr != null ? bunderStr : StringPool.BLANK);
Class<?> model = bundleLoader.getClassLoader().loadClass(modelStr != null ? modelStr : StringPool.BLANK);
Method method = null;
int lengColumns = 0;
if (message.getString(CMD).equals(GET)) {
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr != null ? serviceUtilStr : StringPool.BLANK).getMethod(DYNAMIC_QUERY);
DynamicQuery dynamicQuery = (DynamicQuery) method.invoke(model);
if (Validator.isNotNull(adminConfig) && !DETAIL.equals(message.getString(RESPONSE_TYPE))) {
String columns = adminConfig.getColumns();
JSONArray arraysColumn = JSONFactoryUtil.createJSONArray(columns);
if (arraysColumn.length() > 0) {
lengColumns = arraysColumn.length();
ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
for (int i = 0; i < arraysColumn.length(); i++) {
JSONObject column = arraysColumn.getJSONObject(i);
projectionList.add(ProjectionFactoryUtil.property(column.getString(COLUMN)));
}
if (LIST_TABLE_MENU.equals(message.getString(RESPONE))) {
projectionList.add(ProjectionFactoryUtil.property(PUBLIC_MANAGER));
}
dynamicQuery.setProjection(projectionList);
}
} else if (MENU.equals(message.getString(RESPONSE_TYPE))) {
ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
projectionList.add(ProjectionFactoryUtil.property(CODE));
projectionList.add(ProjectionFactoryUtil.property(NAME));
dynamicQuery.setProjection(projectionList);
}
if (Validator.isNotNull(message.getJSONArray(FILTER))
&& message.getJSONArray(FILTER).length() > 0) {
for (int i = 0; i < message.getJSONArray(FILTER).length(); i++) {
JSONObject filter = message.getJSONArray(FILTER).getJSONObject(i);
if (Validator.isNotNull(filter.getString(VALUE_FILTER))
&& filter.getString(VALUE_FILTER).length() > 0) {
if (StringPool.EQUAL.equals(filter.getString(COMPARE))) {
if (NUMBER.equals(filter.getString(TYPE)) || AUTO_COMPLETE.equals(filter.getString(TYPE))) {
if (filter.getBoolean(TYPE_INT)) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getInt(VALUE_FILTER)));
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getLong(VALUE_FILTER)));
}
} else if (CHECK_BOX.equals(filter.getString(TYPE))) {
if (TYPE_INT.equals(filter.getString(DATA_TYPE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getBoolean(VALUE_FILTER) ? 1 : 0));
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getBoolean(VALUE_FILTER)));
}
} else {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.eq(filter.getString(VALUE_FILTER)));
}
} else if (QUERY_LIKE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(
PropertyFactoryUtil.forName(filter.getString(KEY)).like(StringPool.PERCENT
+ filter.getString(VALUE_FILTER) + StringPool.PERCENT));
} else if (COMPARE_LT.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.lt(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_LE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.le(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_GT.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.gt(filter.getLong(VALUE_FILTER)));
} else if (COMPARE_GE.equals(filter.getString(COMPARE))) {
dynamicQuery.add(PropertyFactoryUtil.forName(filter.getString(KEY))
.ge(filter.getLong(VALUE_FILTER)));
}
}
}
}
if (groupId > 0 && adminConfig.getGroupFilter()) {
Disjunction disjunction = RestrictionsFactoryUtil.disjunction();
if (Validator.isNotNull(code)
&& (CLASSNAME_WORKING_UNIT.equals(code) || CLASSNAME_APPLICANT.equals(code))) {
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, groupId));
} else {
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, 0l));
disjunction.add(RestrictionsFactoryUtil.eq(Field.GROUP_ID, groupId));
}
dynamicQuery.add(disjunction);
}
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(DYNAMIC_QUERY,
DynamicQuery.class, int.class, int.class);
messageData.put(STATUS, HttpStatus.OK);
JSONObject headersObj = JSONFactoryUtil.createJSONObject(adminConfig.getHeadersName());
// System.out.println("code: " + code.equals("opencps_employee"));
_log.debug("code: " + "opencps_employee".equalsIgnoreCase(code));
if (message.getBoolean(CONFIG)) {
JSONObject config = JSONFactoryUtil.createJSONObject();
config.put(CODE, adminConfig.getCode());
config.put(NAME, adminConfig.getName());
config.put(HEARDER_NAME, headersObj.getJSONArray(HEADERS));
config.put(COLUMN, adminConfig.getColumns());
config.put(DETAIL_COLUMN, adminConfig.getDetailColumns());
config.put(EXT_FORM, adminConfig.getExtForm());
config.put(DEPENDENCY_TITLE, headersObj.get(DEPENDENCY_TITLE));
config.put(DEPENDENCY_LINK, headersObj.get(DEPENDENCY_LINK));
messageData.put(message.getString(RESPONE), config);
} else if (message.getBoolean(COUNTER)) {
Method methodCounter = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(DYNAMIC_COUNT,
DynamicQuery.class);
messageData.put(message.getString(RESPONE), methodCounter.invoke(model, dynamicQuery));
} else {
int start = Validator.isNotNull(message.getString(START)) ? message.getInt(START) : 0;
int end = Validator.isNotNull(message.getString(END)) ? message.getInt(END) : 1;
if (CLASSNAME_EMPLOYEE.equals(code)) {
@SuppressWarnings("unchecked")
List<Object[]> employees = (List<Object[]>) method.invoke(model, dynamicQuery, start, end);
_log.debug("employees: " + employees);
if (lengColumns > 0) {
for (Object[] obj: employees) {
_log.debug("obj[lengColumns - 1]: " + obj[lengColumns - 1]);
if (Validator.isNotNull(obj[lengColumns - 1])) {
long userIdMapping = (long) obj[lengColumns - 1];
User user = UserLocalServiceUtil.fetchUser(userIdMapping);
if (user != null && user.getLoginDate() != null) {
obj[lengColumns - 1] = convertDateToString(user.getLoginDate());
}
}
}
}
// System.out.println("employees.employees()" + employees);
messageData.put(message.getString(RESPONE), employees);
} else {
messageData.put(message.getString(RESPONE), method.invoke(model, dynamicQuery, start, end));
}
}
messageData.put(TITLE, headersObj.getString(TITLE));
} else {
if (message.getString(CMD).equals(DELETE)) {
method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(PROCESS_DELETE,
Long.class);
messageData.put(message.getString(RESPONE), method.invoke(model, message.getLong(ID)));
messageData.put(STATUS, HttpStatus.OK);
} else {
// method = bundleLoader.getClassLoader().loadClass(serviceUtilStr).getMethod(PROCESS_DATA,
// JSONObject.class);
JSONObject postData = message.getJSONObject(DATA);
postData.put(Field.GROUP_ID, groupId);
postData.put(COMPANY_ID, company.getCompanyId());
postData.put(Field.USER_ID, u.getUserId());
postData.put(Field.USER_NAME, u.getFullName());
messageData.put(STATUS, HttpStatus.OK);
}
}
} else if (message.getString(TYPE).equals(API)) {
// RestTemplate restTemplate = new RestTemplate();
//
// restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
//
// org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
//
// headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
//
// JSONObject headerObject = message.getJSONObject("headers");
//
// JSONArray keys = headerObject.names();
//
// for (int i = 0; i < keys.length(); ++i) {
//
// String key = keys.getString(i);
// String value = headerObject.getString(key);
//
// headers.set(key, value);
//
// }
// headers.set("localaccess", headerObject.getString("Token"));
// headers.set("userid", headerObject.getString("USER_ID"));
//
// HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
//
// HttpEntity<String> response = restTemplate.exchange(portalURL + message.getString("api"),
// HttpMethod.GET, entity, String.class);
//
// String resultString = response.getBody();
//
// JSONArray responeData = JSONFactoryUtil.createJSONArray();
// try {
// responeData = JSONFactoryUtil.createJSONObject(resultString).getJSONArray("data");
// } catch (Exception e) {
// _log.debug(e);
// responeData = JSONFactoryUtil.createJSONArray(resultString);
// }
// messageData.put(message.getString(RESPONE), responeData);
//
// messageData.put(STATUS, HttpStatus.OK);
// String apiUrl = StringPool.BLANK;
String apiUrl;
StringBuilder sb = new StringBuilder();
try
{
URL urlVal = null;
apiUrl = OpenCPSConfigUtil.getAdminProxyUrl() + message.getString(API);
urlVal = new URL(apiUrl);
JSONObject headerObject = message.getJSONObject(HEADERS);
HttpURLConnection conn = (HttpURLConnection) urlVal.openConnection();
JSONArray keys = headerObject.names();
for (int i = 0; i < keys.length(); ++i) {
String key = keys.getString(i);
String value = headerObject.getString(key);
conn.setRequestProperty(key, value);
}
conn.setRequestProperty(LOCAL_ACCESSS, headerObject.getString(P_AUTH));
conn.setRequestProperty(USER_REQUEST_ID, headerObject.getString(USER_ID));
conn.setRequestMethod(message.getString(CMD).toUpperCase());
conn.setRequestProperty(ACCEPT, ConstantUtils.CONTENT_TYPE_JSON);
conn.setRequestProperty(ConstantUtils.CONTENT_TYPE,
ConstantUtils.CONTENT_TYPE_JSON);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(OpenCPSConfigUtil.getRestConnectionTimeout());
conn.setReadTimeout(OpenCPSConfigUtil.getRestReadTimeout());
BufferedReader brf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int cp;
while ((cp = brf.read()) != -1) {
sb.append((char) cp);
}
JSONArray responeData = JSONFactoryUtil.createJSONArray();
try {
responeData = JSONFactoryUtil.createJSONObject(sb.toString()).getJSONArray(ConstantUtils.DATA);
} catch (Exception e) {
_log.debug(e);
responeData = JSONFactoryUtil.createJSONArray(sb.toString());
}
messageData.put(message.getString(RESPONE), responeData);
messageData.put(STATUS, HttpStatus.OK);
conn.disconnect();
}
catch(IOException e)
{
_log.debug("Something went wrong while reading/writing in stream!!");
_log.debug(e);
}
}
messageData.put(RESPONE, message.getString(RESPONE));
messageData.put(CMD, message.getString(CMD));
} catch (Exception e) {
_log.debug(e);
messageData.put(STATUS, HttpStatus.INTERNAL_SERVER_ERROR);
messageData.put(RESPONE, message.getString(RESPONE));
messageData.put(CMD, message.getString(CMD));
}
messageData.put(TYPE, message.getString(TYPE));
return Response.status(HttpURLConnection.HTTP_OK).entity(messageData.toJSONString()).build();
} catch (Exception e) {
return BusinessExceptionImpl.processException(e);
}
}
}
|
Update admin config security
|
modules/backend-api-rest/src/main/java/org/opencps/api/controller/impl/AdminConfigManagementImpl.java
|
Update admin config security
|
|
Java
|
agpl-3.0
|
18202bffbd9ffbc6d57e3c1e54ab703355a2417b
| 0
|
Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.zetime;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.net.Uri;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeConstants;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeSampleProvider;
import nodomain.freeyourgadget.gadgetbridge.entities.ZeTimeActivitySample;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.Weather;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
/**
* Created by Kranz on 08.02.2018.
*/
public class ZeTimeDeviceSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(ZeTimeDeviceSupport.class);
private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
private final GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
private final GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
private final int sixHourOffset = 21600;
private byte[] lastMsg;
private byte msgPart;
private int availableSleepData;
private int availableStepsData;
private int availableHeartRateData;
private int progressSteps;
private int progressSleep;
private int progressHeartRate;
private final int maxMsgLength = 20;
private boolean callIncoming = false;
private String songtitle = null;
private byte musicState = -1;
public byte[] music = null;
public byte volume = 50;
public BluetoothGattCharacteristic notifyCharacteristic = null;
public BluetoothGattCharacteristic writeCharacteristic = null;
public BluetoothGattCharacteristic ackCharacteristic = null;
public BluetoothGattCharacteristic replyCharacteristic = null;
public ZeTimeDeviceSupport(){
super(LOG);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_BASE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_EXTEND);
addSupportedService(ZeTimeConstants.UUID_SERVICE_HEART_RATE);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
LOG.info("Initializing");
msgPart = 0;
availableStepsData = 0;
availableHeartRateData = 0;
availableSleepData = 0;
progressSteps = 0;
progressSleep = 0;
progressHeartRate = 0;
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZING, getContext()));
notifyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC);
writeCharacteristic = getCharacteristic(ZeTimeConstants.UUID_WRITE_CHARACTERISTIC);
ackCharacteristic = getCharacteristic(ZeTimeConstants.UUID_ACK_CHARACTERISTIC);
replyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_REPLY_CHARACTERISTIC);
builder.notify(ackCharacteristic, true);
builder.notify(notifyCharacteristic, true);
requestDeviceInfo(builder);
requestBatteryInfo(builder);
requestActivityInfo(builder);
synchronizeTime(builder);
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZED, getContext()));
LOG.info("Initialization Done");
return builder;
}
@Override
public void onSendConfiguration(String config) {
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
}
@Override
public void onHeartRateTest() {
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
}
@Override
public void onFindDevice(boolean start) {
}
@Override
public boolean useAutoConnect() {
return false;
}
@Override
public void onSetHeartRateMeasurementInterval(int seconds) {
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
}
@Override
public void onAppConfiguration(UUID appUuid, String config, Integer id) {
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
songtitle = musicSpec.track;
if(musicState != -1) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
music[5] = musicState;
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onSetCallState(CallSpec callSpec) {
int subject_length = 0;
int notification_length = 0;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
// convert every single digit of the date to ascii characters
// we do it like so: use the base chrachter of '0' and add the digit
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
if(callIncoming || (callSpec.command == CallSpec.CALL_INCOMING)) {
if (callSpec.command == CallSpec.CALL_INCOMING) {
if (callSpec.name != null) {
notification_length += callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.name.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if (callSpec.number != null) {
notification_length += callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.number.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_INCOME_CALL;
notification[6] = 1;
notification[7] = (byte) subject_length;
notification[8] = (byte) 0;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(datetimeBytes, 0, notification, 9 + subject_length, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = true;
} else {
notification_length = datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_CALL_OFF;
notification[6] = 1;
notification[7] = (byte) 0;
notification[8] = (byte) 0;
System.arraycopy(datetimeBytes, 0, notification, 9, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = false;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("setCallState");
sendMsgToWatch(builder, notification);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error set call state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAppStart(UUID uuid, boolean start) {
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
}
@Override
public void onSetConstantVibration(int integer) {
}
@Override
public void onFetchRecordedData(int dataTypes) {
try {
TransactionBuilder builder = performInitialized("fetchActivityData");
requestActivityInfo(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error on fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onTestNewFunction() {
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
musicState = stateSpec.state;
if(songtitle != null) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
if (stateSpec.state == MusicStateSpec.STATE_PLAYING) {
music[5] = 0;
} else {
music[5] = 1;
}
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
Calendar time = GregorianCalendar.getInstance();
byte[] CalendarEvent = new byte[calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 16]; // 26 bytes for calendar and overhead
time.setTimeInMillis(calendarEventSpec.timestamp);
CalendarEvent[0] = ZeTimeConstants.CMD_PREAMBLE;
CalendarEvent[1] = ZeTimeConstants.CMD_PUSH_CALENDAR_DAY;
CalendarEvent[2] = ZeTimeConstants.CMD_SEND;
CalendarEvent[3] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) & 0xff);
CalendarEvent[4] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) >> 8);
CalendarEvent[5] = (byte)(calendarEventSpec.type + 0x1);
CalendarEvent[6] = (byte)(time.get(Calendar.YEAR) & 0xff);
CalendarEvent[7] = (byte)(time.get(Calendar.YEAR) >> 8);
CalendarEvent[8] = (byte)(time.get(Calendar.MONTH)+1);
CalendarEvent[9] = (byte)time.get(Calendar.DAY_OF_MONTH);
CalendarEvent[10] = (byte) (time.get(Calendar.HOUR_OF_DAY) & 0xff);
CalendarEvent[11] = (byte) (time.get(Calendar.HOUR_OF_DAY) >> 8);
CalendarEvent[12] = (byte) (time.get(Calendar.MINUTE) & 0xff);
CalendarEvent[13] = (byte) (time.get(Calendar.MINUTE) >> 8);
CalendarEvent[14] = (byte) calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length;
System.arraycopy(calendarEventSpec.title.getBytes(StandardCharsets.UTF_8), 0, CalendarEvent, 15, calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length);
CalendarEvent[CalendarEvent.length-1] = ZeTimeConstants.CMD_END;
if(CalendarEvent != null)
{
try {
TransactionBuilder builder = performInitialized("sendCalendarEvenr");
sendMsgToWatch(builder, CalendarEvent);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending calendar event: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("synchronizeTime");
synchronizeTime(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting the time: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onAppDelete(UUID uuid) {
}
@Override
public void onAppInfoReq() {
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
@Override
public void onReboot() {
}
@Override
public void onScreenshotReq() {
}
@Override
public void onSendWeather(WeatherSpec weatherSpec) {
byte[] weather = new byte[weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 26]; // 26 bytes for weatherdata and overhead
weather[0] = ZeTimeConstants.CMD_PREAMBLE;
weather[1] = ZeTimeConstants.CMD_PUSH_WEATHER_DATA;
weather[2] = ZeTimeConstants.CMD_SEND;
weather[3] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) & 0xff);
weather[4] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) >> 8);
weather[5] = 0; // celsius
weather[6] = (byte)(weatherSpec.currentTemp - 273);
weather[7] = (byte)(weatherSpec.todayMinTemp - 273);
weather[8] = (byte)(weatherSpec.todayMaxTemp - 273);
weather[9] = Weather.mapToZeTimeCondition(weatherSpec.currentConditionCode);
for(int forecast = 0; forecast < 3; forecast++) {
weather[10+(forecast*5)] = 0; // celsius
weather[11+(forecast*5)] = (byte) 0xff;
weather[12+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).minTemp - 273);
weather[13+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).maxTemp - 273);
weather[14+(forecast*5)] = Weather.mapToZeTimeCondition(weatherSpec.forecasts.get(forecast).conditionCode);
}
System.arraycopy(weatherSpec.location.getBytes(StandardCharsets.UTF_8), 0, weather, 25, weatherSpec.location.getBytes(StandardCharsets.UTF_8).length);
weather[weather.length-1] = ZeTimeConstants.CMD_END;
if(weather != null)
{
try {
TransactionBuilder builder = performInitialized("sendWeahter");
sendMsgToWatch(builder, weather);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending weather: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onAppReorder(UUID[] uuids) {
}
@Override
public void onInstallApp(Uri uri) {
}
@Override
public void onDeleteNotification(int id) {
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
int subject_length = 0;
int body_length = notificationSpec.body.getBytes(StandardCharsets.UTF_8).length;
if(body_length > 256)
{
body_length = 256;
}
int notification_length = body_length;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
// convert every single digit of the date to ascii characters
// we do it like so: use the base chrachter of '0' and add the digit
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.phoneNumber != null)
{
notification_length += notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.title != null)
{
notification_length += notificationSpec.title.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.title.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.title.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
switch(notificationSpec.type)
{
case GENERIC_SMS:
notification[5] = ZeTimeConstants.NOTIFICATION_SMS;
break;
case GENERIC_PHONE:
notification[5] = ZeTimeConstants.NOTIFICATION_MISSED_CALL;
break;
case GMAIL:
case GOOGLE_INBOX:
case MAILBOX:
case OUTLOOK:
case YAHOO_MAIL:
case GENERIC_EMAIL:
notification[5] = ZeTimeConstants.NOTIFICATION_EMAIL;
break;
case WECHAT:
notification[5] = ZeTimeConstants.NOTIFICATION_WECHAT;
break;
case VIBER:
notification[5] = ZeTimeConstants.NOTIFICATION_VIBER;
break;
case WHATSAPP:
notification[5] = ZeTimeConstants.NOTIFICATION_WHATSAPP;
break;
case FACEBOOK:
case FACEBOOK_MESSENGER:
notification[5] = ZeTimeConstants.NOTIFICATION_FACEBOOK;
break;
case GOOGLE_HANGOUTS:
notification[5] = ZeTimeConstants.NOTIFICATION_HANGOUTS;
break;
case LINE:
notification[5] = ZeTimeConstants.NOTIFICATION_LINE;
break;
case SKYPE:
notification[5] = ZeTimeConstants.NOTIFICATION_SKYPE;
break;
case CONVERSATIONS:
case RIOT:
case SIGNAL:
case TELEGRAM:
case THREEMA:
case KONTALK:
case ANTOX:
case GOOGLE_MESSENGER:
case HIPCHAT:
case KIK:
case KAKAO_TALK:
case SLACK:
notification[5] = ZeTimeConstants.NOTIFICATION_MESSENGER;
break;
case SNAPCHAT:
notification[5] = ZeTimeConstants.NOTIFICATION_SNAPCHAT;
break;
case INSTAGRAM:
notification[5] = ZeTimeConstants.NOTIFICATION_INSTAGRAM;
break;
case TWITTER:
notification[5] = ZeTimeConstants.NOTIFICATION_TWITTER;
break;
case LINKEDIN:
notification[5] = ZeTimeConstants.NOTIFICATION_LINKEDIN;
break;
case GENERIC_CALENDAR:
notification[5] = ZeTimeConstants.NOTIFICATION_CALENDAR;
break;
default:
notification[5] = ZeTimeConstants.NOTIFICATION_SOCIAL;
break;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("sendNotification");
sendMsgToWatch(builder, notification);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending notification: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID characteristicUUID = characteristic.getUuid();
if (ZeTimeConstants.UUID_ACK_CHARACTERISTIC.equals(characteristicUUID)) {
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1]) {
case ZeTimeConstants.CMD_WATCH_ID:
break;
case ZeTimeConstants.CMD_DEVICE_VERSION:
handleDeviceInfo(data);
break;
case ZeTimeConstants.CMD_BATTERY_POWER:
handleBatteryInfo(data);
break;
case ZeTimeConstants.CMD_SHOCK_STRENGTH:
break;
case ZeTimeConstants.CMD_AVAIABLE_DATA:
handleActivityFetching(data);
break;
case ZeTimeConstants.CMD_GET_STEP_COUNT:
handleStepsData(data);
break;
case ZeTimeConstants.CMD_GET_SLEEP_DATA:
handleSleepData(data);
break;
case ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA:
handleHeartRateData(data);
break;
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
}
return true;
} else if (ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC.equals(characteristicUUID))
{
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1])
{
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
return true;
}
}
else {
LOG.info("Unhandled characteristic changed: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
return false;
}
private boolean isMsgFormatOK(byte[] msg)
{
if(msg != null) {
if (msg[0] == ZeTimeConstants.CMD_PREAMBLE) {
if ((msg[3] != 0) || (msg[4] != 0)) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
int msgLength = payloadSize + 6;
if (msgLength == msg.length) {
if (msg[msgLength - 1] == ZeTimeConstants.CMD_END) {
return true;
}
}
}
}
}
return false;
}
private byte[] receiveCompleteMsg(byte[] msg)
{
if(msgPart == 0) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
if (payloadSize > 14) {
lastMsg = new byte[msg.length];
System.arraycopy(msg, 0, lastMsg, 0, msg.length);
msgPart++;
return null;
} else {
return msg;
}
} else
{
byte[] completeMsg = new byte[lastMsg.length + msg.length];
System.arraycopy(lastMsg, 0, completeMsg, 0, lastMsg.length);
System.arraycopy(msg, 0, completeMsg, lastMsg.length, msg.length);
msgPart = 0;
return completeMsg;
}
}
private ZeTimeDeviceSupport requestBatteryInfo(TransactionBuilder builder) {
LOG.debug("Requesting Battery Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_BATTERY_POWER,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestDeviceInfo(TransactionBuilder builder) {
LOG.debug("Requesting Device Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_WATCH_ID,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x05,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x02,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestActivityInfo(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_AVAIABLE_DATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestShockStrength(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_SHOCK_STRENGTH,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private void handleBatteryInfo(byte[] value) {
batteryCmd.level = ((short) value[5]);
if(batteryCmd.level <= 25)
{
batteryCmd.state = BatteryState.BATTERY_LOW;
} else
{
batteryCmd.state = BatteryState.BATTERY_NORMAL;
}
evaluateGBDeviceEvent(batteryCmd);
}
private void handleDeviceInfo(byte[] value) {
value[value.length-1] = 0; // convert the end to a String end
byte[] string = Arrays.copyOfRange(value,6, value.length-1);
if(value[5] == 5)
{
versionCmd.fwVersion = new String(string);
} else{
versionCmd.hwVersion = new String(string);
}
evaluateGBDeviceEvent(versionCmd);
}
private void handleActivityFetching(byte[] msg)
{
availableStepsData = (int) ((msg[5]&0xff) | (msg[6] << 8)&0xff00);
availableSleepData = (int) ((msg[7]&0xff) | (msg[8] << 8)&0xff00);
availableHeartRateData= (int) ((msg[9]&0xff) | (msg[10] << 8)&0xff00);
if(availableStepsData > 0){
getStepData();
} else if(availableHeartRateData > 0)
{
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
private void getStepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_STEP_COUNT,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getHeartRateData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getSleepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_SLEEP_DATA,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void handleStepsData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
int timestamp = (msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff);
timestamp += sixHourOffset; // the timestamp from the watch has an offset of six hours, do not know why...
sample.setTimestamp(timestamp);
sample.setSteps((msg[14] << 24)&0xff000000 | (msg[13] << 16)&0xff0000 | (msg[12] << 8)&0xff00 | (msg[11]&0xff));
sample.setCaloriesBurnt((msg[18] << 24)&0xff000000 | (msg[17] << 16)&0xff0000 | (msg[16] << 8)&0xff00 | (msg[15]&0xff));
sample.setDistanceMeters((msg[22] << 24)&0xff000000 | (msg[21] << 16)&0xff0000 | (msg[20] << 8)&0xff00 | (msg[19]&0xff));
sample.setActiveTimeMinutes((msg[26] << 24)&0xff000000 | (msg[25] << 16)&0xff0000 | (msg[24] << 8)&0xff00 | (msg[23]&0xff));
sample.setRawKind(ActivityKind.TYPE_ACTIVITY);
sample.setRawIntensity(sample.getSteps());
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSteps = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSteps *100 / availableStepsData), getContext());
if (progressSteps == availableStepsData) {
progressSteps = 0;
availableStepsData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableHeartRateData > 0) {
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void handleSleepData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
int timestamp = (msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff);
timestamp += sixHourOffset; // the timestamp from the watch has an offset of six hours, do not know why...
sample.setTimestamp(timestamp);
if(msg[11] == 0) {
sample.setRawKind(ActivityKind.TYPE_DEEP_SLEEP);
} else if(msg[11] == 1)
{
sample.setRawKind(ActivityKind.TYPE_LIGHT_SLEEP);
} else
{
sample.setRawKind(ActivityKind.TYPE_UNKNOWN);
}
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSleep = (msg[5]&0xff) | (msg[6] << 8)&0xff00;
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSleep *100 / availableSleepData), getContext());
if (progressSleep == availableSleepData) {
progressSleep = 0;
availableSleepData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
}
}
private void handleHeartRateData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
int timestamp = (msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff);
timestamp += sixHourOffset; // the timestamp from the watch has an offset of six hours, do not know why...
sample.setHeartRate(msg[11]);
sample.setTimestamp(timestamp);
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressHeartRate = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressHeartRate *100 / availableHeartRateData), getContext());
if (progressHeartRate == availableHeartRateData) {
progressHeartRate = 0;
availableHeartRateData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void sendMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(writeCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(writeCharacteristic, msg);
}
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
}
private void handleMusicControl(byte[] musicControlMsg)
{
if(musicControlMsg[2] == ZeTimeConstants.CMD_SEND) {
switch (musicControlMsg[5]) {
case 0: // play current song
musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
break;
case 1: // pause current song
musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
break;
case 2: // skip to previous song
musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
break;
case 3: // skip to next song
musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
break;
case 4: // change volume
if (musicControlMsg[6] > volume) {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
if(volume < 90) {
volume += 10;
}
} else {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
if(volume > 10) {
volume -= 10;
}
}
try {
TransactionBuilder builder = performInitialized("replyMusicVolume");
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music volume: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
break;
}
evaluateGBDeviceEvent(musicCmd);
} else {
if (music != null) {
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
try {
TransactionBuilder builder = performInitialized("replyMusicState");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
private void replyMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(replyCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(replyCharacteristic, msg);
}
}
private void synchronizeTime(TransactionBuilder builder)
{
Calendar now = GregorianCalendar.getInstance();
byte[] timeSync = new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DATE_TIME,
ZeTimeConstants.CMD_SEND,
0x0c,
0x00,
(byte)(now.get(Calendar.YEAR) & 0xff),
(byte)(now.get(Calendar.YEAR) >> 8),
(byte)(now.get(Calendar.MONTH) + 1),
(byte)now.get(Calendar.DAY_OF_MONTH),
(byte)now.get(Calendar.HOUR_OF_DAY),
(byte)now.get(Calendar.MINUTE),
(byte)now.get(Calendar.SECOND),
0x00, // is 24h
0x00, // SetTime after calibration
0x01, // Unit
(byte)((now.get(Calendar.ZONE_OFFSET)/3600000) + (now.get(Calendar.DST_OFFSET)/3600000)), // TimeZone hour + daylight saving
0x00, // TimeZone minute
ZeTimeConstants.CMD_END};
sendMsgToWatch(builder, timeSync);
}
}
|
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/zetime/ZeTimeDeviceSupport.java
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.zetime;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.net.Uri;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeConstants;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeSampleProvider;
import nodomain.freeyourgadget.gadgetbridge.entities.ZeTimeActivitySample;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.Weather;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
/**
* Created by Kranz on 08.02.2018.
*/
public class ZeTimeDeviceSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(ZeTimeDeviceSupport.class);
private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
private final GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
private final GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
private byte[] lastMsg;
private byte msgPart;
private int availableSleepData;
private int availableStepsData;
private int availableHeartRateData;
private int progressSteps;
private int progressSleep;
private int progressHeartRate;
private final int maxMsgLength = 20;
private boolean callIncoming = false;
private String songtitle = null;
private byte musicState = -1;
public byte[] music = null;
public byte volume = 50;
public BluetoothGattCharacteristic notifyCharacteristic = null;
public BluetoothGattCharacteristic writeCharacteristic = null;
public BluetoothGattCharacteristic ackCharacteristic = null;
public BluetoothGattCharacteristic replyCharacteristic = null;
public ZeTimeDeviceSupport(){
super(LOG);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_BASE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_EXTEND);
addSupportedService(ZeTimeConstants.UUID_SERVICE_HEART_RATE);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
LOG.info("Initializing");
msgPart = 0;
availableStepsData = 0;
availableHeartRateData = 0;
availableSleepData = 0;
progressSteps = 0;
progressSleep = 0;
progressHeartRate = 0;
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZING, getContext()));
notifyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC);
writeCharacteristic = getCharacteristic(ZeTimeConstants.UUID_WRITE_CHARACTERISTIC);
ackCharacteristic = getCharacteristic(ZeTimeConstants.UUID_ACK_CHARACTERISTIC);
replyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_REPLY_CHARACTERISTIC);
builder.notify(ackCharacteristic, true);
builder.notify(notifyCharacteristic, true);
requestDeviceInfo(builder);
requestBatteryInfo(builder);
requestActivityInfo(builder);
synchronizeTime(builder);
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZED, getContext()));
LOG.info("Initialization Done");
return builder;
}
@Override
public void onSendConfiguration(String config) {
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
}
@Override
public void onHeartRateTest() {
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
}
@Override
public void onFindDevice(boolean start) {
}
@Override
public boolean useAutoConnect() {
return false;
}
@Override
public void onSetHeartRateMeasurementInterval(int seconds) {
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
}
@Override
public void onAppConfiguration(UUID appUuid, String config, Integer id) {
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
songtitle = musicSpec.track;
if(musicState != -1) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
music[5] = musicState;
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onSetCallState(CallSpec callSpec) {
int subject_length = 0;
int notification_length = 0;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
// convert every single digit of the date to ascii characters
// we do it like so: use the base chrachter of '0' and add the digit
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
if(callIncoming || (callSpec.command == CallSpec.CALL_INCOMING)) {
if (callSpec.command == CallSpec.CALL_INCOMING) {
if (callSpec.name != null) {
notification_length += callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.name.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if (callSpec.number != null) {
notification_length += callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.number.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_INCOME_CALL;
notification[6] = 1;
notification[7] = (byte) subject_length;
notification[8] = (byte) 0;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(datetimeBytes, 0, notification, 9 + subject_length, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = true;
} else {
notification_length = datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_CALL_OFF;
notification[6] = 1;
notification[7] = (byte) 0;
notification[8] = (byte) 0;
System.arraycopy(datetimeBytes, 0, notification, 9, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = false;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("setCallState");
sendMsgToWatch(builder, notification);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error set call state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAppStart(UUID uuid, boolean start) {
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
}
@Override
public void onSetConstantVibration(int integer) {
}
@Override
public void onFetchRecordedData(int dataTypes) {
try {
TransactionBuilder builder = performInitialized("fetchActivityData");
requestActivityInfo(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error on fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onTestNewFunction() {
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
musicState = stateSpec.state;
if(songtitle != null) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
if (stateSpec.state == MusicStateSpec.STATE_PLAYING) {
music[5] = 0;
} else {
music[5] = 1;
}
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
Calendar time = GregorianCalendar.getInstance();
byte[] CalendarEvent = new byte[calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 16]; // 26 bytes for calendar and overhead
time.setTimeInMillis(calendarEventSpec.timestamp);
CalendarEvent[0] = ZeTimeConstants.CMD_PREAMBLE;
CalendarEvent[1] = ZeTimeConstants.CMD_PUSH_CALENDAR_DAY;
CalendarEvent[2] = ZeTimeConstants.CMD_SEND;
CalendarEvent[3] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) & 0xff);
CalendarEvent[4] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) >> 8);
CalendarEvent[5] = (byte)(calendarEventSpec.type + 0x1);
CalendarEvent[6] = (byte)(time.get(Calendar.YEAR) & 0xff);
CalendarEvent[7] = (byte)(time.get(Calendar.YEAR) >> 8);
CalendarEvent[8] = (byte)(time.get(Calendar.MONTH)+1);
CalendarEvent[9] = (byte)time.get(Calendar.DAY_OF_MONTH);
CalendarEvent[10] = (byte) (time.get(Calendar.HOUR_OF_DAY) & 0xff);
CalendarEvent[11] = (byte) (time.get(Calendar.HOUR_OF_DAY) >> 8);
CalendarEvent[12] = (byte) (time.get(Calendar.MINUTE) & 0xff);
CalendarEvent[13] = (byte) (time.get(Calendar.MINUTE) >> 8);
CalendarEvent[14] = (byte) calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length;
System.arraycopy(calendarEventSpec.title.getBytes(StandardCharsets.UTF_8), 0, CalendarEvent, 15, calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length);
CalendarEvent[CalendarEvent.length-1] = ZeTimeConstants.CMD_END;
if(CalendarEvent != null)
{
try {
TransactionBuilder builder = performInitialized("sendCalendarEvenr");
sendMsgToWatch(builder, CalendarEvent);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending calendar event: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("synchronizeTime");
synchronizeTime(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error setting the time: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onAppDelete(UUID uuid) {
}
@Override
public void onAppInfoReq() {
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
@Override
public void onReboot() {
}
@Override
public void onScreenshotReq() {
}
@Override
public void onSendWeather(WeatherSpec weatherSpec) {
byte[] weather = new byte[weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 26]; // 26 bytes for weatherdata and overhead
weather[0] = ZeTimeConstants.CMD_PREAMBLE;
weather[1] = ZeTimeConstants.CMD_PUSH_WEATHER_DATA;
weather[2] = ZeTimeConstants.CMD_SEND;
weather[3] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) & 0xff);
weather[4] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) >> 8);
weather[5] = 0; // celsius
weather[6] = (byte)(weatherSpec.currentTemp - 273);
weather[7] = (byte)(weatherSpec.todayMinTemp - 273);
weather[8] = (byte)(weatherSpec.todayMaxTemp - 273);
weather[9] = Weather.mapToZeTimeCondition(weatherSpec.currentConditionCode);
for(int forecast = 0; forecast < 3; forecast++) {
weather[10+(forecast*5)] = 0; // celsius
weather[11+(forecast*5)] = (byte) 0xff;
weather[12+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).minTemp - 273);
weather[13+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).maxTemp - 273);
weather[14+(forecast*5)] = Weather.mapToZeTimeCondition(weatherSpec.forecasts.get(forecast).conditionCode);
}
System.arraycopy(weatherSpec.location.getBytes(StandardCharsets.UTF_8), 0, weather, 25, weatherSpec.location.getBytes(StandardCharsets.UTF_8).length);
weather[weather.length-1] = ZeTimeConstants.CMD_END;
if(weather != null)
{
try {
TransactionBuilder builder = performInitialized("sendWeahter");
sendMsgToWatch(builder, weather);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending weather: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onAppReorder(UUID[] uuids) {
}
@Override
public void onInstallApp(Uri uri) {
}
@Override
public void onDeleteNotification(int id) {
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
int subject_length = 0;
int body_length = notificationSpec.body.getBytes(StandardCharsets.UTF_8).length;
if(body_length > 256)
{
body_length = 256;
}
int notification_length = body_length;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
// convert every single digit of the date to ascii characters
// we do it like so: use the base chrachter of '0' and add the digit
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.phoneNumber != null)
{
notification_length += notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.title != null)
{
notification_length += notificationSpec.title.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.title.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.title.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
switch(notificationSpec.type)
{
case GENERIC_SMS:
notification[5] = ZeTimeConstants.NOTIFICATION_SMS;
break;
case GENERIC_PHONE:
notification[5] = ZeTimeConstants.NOTIFICATION_MISSED_CALL;
break;
case GMAIL:
case GOOGLE_INBOX:
case MAILBOX:
case OUTLOOK:
case YAHOO_MAIL:
case GENERIC_EMAIL:
notification[5] = ZeTimeConstants.NOTIFICATION_EMAIL;
break;
case WECHAT:
notification[5] = ZeTimeConstants.NOTIFICATION_WECHAT;
break;
case VIBER:
notification[5] = ZeTimeConstants.NOTIFICATION_VIBER;
break;
case WHATSAPP:
notification[5] = ZeTimeConstants.NOTIFICATION_WHATSAPP;
break;
case FACEBOOK:
case FACEBOOK_MESSENGER:
notification[5] = ZeTimeConstants.NOTIFICATION_FACEBOOK;
break;
case GOOGLE_HANGOUTS:
notification[5] = ZeTimeConstants.NOTIFICATION_HANGOUTS;
break;
case LINE:
notification[5] = ZeTimeConstants.NOTIFICATION_LINE;
break;
case SKYPE:
notification[5] = ZeTimeConstants.NOTIFICATION_SKYPE;
break;
case CONVERSATIONS:
case RIOT:
case SIGNAL:
case TELEGRAM:
case THREEMA:
case KONTALK:
case ANTOX:
case GOOGLE_MESSENGER:
case HIPCHAT:
case KIK:
case KAKAO_TALK:
case SLACK:
notification[5] = ZeTimeConstants.NOTIFICATION_MESSENGER;
break;
case SNAPCHAT:
notification[5] = ZeTimeConstants.NOTIFICATION_SNAPCHAT;
break;
case INSTAGRAM:
notification[5] = ZeTimeConstants.NOTIFICATION_INSTAGRAM;
break;
case TWITTER:
notification[5] = ZeTimeConstants.NOTIFICATION_TWITTER;
break;
case LINKEDIN:
notification[5] = ZeTimeConstants.NOTIFICATION_LINKEDIN;
break;
case GENERIC_CALENDAR:
notification[5] = ZeTimeConstants.NOTIFICATION_CALENDAR;
break;
default:
notification[5] = ZeTimeConstants.NOTIFICATION_SOCIAL;
break;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("sendNotification");
sendMsgToWatch(builder, notification);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error sending notification: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID characteristicUUID = characteristic.getUuid();
if (ZeTimeConstants.UUID_ACK_CHARACTERISTIC.equals(characteristicUUID)) {
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1]) {
case ZeTimeConstants.CMD_WATCH_ID:
break;
case ZeTimeConstants.CMD_DEVICE_VERSION:
handleDeviceInfo(data);
break;
case ZeTimeConstants.CMD_BATTERY_POWER:
handleBatteryInfo(data);
break;
case ZeTimeConstants.CMD_SHOCK_STRENGTH:
break;
case ZeTimeConstants.CMD_AVAIABLE_DATA:
handleActivityFetching(data);
break;
case ZeTimeConstants.CMD_GET_STEP_COUNT:
handleStepsData(data);
break;
case ZeTimeConstants.CMD_GET_SLEEP_DATA:
handleSleepData(data);
break;
case ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA:
handleHeartRateData(data);
break;
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
}
return true;
} else if (ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC.equals(characteristicUUID))
{
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1])
{
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
return true;
}
}
else {
LOG.info("Unhandled characteristic changed: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
return false;
}
private boolean isMsgFormatOK(byte[] msg)
{
if(msg != null) {
if (msg[0] == ZeTimeConstants.CMD_PREAMBLE) {
if ((msg[3] != 0) || (msg[4] != 0)) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
int msgLength = payloadSize + 6;
if (msgLength == msg.length) {
if (msg[msgLength - 1] == ZeTimeConstants.CMD_END) {
return true;
}
}
}
}
}
return false;
}
private byte[] receiveCompleteMsg(byte[] msg)
{
if(msgPart == 0) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
if (payloadSize > 14) {
lastMsg = new byte[msg.length];
System.arraycopy(msg, 0, lastMsg, 0, msg.length);
msgPart++;
return null;
} else {
return msg;
}
} else
{
byte[] completeMsg = new byte[lastMsg.length + msg.length];
System.arraycopy(lastMsg, 0, completeMsg, 0, lastMsg.length);
System.arraycopy(msg, 0, completeMsg, lastMsg.length, msg.length);
msgPart = 0;
return completeMsg;
}
}
private ZeTimeDeviceSupport requestBatteryInfo(TransactionBuilder builder) {
LOG.debug("Requesting Battery Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_BATTERY_POWER,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestDeviceInfo(TransactionBuilder builder) {
LOG.debug("Requesting Device Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_WATCH_ID,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x05,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x02,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestActivityInfo(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_AVAIABLE_DATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestShockStrength(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_SHOCK_STRENGTH,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private void handleBatteryInfo(byte[] value) {
batteryCmd.level = ((short) value[5]);
if(batteryCmd.level <= 25)
{
batteryCmd.state = BatteryState.BATTERY_LOW;
} else
{
batteryCmd.state = BatteryState.BATTERY_NORMAL;
}
evaluateGBDeviceEvent(batteryCmd);
}
private void handleDeviceInfo(byte[] value) {
value[value.length-1] = 0; // convert the end to a String end
byte[] string = Arrays.copyOfRange(value,6, value.length-1);
if(value[5] == 5)
{
versionCmd.fwVersion = new String(string);
} else{
versionCmd.hwVersion = new String(string);
}
evaluateGBDeviceEvent(versionCmd);
}
private void handleActivityFetching(byte[] msg)
{
availableStepsData = (int) ((msg[5]&0xff) | (msg[6] << 8)&0xff00);
availableSleepData = (int) ((msg[7]&0xff) | (msg[8] << 8)&0xff00);
availableHeartRateData= (int) ((msg[9]&0xff) | (msg[10] << 8)&0xff00);
if(availableStepsData > 0){
getStepData();
} else if(availableHeartRateData > 0)
{
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
private void getStepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_STEP_COUNT,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getHeartRateData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getSleepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_SLEEP_DATA,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void handleStepsData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
sample.setSteps((msg[14] << 24)&0xff000000 | (msg[13] << 16)&0xff0000 | (msg[12] << 8)&0xff00 | (msg[11]&0xff));
sample.setCaloriesBurnt((msg[18] << 24)&0xff000000 | (msg[17] << 16)&0xff0000 | (msg[16] << 8)&0xff00 | (msg[15]&0xff));
sample.setDistanceMeters((msg[22] << 24)&0xff000000 | (msg[21] << 16)&0xff0000 | (msg[20] << 8)&0xff00 | (msg[19]&0xff));
sample.setActiveTimeMinutes((msg[26] << 24)&0xff000000 | (msg[25] << 16)&0xff0000 | (msg[24] << 8)&0xff00 | (msg[23]&0xff));
sample.setRawKind(ActivityKind.TYPE_ACTIVITY);
sample.setRawIntensity(sample.getSteps());
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSteps = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSteps *100 / availableStepsData), getContext());
if (progressSteps == availableStepsData) {
progressSteps = 0;
availableStepsData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableHeartRateData > 0) {
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void handleSleepData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
if(msg[11] == 0) {
sample.setRawKind(ActivityKind.TYPE_DEEP_SLEEP);
} else if(msg[11] == 1)
{
sample.setRawKind(ActivityKind.TYPE_LIGHT_SLEEP);
} else
{
sample.setRawKind(ActivityKind.TYPE_UNKNOWN);
}
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSleep = (msg[5]&0xff) | (msg[6] << 8)&0xff00;
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSleep *100 / availableSleepData), getContext());
if (progressSleep == availableSleepData) {
progressSleep = 0;
availableSleepData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
}
}
private void handleHeartRateData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setHeartRate(msg[11]);
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressHeartRate = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressHeartRate *100 / availableHeartRateData), getContext());
if (progressHeartRate == availableHeartRateData) {
progressHeartRate = 0;
availableHeartRateData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void sendMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(writeCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(writeCharacteristic, msg);
}
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
}
private void handleMusicControl(byte[] musicControlMsg)
{
if(musicControlMsg[2] == ZeTimeConstants.CMD_SEND) {
switch (musicControlMsg[5]) {
case 0: // play current song
musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
break;
case 1: // pause current song
musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
break;
case 2: // skip to previous song
musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
break;
case 3: // skip to next song
musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
break;
case 4: // change volume
if (musicControlMsg[6] > volume) {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
if(volume < 90) {
volume += 10;
}
} else {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
if(volume > 10) {
volume -= 10;
}
}
try {
TransactionBuilder builder = performInitialized("replyMusicVolume");
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music volume: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
break;
}
evaluateGBDeviceEvent(musicCmd);
} else {
if (music != null) {
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
try {
TransactionBuilder builder = performInitialized("replyMusicState");
replyMsgToWatch(builder, music);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
private void replyMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(replyCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(replyCharacteristic, msg);
}
}
private void synchronizeTime(TransactionBuilder builder)
{
Calendar now = GregorianCalendar.getInstance();
byte[] timeSync = new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DATE_TIME,
ZeTimeConstants.CMD_SEND,
0x0c,
0x00,
(byte)(now.get(Calendar.YEAR) & 0xff),
(byte)(now.get(Calendar.YEAR) >> 8),
(byte)(now.get(Calendar.MONTH) + 1),
(byte)now.get(Calendar.DAY_OF_MONTH),
(byte)now.get(Calendar.HOUR_OF_DAY),
(byte)now.get(Calendar.MINUTE),
(byte)now.get(Calendar.SECOND),
0x00, // is 24h
0x00, // SetTime after calibration
0x01, // Unit
(byte)((now.get(Calendar.ZONE_OFFSET)/3600000) + (now.get(Calendar.DST_OFFSET)/3600000)), // TimeZone hour + daylight saving
0x00, // TimeZone minute
ZeTimeConstants.CMD_END};
sendMsgToWatch(builder, timeSync);
}
}
|
Fix timestamps of activities, cause the watch reports them with 6 hours offset.
|
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/zetime/ZeTimeDeviceSupport.java
|
Fix timestamps of activities, cause the watch reports them with 6 hours offset.
|
|
Java
|
agpl-3.0
|
201c00d2d86c04e876aa3a1d0e5b381daff0bcae
| 0
|
roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,rdkgit/opennms
|
/*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2008 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications;
* Created 10/16/2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.netmgt.provision.support;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import org.opennms.netmgt.provision.DetectorMonitor;
import org.opennms.netmgt.provision.SyncServiceDetector;
import org.opennms.netmgt.provision.support.ClientConversation.RequestBuilder;
import org.opennms.netmgt.provision.support.ClientConversation.ResponseValidator;
/**
*
* @author <a href=mailto:desloge@opennms.com>Donald Desloge</a>
*
*/
public abstract class BasicDetector<Request, Response> extends AbstractDetector implements SyncServiceDetector {
private ClientConversation<Request, Response> m_conversation = new ClientConversation<Request, Response>();
protected BasicDetector(int defaultPort, int defaultTimeout, int defaultRetries) {
super(defaultPort, defaultTimeout, defaultRetries);
}
abstract protected void onInit();
public boolean isServiceDetected(InetAddress address, DetectorMonitor detectorMonitor) {
String ipAddr = address.getHostAddress();
int port = getPort();
int retries = getRetries();
int timeout = getTimeout();
System.out.printf("Address: %s || port: %s || \n", address, getPort());
detectorMonitor.start(this, "Checking address: %s for %s capability", address, getServiceName());
Client<Request, Response> client = getClient();
for (int attempts = 0; attempts <= retries; attempts++) {
try {
client.connect(address, port, timeout);
detectorMonitor.attempt(this, attempts, "Attempting to connect to address: %s port %d attempt #%s",ipAddr,port,attempts);
if (attemptConversation(client)) {
return true;
}
} catch (ConnectException cE) {
// Connection refused!! Continue to retry.
System.out.println("put before");
cE.printStackTrace();
detectorMonitor.info(this, cE, "%s: Excpetion attempting to connect to address: %s port %d, attempt #%s",getServiceName(), ipAddr,port, attempts);
} catch (NoRouteToHostException e) {
// No Route to host!!!
e.printStackTrace();
detectorMonitor.info(this, e, "%s: No route to address %s was available", getServiceName(), ipAddr);
throw new UndeclaredThrowableException(e);
} catch (InterruptedIOException e) {
// Expected exception
e.printStackTrace();
detectorMonitor.info(this, e, "%s: Did not connect to to address %s port %d within timeout: %d attempt: %d", getServiceName(), ipAddr, port, timeout, attempts);
} catch (IOException e) {
e.printStackTrace();
detectorMonitor.info(this, e, "%s: An unexpected I/O exception occured contacting address %s port %d",getServiceName(), ipAddr, port);
} catch (Throwable t) {
t.printStackTrace();
detectorMonitor.failure(this, "%s: Failed to detect %s on address %s port %d", getServiceName(), getServiceName(), ipAddr, port);
detectorMonitor.error(this, t, "%s: An undeclared throwable exception was caught contating address %s port %d", getServiceName(), ipAddr, port);
} finally {
client.close();
}
}
return false;
}
/**
* @return
*/
abstract protected Client<Request, Response> getClient();
private boolean attemptConversation(Client<Request, Response> client) throws IOException, Exception {
return getConversation().attemptConversation(client);
}
protected void expectBanner(ResponseValidator<Response> bannerValidator) {
getConversation().expectBanner(bannerValidator);
}
protected void send(RequestBuilder<Request> requestBuilder, ResponseValidator<Response> responseValidator) {
getConversation().addExchange(requestBuilder, responseValidator);
}
protected void send(Request request, ResponseValidator<Response> responseValidator) {
getConversation().addExchange(request, responseValidator);
}
protected ClientConversation<Request, Response> getConversation() {
return m_conversation;
}
}
|
opennms-provision/opennms-provision-api/src/main/java/org/opennms/netmgt/provision/support/BasicDetector.java
|
/*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2008 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications;
* Created 10/16/2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.netmgt.provision.support;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import org.opennms.netmgt.provision.DetectorMonitor;
import org.opennms.netmgt.provision.SyncServiceDetector;
import org.opennms.netmgt.provision.support.Client;
import org.opennms.netmgt.provision.support.ClientConversation.RequestBuilder;
import org.opennms.netmgt.provision.support.ClientConversation.ResponseValidator;
/**
*
* @author <a href=mailto:desloge@opennms.com>Donald Desloge</a>
*
*/
public abstract class BasicDetector<Request, Response> extends AbstractDetector implements SyncServiceDetector {
private ClientConversation<Request, Response> m_conversation = new ClientConversation<Request, Response>();
protected BasicDetector(int defaultPort, int defaultTimeout, int defaultRetries) {
super(defaultPort, defaultTimeout, defaultRetries);
}
abstract protected void onInit();
public boolean isServiceDetected(InetAddress address, DetectorMonitor detectorMonitor) {
int port = getPort();
int retries = getRetries();
int timeout = getTimeout();
System.out.printf("Address: %s || port: %s || \n", address, getPort());
detectorMonitor.start(this, "Checking address: %s for %s capability", address, getServiceName());
Client<Request, Response> client = getClient();
for (int attempts = 0; attempts <= retries; attempts++) {
try {
client.connect(address, port, timeout);
detectorMonitor.attempt(this, attempts, "Attempting to connect to address: %s attempt #%s",address.getHostAddress(),attempts);
if (attemptConversation(client)) {
return true;
}
} catch (ConnectException cE) {
// Connection refused!! Continue to retry.
System.out.println("put before");
cE.printStackTrace();
detectorMonitor.info(this, cE, "Attempting to connect to address: %s attempt #%s",address.getHostAddress(),attempts);
} catch (NoRouteToHostException e) {
// No Route to host!!!
e.printStackTrace();
detectorMonitor.info(this, e, "%s: No route to address %s was available", getServiceName(), address.getHostAddress());
throw new UndeclaredThrowableException(e);
} catch (InterruptedIOException e) {
// Expected exception
e.printStackTrace();
detectorMonitor.info(this, e, "%s: Did not connect to to address within timeout: %d attempt: %d", getServiceName(), timeout, attempts);
} catch (IOException e) {
e.printStackTrace();
detectorMonitor.info(this, e, "%s: An unexpected I/O exception occured contacting address %s",getServiceName(), address.getHostAddress());
} catch (Throwable t) {
t.printStackTrace();
detectorMonitor.failure(this, "%s: Failed to detect %s on address %s", getServiceName(), getServiceName(), address.getHostAddress());
detectorMonitor.error(this, t, "%s: An undeclared throwable exception was caught contating address %s", getServiceName(), address.getHostAddress());
} finally {
client.close();
}
}
return false;
}
/**
* @return
*/
abstract protected Client<Request, Response> getClient();
private boolean attemptConversation(Client<Request, Response> client) throws IOException, Exception {
return getConversation().attemptConversation(client);
}
protected void expectBanner(ResponseValidator<Response> bannerValidator) {
getConversation().expectBanner(bannerValidator);
}
protected void send(RequestBuilder<Request> requestBuilder, ResponseValidator<Response> responseValidator) {
getConversation().addExchange(requestBuilder, responseValidator);
}
protected void send(Request request, ResponseValidator<Response> responseValidator) {
getConversation().addExchange(request, responseValidator);
}
protected ClientConversation<Request, Response> getConversation() {
return m_conversation;
}
}
|
clean up log message
|
opennms-provision/opennms-provision-api/src/main/java/org/opennms/netmgt/provision/support/BasicDetector.java
|
clean up log message
|
|
Java
|
lgpl-2.1
|
3e3125a2bb2134baa4df22def93ad6710054c1d6
| 0
|
CreativeMD/LittleTiles
|
package com.creativemd.littletiles.common.events;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.creativemd.creativecore.common.utils.math.box.OrientatedBoundingBox;
import com.creativemd.littletiles.client.render.entity.RenderAnimation;
import com.creativemd.littletiles.common.entity.EntityAnimation;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ClassInheritanceMultiMap;
import net.minecraft.util.ReportedException;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.event.world.GetCollisionBoxesEvent;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class LittleDoorHandler {
public static LittleDoorHandler client;
public static LittleDoorHandler server;
public static LittleDoorHandler getHandler(World world) {
if (world.isRemote)
return client;
return server;
}
public final Side side;
public LittleDoorHandler(Side side) {
this.side = side;
}
public List<EntityAnimation> openDoors = new ArrayList<>();
public List<EntityAnimation> findDoors(World world, AxisAlignedBB bb) {
if (openDoors.isEmpty())
return Collections.emptyList();
List<EntityAnimation> doors = new ArrayList<>();
for (EntityAnimation door : openDoors) {
if (door.world == world && door.getEntityBoundingBox().intersects(bb))
doors.add(door);
}
return doors;
}
public void createDoor(EntityAnimation door) {
openDoors.add(door);
}
@SubscribeEvent
public void tick(WorldTickEvent event) {
if (event.side == side && event.phase == Phase.END) {
for (Iterator iterator = openDoors.iterator(); iterator.hasNext();) {
EntityAnimation door = (EntityAnimation) iterator.next();
door.onUpdateForReal();
if (door.isDead)
iterator.remove();
}
}
}
@SideOnly(Side.CLIENT)
public Render render;
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void renderTick(RenderWorldLastEvent event) {
if (side.isClient()) {
if (render == null)
render = new RenderAnimation(Minecraft.getMinecraft().getRenderManager());
float partialTicks = event.getPartialTicks();
Entity renderViewEntity = Minecraft.getMinecraft().getRenderViewEntity();
if (renderViewEntity == null || openDoors.isEmpty())
return;
double camX = renderViewEntity.prevPosX + (renderViewEntity.posX - renderViewEntity.prevPosX) * (double) partialTicks;
double camY = renderViewEntity.prevPosY + (renderViewEntity.posY - renderViewEntity.prevPosY) * (double) partialTicks;
double camZ = renderViewEntity.prevPosZ + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * (double) partialTicks;
ICamera camera = new Frustum();
camera.setPosition(camX, camY, camZ);
for (EntityAnimation door : openDoors) {
if (!render.shouldRender(door, camera, camX, camY, camZ) || door.isDead)
continue;
if (door.ticksExisted == 0) {
door.lastTickPosX = door.posX;
door.lastTickPosY = door.posY;
door.lastTickPosZ = door.posZ;
}
double d0 = door.lastTickPosX + (door.posX - door.lastTickPosX) * (double) partialTicks;
double d1 = door.lastTickPosY + (door.posY - door.lastTickPosY) * (double) partialTicks;
double d2 = door.lastTickPosZ + (door.posZ - door.lastTickPosZ) * (double) partialTicks;
float f = door.prevRotationYaw + (door.rotationYaw - door.prevRotationYaw) * partialTicks;
int i = door.getBrightnessForRender();
if (door.isBurning()) {
i = 15728880;
}
int j = i % 65536;
int k = i / 65536;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j, (float) k);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
try {
// render.setRenderOutlines(render.getRenderManager().renderOutlines);
render.doRender(door, d0 - TileEntityRendererDispatcher.staticPlayerX, d1 - TileEntityRendererDispatcher.staticPlayerY, d2 - TileEntityRendererDispatcher.staticPlayerZ, f, partialTicks);
} catch (Throwable throwable1) {
throw new ReportedException(CrashReport.makeCrashReport(throwable1, "Rendering entity in world"));
}
}
}
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void tickClient(ClientTickEvent event) {
if (event.side == side && event.phase == Phase.END) {
for (Iterator iterator = openDoors.iterator(); iterator.hasNext();) {
EntityAnimation door = (EntityAnimation) iterator.next();
if (door.isDead)
iterator.remove();
door.onUpdateForReal();
}
}
}
@SubscribeEvent
public void chunkUnload(ChunkEvent.Unload event) {
for (ClassInheritanceMultiMap<Entity> map : event.getChunk().getEntityLists()) {
for (Entity entity : map) {
if (entity instanceof EntityAnimation && ((EntityAnimation) entity).addedDoor) {
((EntityAnimation) entity).addedDoor = false;
openDoors.remove(entity);
}
}
}
}
@SubscribeEvent
public void worldUnload(WorldEvent.Unload event) {
for (Iterator iterator = openDoors.iterator(); iterator.hasNext();) {
EntityAnimation animation = (EntityAnimation) iterator.next();
if (animation.world == event.getWorld()) {
animation.addedDoor = false;
iterator.remove();
}
}
}
@SubscribeEvent
public void worldCollision(GetCollisionBoxesEvent event) {
if (event.getWorld().isRemote != side.isClient())
return;
AxisAlignedBB box = event.getAabb();
for (EntityAnimation animation : findDoors(event.getWorld(), box)) {
if (animation.noCollision)
continue;
OrientatedBoundingBox newAlignedBox = animation.origin.getOrientatedBox(box);
for (OrientatedBoundingBox bb : animation.worldCollisionBoxes) {
if (bb.intersects(newAlignedBox))
event.getCollisionBoxesList().add(bb);
}
}
}
private static Field wasPushedByDoor = ReflectionHelper.findField(EntityPlayerMP.class, "wasPushedByDoor");
public static void setPushedByDoor(EntityPlayerMP player) {
try {
wasPushedByDoor.setInt(player, 10);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static boolean checkIfEmpty(List<AxisAlignedBB> boxes, EntityPlayerMP player) {
try {
if (wasPushedByDoor.getInt(player) > 0)
return true;
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return boxes.isEmpty();
}
}
|
src/main/java/com/creativemd/littletiles/common/events/LittleDoorHandler.java
|
package com.creativemd.littletiles.common.events;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.creativemd.creativecore.common.utils.math.box.OrientatedBoundingBox;
import com.creativemd.littletiles.client.render.entity.RenderAnimation;
import com.creativemd.littletiles.common.entity.EntityAnimation;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ClassInheritanceMultiMap;
import net.minecraft.util.ReportedException;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.event.world.GetCollisionBoxesEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class LittleDoorHandler {
public static LittleDoorHandler client;
public static LittleDoorHandler server;
public static LittleDoorHandler getHandler(World world) {
if (world.isRemote)
return client;
return server;
}
public final Side side;
public LittleDoorHandler(Side side) {
this.side = side;
}
public List<EntityAnimation> openDoors = new ArrayList<>();
public List<EntityAnimation> findDoors(World world, AxisAlignedBB bb) {
if (openDoors.isEmpty())
return Collections.emptyList();
List<EntityAnimation> doors = new ArrayList<>();
for (EntityAnimation door : openDoors) {
if (door.world == world && door.getEntityBoundingBox().intersects(bb))
doors.add(door);
}
return doors;
}
public void createDoor(EntityAnimation door) {
openDoors.add(door);
}
@SubscribeEvent
public void tick(WorldTickEvent event) {
if (event.side == side && event.phase == Phase.END) {
for (Iterator iterator = openDoors.iterator(); iterator.hasNext();) {
EntityAnimation door = (EntityAnimation) iterator.next();
door.onUpdateForReal();
if (door.isDead)
iterator.remove();
}
}
}
@SideOnly(Side.CLIENT)
public Render render;
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void renderTick(RenderWorldLastEvent event) {
if (side.isClient()) {
if (render == null)
render = new RenderAnimation(Minecraft.getMinecraft().getRenderManager());
float partialTicks = event.getPartialTicks();
Entity renderViewEntity = Minecraft.getMinecraft().getRenderViewEntity();
if (renderViewEntity == null || openDoors.isEmpty())
return;
double camX = renderViewEntity.prevPosX + (renderViewEntity.posX - renderViewEntity.prevPosX) * (double) partialTicks;
double camY = renderViewEntity.prevPosY + (renderViewEntity.posY - renderViewEntity.prevPosY) * (double) partialTicks;
double camZ = renderViewEntity.prevPosZ + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * (double) partialTicks;
ICamera camera = new Frustum();
camera.setPosition(camX, camY, camZ);
for (EntityAnimation door : openDoors) {
if (!render.shouldRender(door, camera, camX, camY, camZ) || door.isDead)
continue;
if (door.ticksExisted == 0) {
door.lastTickPosX = door.posX;
door.lastTickPosY = door.posY;
door.lastTickPosZ = door.posZ;
}
double d0 = door.lastTickPosX + (door.posX - door.lastTickPosX) * (double) partialTicks;
double d1 = door.lastTickPosY + (door.posY - door.lastTickPosY) * (double) partialTicks;
double d2 = door.lastTickPosZ + (door.posZ - door.lastTickPosZ) * (double) partialTicks;
float f = door.prevRotationYaw + (door.rotationYaw - door.prevRotationYaw) * partialTicks;
int i = door.getBrightnessForRender();
if (door.isBurning()) {
i = 15728880;
}
int j = i % 65536;
int k = i / 65536;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j, (float) k);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
try {
// render.setRenderOutlines(render.getRenderManager().renderOutlines);
render.doRender(door, d0 - TileEntityRendererDispatcher.staticPlayerX, d1 - TileEntityRendererDispatcher.staticPlayerY, d2 - TileEntityRendererDispatcher.staticPlayerZ, f, partialTicks);
} catch (Throwable throwable1) {
throw new ReportedException(CrashReport.makeCrashReport(throwable1, "Rendering entity in world"));
}
}
}
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void tickClient(ClientTickEvent event) {
if (event.side == side && event.phase == Phase.END) {
for (Iterator iterator = openDoors.iterator(); iterator.hasNext();) {
EntityAnimation door = (EntityAnimation) iterator.next();
if (door.isDead)
iterator.remove();
door.onUpdateForReal();
}
}
}
@SubscribeEvent
public void chunkUnload(ChunkEvent.Unload event) {
for (ClassInheritanceMultiMap<Entity> map : event.getChunk().getEntityLists()) {
for (Entity entity : map) {
if (entity instanceof EntityAnimation && ((EntityAnimation) entity).addedDoor) {
((EntityAnimation) entity).addedDoor = false;
openDoors.remove(entity);
}
}
}
}
@SubscribeEvent
public void worldCollision(GetCollisionBoxesEvent event) {
if (event.getWorld().isRemote != side.isClient())
return;
AxisAlignedBB box = event.getAabb();
for (EntityAnimation animation : findDoors(event.getWorld(), box)) {
if (animation.noCollision)
continue;
OrientatedBoundingBox newAlignedBox = animation.origin.getOrientatedBox(box);
for (OrientatedBoundingBox bb : animation.worldCollisionBoxes) {
if (bb.intersects(newAlignedBox))
event.getCollisionBoxesList().add(bb);
}
}
}
private static Field wasPushedByDoor = ReflectionHelper.findField(EntityPlayerMP.class, "wasPushedByDoor");
public static void setPushedByDoor(EntityPlayerMP player) {
try {
wasPushedByDoor.setInt(player, 10);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static boolean checkIfEmpty(List<AxisAlignedBB> boxes, EntityPlayerMP player) {
try {
if (wasPushedByDoor.getInt(player) > 0)
return true;
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return boxes.isEmpty();
}
}
|
Fixed not despawning animations when unloading world
|
src/main/java/com/creativemd/littletiles/common/events/LittleDoorHandler.java
|
Fixed not despawning animations when unloading world
|
|
Java
|
apache-2.0
|
2758a23502fbec3cfff75fb670126eab2a97d0b6
| 0
|
vibur/vibur-dbcp-hibernate4.012
|
/**
* Copyright 2013 Simeon Malchev
*
* 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.vibur.dbcp.integration;
import org.hibernate.Session;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hsqldb.cmdline.SqlToolError;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.runners.MockitoJUnitRunner;
import org.vibur.dbcp.ViburDBCPDataSource;
import org.vibur.dbcp.cache.ConnMethodKey;
import org.vibur.dbcp.cache.StatementVal;
import org.vibur.dbcp.model.Actor;
import org.vibur.dbcp.util.HibernateTestUtils;
import org.vibur.dbcp.util.HsqldbUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.vibur.dbcp.cache.StatementVal.AVAILABLE;
/**
* Hibernate unit/integration test.
*
* @author Simeon Malchev
*/
@RunWith(MockitoJUnitRunner.class)
public class ViburDBCPConnectionProviderTest {
@BeforeClass
public static void deployDatabaseSchemaAndData() throws IOException, SqlToolError, SQLException {
Properties properties = ((SessionFactoryImplementor)
HibernateTestUtils.getSessionFactoryWithStmtCache()).getProperties();
HsqldbUtils.deployDatabaseSchemaAndData(properties.getProperty("hibernate.connection.url"),
properties.getProperty("hibernate.connection.username"),
properties.getProperty("hibernate.connection.password"));
}
@Captor
private ArgumentCaptor<ConnMethodKey> key1, key2;
@Captor
private ArgumentCaptor<StatementVal> val1;
@Test
public void testSelectStatementNoStatementsCache() throws SQLException {
Session session = HibernateTestUtils.getSessionFactoryWithoutStmtCache().getCurrentSession();
try {
executeAndVerifySelect(session);
} catch (RuntimeException e) {
session.getTransaction().rollback();
throw e;
}
}
@Test
@SuppressWarnings("unchecked")
public void testSelectStatementWithStatementsCache() throws SQLException {
Session session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession();
ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()).getConnectionProvider();
ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource();
ConcurrentMap<ConnMethodKey, StatementVal> mockedStatementCache =
mock(ConcurrentMap.class, delegatesTo(ds.getStatementCache()));
ds.setStatementCache(mockedStatementCache);
executeAndVerifySelectInSession(session);
// resources/hibernate-with-stmt-cache.cfg.xml defines pool with 1 connection only, that's why
// the second session will get and use the same underlying connection.
session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession();
executeAndVerifySelectInSession(session);
InOrder inOrder = inOrder(mockedStatementCache);
inOrder.verify(mockedStatementCache).get(key1.capture());
inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture());
inOrder.verify(mockedStatementCache).get(key2.capture());
assertEquals(1, mockedStatementCache.size());
assertTrue(mockedStatementCache.containsKey(key1.getValue()));
assertEquals(key1.getValue(), key2.getValue());
assertEquals("prepareStatement", key1.getValue().getMethod().getName());
assertEquals(AVAILABLE, val1.getValue().state().get());
}
private void executeAndVerifySelectInSession(Session session) {
try {
executeAndVerifySelect(session);
} catch (RuntimeException e) {
session.getTransaction().rollback();
throw e;
} finally {
session.close();
}
}
@SuppressWarnings("unchecked")
private void executeAndVerifySelect(Session session) {
session.beginTransaction();
List<Actor> list = session.createQuery("from Actor where firstName = ?")
.setParameter(0, "CHRISTIAN").list();
session.getTransaction().commit();
Set<String> expectedLastNames = new HashSet<String>(Arrays.asList("GABLE", "AKROYD", "NEESON"));
assertEquals(expectedLastNames.size(), list.size());
for (Actor actor : list) {
assertTrue(expectedLastNames.remove(actor.getLastName()));
}
}
}
|
src/test/java/org/vibur/dbcp/integration/ViburDBCPConnectionProviderTest.java
|
/**
* Copyright 2013 Simeon Malchev
*
* 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.vibur.dbcp.integration;
import org.hibernate.Session;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hsqldb.cmdline.SqlToolError;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.runners.MockitoJUnitRunner;
import org.vibur.dbcp.ViburDBCPDataSource;
import org.vibur.dbcp.cache.ConnMethodKey;
import org.vibur.dbcp.cache.ReturnVal;
import org.vibur.dbcp.model.Actor;
import org.vibur.dbcp.util.HibernateTestUtils;
import org.vibur.dbcp.util.HsqldbUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.vibur.dbcp.cache.ReturnVal.AVAILABLE;
/**
* Hibernate unit/integration test.
*
* @author Simeon Malchev
*/
@RunWith(MockitoJUnitRunner.class)
public class ViburDBCPConnectionProviderTest {
@BeforeClass
public static void deployDatabaseSchemaAndData() throws IOException, SqlToolError, SQLException {
Properties properties = ((SessionFactoryImplementor)
HibernateTestUtils.getSessionFactoryWithStmtCache()).getProperties();
HsqldbUtils.deployDatabaseSchemaAndData(properties.getProperty("hibernate.connection.url"),
properties.getProperty("hibernate.connection.username"),
properties.getProperty("hibernate.connection.password"));
}
@Captor
private ArgumentCaptor<ConnMethodKey> key1, key2;
@Captor
private ArgumentCaptor<ReturnVal<Statement>> val1;
@Test
public void testSelectStatementNoStatementsCache() throws SQLException {
Session session = HibernateTestUtils.getSessionFactoryWithoutStmtCache().getCurrentSession();
try {
executeAndVerifySelect(session);
} catch (RuntimeException e) {
session.getTransaction().rollback();
throw e;
}
}
@Test
@SuppressWarnings("unchecked")
public void testSelectStatementWithStatementsCache() throws SQLException {
Session session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession();
ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()).getConnectionProvider();
ViburDBCPDataSource ds = ((ViburDBCPConnectionProvider) cp).getDataSource();
ConcurrentMap<ConnMethodKey, ReturnVal<Statement>> mockedStatementCache =
mock(ConcurrentMap.class, delegatesTo(ds.getStatementCache()));
ds.setStatementCache(mockedStatementCache);
executeAndVerifySelectInSession(session);
// resources/hibernate-with-stmt-cache.cfg.xml defines pool with 1 connection only, that's why
// the second session will get and use the same underlying connection.
session = HibernateTestUtils.getSessionFactoryWithStmtCache().openSession();
executeAndVerifySelectInSession(session);
InOrder inOrder = inOrder(mockedStatementCache);
inOrder.verify(mockedStatementCache).get(key1.capture());
inOrder.verify(mockedStatementCache).putIfAbsent(same(key1.getValue()), val1.capture());
inOrder.verify(mockedStatementCache).get(key2.capture());
assertEquals(1, mockedStatementCache.size());
assertTrue(mockedStatementCache.containsKey(key1.getValue()));
assertEquals(key1.getValue(), key2.getValue());
assertEquals("prepareStatement", key1.getValue().getMethod().getName());
assertEquals(AVAILABLE, val1.getValue().state().get());
}
private void executeAndVerifySelectInSession(Session session) {
try {
executeAndVerifySelect(session);
} catch (RuntimeException e) {
session.getTransaction().rollback();
throw e;
} finally {
session.close();
}
}
@SuppressWarnings("unchecked")
private void executeAndVerifySelect(Session session) {
session.beginTransaction();
List<Actor> list = session.createQuery("from Actor where firstName = ?")
.setParameter(0, "CHRISTIAN").list();
session.getTransaction().commit();
Set<String> expectedLastNames = new HashSet<String>(Arrays.asList("GABLE", "AKROYD", "NEESON"));
assertEquals(expectedLastNames.size(), list.size());
for (Actor actor : list) {
assertTrue(expectedLastNames.remove(actor.getLastName()));
}
}
}
|
ReturnVal -> StatementVal + related refactoring
|
src/test/java/org/vibur/dbcp/integration/ViburDBCPConnectionProviderTest.java
|
ReturnVal -> StatementVal + related refactoring
|
|
Java
|
apache-2.0
|
5e5e3a5b045ebfb2be235a6b2e035bafa5752ad1
| 0
|
klopfdreh/wicket,zwsong/wicket,aldaris/wicket,klopfdreh/wicket,freiheit-com/wicket,mafulafunk/wicket,zwsong/wicket,mosoft521/wicket,selckin/wicket,mafulafunk/wicket,apache/wicket,topicusonderwijs/wicket,bitstorm/wicket,klopfdreh/wicket,AlienQueen/wicket,selckin/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,martin-g/wicket-osgi,apache/wicket,mosoft521/wicket,zwsong/wicket,mosoft521/wicket,astrapi69/wicket,freiheit-com/wicket,apache/wicket,zwsong/wicket,astrapi69/wicket,mosoft521/wicket,aldaris/wicket,klopfdreh/wicket,martin-g/wicket-osgi,klopfdreh/wicket,apache/wicket,bitstorm/wicket,dashorst/wicket,bitstorm/wicket,AlienQueen/wicket,AlienQueen/wicket,topicusonderwijs/wicket,AlienQueen/wicket,freiheit-com/wicket,astrapi69/wicket,aldaris/wicket,dashorst/wicket,selckin/wicket,dashorst/wicket,bitstorm/wicket,topicusonderwijs/wicket,AlienQueen/wicket,mafulafunk/wicket,dashorst/wicket,mosoft521/wicket,aldaris/wicket,freiheit-com/wicket,apache/wicket,selckin/wicket,bitstorm/wicket,aldaris/wicket,astrapi69/wicket,martin-g/wicket-osgi,freiheit-com/wicket,selckin/wicket,dashorst/wicket
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.AuthorizationException;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.authorization.UnauthorizedActionException;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.event.IEventSink;
import org.apache.wicket.event.IEventSource;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.IMarkupFragment;
import org.apache.wicket.markup.MarkupElement;
import org.apache.wicket.markup.MarkupException;
import org.apache.wicket.markup.MarkupNotFoundException;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.WicketTag;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.model.IComponentAssignedModel;
import org.apache.wicket.model.IComponentInheritedModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.IModelComparator;
import org.apache.wicket.model.IWrapModel;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.component.IRequestableComponent;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.handler.BookmarkableListenerInterfaceRequestHandler;
import org.apache.wicket.request.handler.ListenerInterfaceRequestHandler;
import org.apache.wicket.request.handler.PageAndComponentProvider;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.settings.IDebugSettings;
import org.apache.wicket.util.IHierarchical;
import org.apache.wicket.util.convert.IConverter;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Classes;
import org.apache.wicket.util.lang.WicketObjects;
import org.apache.wicket.util.string.ComponentStrings;
import org.apache.wicket.util.string.PrependingStringBuffer;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.apache.wicket.util.visit.Visit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Component serves as the highest level abstract base class for all components.
*
* <ul>
* <li><b>Identity </b>- All Components must have a non-null id which is retrieved by calling
* getId(). The id must be unique within the MarkupContainer that holds the Component, but does not
* have to be globally unique or unique within a Page's component hierarchy.
*
* <li><b>Hierarchy </b>- A component has a parent which can be retrieved with {@link #getParent()}.
* If a component is an instance of MarkupContainer, it may have children. In this way it has a
* place in the hierarchy of components contained on a given page.
*
* <li><b>Component Paths </b>- The path from the Page at the root of the component hierarchy to a
* given Component is simply the concatenation with dot separators of each id along the way. For
* example, the path "a.b.c" would refer to the component named "c" inside the MarkupContainer named
* "b" inside the container named "a". The path to a component can be retrieved by calling
* getPath(). This path is an absolute path beginning with the id of the Page at the root. Pages
* bear a PageMap/Session-relative identifier as their id, so each absolute path will begin with a
* number, such as "0.a.b.c". To get a Component path relative to the page that contains it, you can
* call getPageRelativePath().
*
* <li><b>LifeCycle </b>- Components participate in the following lifecycle phases:
* <ul>
* <li><b>Construction </b>- A Component is constructed with the Java language new operator.
* Children may be added during construction if the Component is a MarkupContainer.
*
* <li><b>Request Handling </b>- An incoming request is processed by a protocol request handler such
* as WicketServlet. An associated Application object creates Session, Request and Response objects
* for use by a given Component in updating its model and rendering a response. These objects are
* stored inside a container called {@link RequestCycle} which is accessible via
* {@link Component#getRequestCycle()}. The convenience methods {@link Component#getRequest()},
* {@link Component#getResponse()} and {@link Component#getSession()} provide easy access to the
* contents of this container.
*
* <li><b>Listener Invocation </b>- If the request references a listener on an existing Component,
* that listener is called, allowing arbitrary user code to handle events such as link clicks or
* form submits. Although arbitrary listeners are supported in Wicket, the need to implement a new
* class of listener is unlikely for a web application and even the need to implement a listener
* interface directly is highly discouraged. Instead, calls to listeners are routed through logic
* specific to the event, resulting in calls to user code through other overridable methods. For
* example, the {@link org.apache.wicket.markup.html.form.IFormSubmitListener#onFormSubmitted()}
* method implemented by the Form class is really a private implementation detail of the Form class
* that is not designed to be overridden (although unfortunately, it must be public since all
* interface methods in Java must be public). Instead, Form subclasses should override user-oriented
* methods such as onValidate(), onSubmit() and onError() (although only the latter two are likely
* to be overridden in practice).
*
* <li><b>Form Submit </b>- If a Form has been submitted and the Component is a FormComponent, the
* component's model is validated by a call to FormComponent.validate().
*
* <li><b>Form Model Update </b>- If a valid Form has been submitted and the Component is a
* FormComponent, the component's model is updated by a call to FormComponent.updateModel().
*
* <li><b>Rendering </b>- A markup response is generated by the Component via
* {@link Component#render()}, which calls subclass implementation code contained in
* {@link org.apache.wicket.Component#onRender()}. Once this phase begins, a Component becomes
* immutable. Attempts to alter the Component will result in a WicketRuntimeException.
*
* </ul>
*
* <li><b>Component Models </b>- The primary responsibility of a component is to use its model (an
* object that implements IModel), which can be set via
* {@link Component#setDefaultModel(IModel model)} and retrieved via
* {@link Component#getDefaultModel()}, to render a response in an appropriate markup language, such
* as HTML. In addition, form components know how to update their models based on request
* information. Since the IModel interface is a wrapper around an actual model object, a convenience
* method {@link Component#getDefaultModelObject()} is provided to retrieve the model Object from
* its IModel wrapper. A further convenience method,
* {@link Component#getDefaultModelObjectAsString()} , is provided for the very common operation of
* converting the wrapped model Object to a String.
*
* <li><b>Visibility </b>- Components which have setVisible(false) will return false from
* isVisible() and will not render a response (nor will their children).
*
* <li><b>Page </b>- The Page containing any given Component can be retrieved by calling
* {@link Component#getPage()}. If the Component is not attached to a Page, an IllegalStateException
* will be thrown. An equivalent method, {@link Component#findPage()} is available for special
* circumstances where it might be desirable to get a null reference back instead.
*
* <li><b>Session </b>- The Page for a Component points back to the Session that contains the Page.
* The Session for a component can be accessed with the convenience method getSession(), which
* simply calls getPage().getSession().
*
* <li><b>Locale </b>- The Locale for a Component is available through the convenience method
* getLocale(), which is equivalent to getSession().getLocale().
*
* <li><b>String Resources </b>- Components can have associated String resources via the
* Application's Localizer, which is available through the method {@link Component#getLocalizer()}.
* The convenience methods {@link Component#getString(String key)} and
* {@link Component#getString(String key, IModel model)} wrap the identical methods on the
* Application Localizer for easy access in Components.
*
* <li><b>Style </b>- The style ("skin") for a component is available through
* {@link org.apache.wicket.Component#getStyle()}, which is equivalent to getSession().getStyle().
* Styles are intended to give a particular look to a Component or Resource that is independent of
* its Locale. For example, a style might be a set of resources, including images and markup files,
* which gives the design look of "ocean" to the user. If the Session's style is set to "ocean" and
* these resources are given names suffixed with "_ocean", Wicket's resource management logic will
* prefer these resources to other resources, such as default resources, which are not as good of a
* match.
*
* <li><b>Variation </b>- Whereas Styles are Session (user) specific, variations are component
* specific. E.g. if the Style is "ocean" and the Variation is "NorthSea", than the resources are
* given the names suffixed with "_ocean_NorthSea".
*
* <li><b>AttributeModifiers </b>- You can add one or more {@link AttributeModifier}s to any
* component if you need to programmatically manipulate attributes of the markup tag to which a
* Component is attached.
*
* <li><b>Application, ApplicationSettings and ApplicationPages </b>- The getApplication() method
* provides convenient access to the Application for a Component via getSession().getApplication().
* The getApplicationSettings() method is equivalent to getApplication().getSettings(). The
* getApplicationPages is equivalent to getApplication().getPages().
*
* <li><b>Feedback Messages </b>- The {@link Component#debug(String)},
* {@link Component#info(String)}, {@link Component#warn(String)},
* {@link Component#error(java.io.Serializable)} and {@link Component#fatal(String)} methods
* associate feedback messages with a Component. It is generally not necessary to use these methods
* directly since Wicket validators automatically register feedback messages on Components. Any
* feedback message for a given Component can be retrieved with {@link Component#getFeedbackMessage}.
*
* <li><b>Versioning </b>- Pages are the unit of versioning in Wicket, but fine-grained control of
* which Components should participate in versioning is possible via the
* {@link Component#setVersioned(boolean)} method. The versioning participation of a given Component
* can be retrieved with {@link Component#isVersioned()}.
*
* <li><b>AJAX support</b>- Components can be re-rendered after the whole Page has been rendered at
* least once by calling doRender().
*
* @author Jonathan Locke
* @author Chris Turner
* @author Eelco Hillenius
* @author Johan Compagner
* @author Juergen Donnerstag
* @author Igor Vaynberg (ivaynberg)
*/
public abstract class Component
implements
IClusterable,
IConverterLocator,
IRequestableComponent,
IHeaderContributor,
IHierarchical<Component>,
IEventSink,
IEventSource
{
/** Log. */
private static final Logger log = LoggerFactory.getLogger(Component.class);
private static final long serialVersionUID = 1L;
/**
* Action used with IAuthorizationStrategy to determine whether a component is allowed to be
* enabled.
* <p>
* If enabling is authorized, a component may decide by itself (typically using it's enabled
* property) whether it is enabled or not. If enabling is not authorized, the given component is
* marked disabled, regardless its enabled property.
* <p>
* When a component is not allowed to be enabled (in effect disabled through the implementation
* of this interface), Wicket will try to prevent model updates too. This is not completely fail
* safe, as constructs like:
*
* <pre>
*
* User u = (User)getModelObject();
* u.setName("got you there!");
*
* </pre>
*
* can't be prevented. Indeed it can be argued that any model protection is best dealt with in
* your model objects to be completely secured. Wicket will catch all normal framework-directed
* use though.
*/
public static final Action ENABLE = new Action(Action.ENABLE);
/** Separator for component paths */
public static final char PATH_SEPARATOR = ':';
/**
* Action used with IAuthorizationStrategy to determine whether a component and its children are
* allowed to be rendered.
* <p>
* There are two uses for this method:
* <ul>
* <li>The 'normal' use is for controlling whether a component is rendered without having any
* effect on the rest of the processing. If a strategy lets this method return 'false', then the
* target component and its children will not be rendered, in the same fashion as if that
* component had visibility property 'false'.</li>
* <li>The other use is when a component should block the rendering of the whole page. So
* instead of 'hiding' a component, what we generally want to achieve here is that we force the
* user to logon/give-credentials for a higher level of authorization. For this functionality,
* the strategy implementation should throw a {@link AuthorizationException}, which will then be
* handled further by the framework.</li>
* </ul>
* </p>
*/
public static final Action RENDER = new Action(Action.RENDER);
/** meta data for user specified markup id */
private static final MetaDataKey<String> MARKUP_ID_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/** Basic model IModelComparator implementation for normal object models */
private static final IModelComparator defaultModelComparator = new IModelComparator()
{
private static final long serialVersionUID = 1L;
public boolean compare(Component component, Object b)
{
final Object a = component.getDefaultModelObject();
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.equals(b);
}
};
/** an unused flag */
private static final int FLAG_UNUSED0 = 0x20000000;
private static final int FLAG_UNUSED1 = 0x800000;
private static final int FLAG_UNUSED2 = 0x1000000;
private static final int FLAG_UNUSED3 = 0x10000000;
/** True when a component is being auto-added */
private static final int FLAG_AUTO = 0x0001;
/** Flag for escaping HTML in model strings */
private static final int FLAG_ESCAPE_MODEL_STRINGS = 0x0002;
/** Boolean whether this component's model is inheritable. */
static final int FLAG_INHERITABLE_MODEL = 0x0004;
/** Versioning boolean */
private static final int FLAG_VERSIONED = 0x0008;
/** Visibility boolean */
private static final int FLAG_VISIBLE = 0x0010;
/** Render tag boolean */
private static final int FLAG_RENDER_BODY_ONLY = 0x0020;
/** Ignore attribute modifiers */
private static final int FLAG_IGNORE_ATTRIBUTE_MODIFIER = 0x0040;
/** True when a component is enabled for model updates and is reachable. */
private static final int FLAG_ENABLED = 0x0080;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED1 = 0x0100;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED2 = 0x0200;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED3 = 0x0400;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED4 = 0x0800;
/** Boolean whether this component was rendered at least once for tracking changes. */
private static final int FLAG_HAS_BEEN_RENDERED = 0x1000;
/**
* Internal indicator of whether this component may be rendered given the current context's
* authorization. It overrides the visible flag in case this is false. Authorization is done
* before trying to render any component (otherwise we would end up with a half rendered page in
* the buffer)
*/
private static final int FLAG_IS_RENDER_ALLOWED = 0x2000;
/** Whether or not the component should print out its markup id into the id attribute */
private static final int FLAG_OUTPUT_MARKUP_ID = 0x4000;
/**
* Output a placeholder tag if the component is not visible. This is useful in ajax mode to go
* to visible(false) to visible(true) without the overhead of repainting a visible parent
* container
*/
private static final int FLAG_PLACEHOLDER = 0x8000;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED5 = 0x10000;
/** onInitialize called */
protected static final int FLAG_INITIALIZED = 0x20000;
/** Reserved subclass-definable flag bit */
private static final int FLAG_NOTUSED7 = 0x40000;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED8 = 0x80000;
/**
* Flag that determines whether the model is set. This is necessary because of the way we
* represent component state ({@link #data}). We can't distinguish between model and behavior
* using instanceof, because one object can implement both interfaces. Thus we need this flag -
* when the flag is set, first object in {@link #data} is always model.
*/
private static final int FLAG_MODEL_SET = 0x100000;
/** True when a component is being removed from the hierarchy */
protected static final int FLAG_REMOVING_FROM_HIERARCHY = 0x200000;
/**
* Flag that makes we are in before-render callback phase Set after component.onBeforeRender is
* invoked (right before invoking beforeRender on children)
*/
private static final int FLAG_RENDERING = 0x2000000;
private static final int FLAG_PREPARED_FOR_RENDER = 0x4000000;
private static final int FLAG_AFTER_RENDERING = 0x8000000;
private static final int FLAG_MARKUP_ATTACHED = 0x10000000;
/**
* Flag that restricts visibility of a component when set to true. This is usually used when a
* component wants to restrict visibility of another component. Calling
* {@link #setVisible(boolean)} on a component does not always have the desired effect because
* isVisible() can be overwritten thus this flag offers an alternative that should always work.
*/
private static final int FLAG_VISIBILITY_ALLOWED = 0x40000000;
private static final int FLAG_DETACHING = 0x80000000;
/**
* The name of attribute that will hold markup id
*/
private static final String MARKUP_ID_ATTR_NAME = "id";
/**
* Meta data key for line precise error logging for the moment of addition. Made package private
* for access in {@link MarkupContainer} and {@link Page}
*/
static final MetaDataKey<String> ADDED_AT_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/**
* meta data key for line precise error logging for the moment of construction. Made package
* private for access in {@link Page}
*/
static final MetaDataKey<String> CONSTRUCTED_AT_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/** Component flags. See FLAG_* for possible non-exclusive flag values. */
private int flags = FLAG_VISIBLE | FLAG_ESCAPE_MODEL_STRINGS | FLAG_VERSIONED | FLAG_ENABLED |
FLAG_IS_RENDER_ALLOWED | FLAG_VISIBILITY_ALLOWED;
private static final short RFLAG_ENABLED_IN_HIERARCHY_VALUE = 0x1;
private static final short RFLAG_ENABLED_IN_HIERARCHY_SET = 0x2;
private static final short RFLAG_VISIBLE_IN_HIEARARCHY_VALUE = 0x4;
private static final short RFLAG_VISIBLE_IN_HIERARCHY_SET = 0x8;
/** onconfigure has been called */
private static final short RFLAG_CONFIGURED = 0x10;
private static final short RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED = 0x20;
private static final short RFLAG_INITIALIZE_SUPER_CALL_VERIFIED = 0x40;
/**
* Flags that only keep their value during the request. Useful for cache markers, etc. At the
* end of the request the value of this variable is reset to 0
*/
private transient short requestFlags = 0;
/** Component id. */
private String id;
/** Any parent container. */
private MarkupContainer parent;
/**
* Instead of remembering the whole markupId, we just remember the number for this component so
* we can "reconstruct" the markupId on demand. While this could be part of {@link #data},
* profiling showed that having it as separate property consumes less memory.
*/
int generatedMarkupId = -1;
/** Must only be used by auto components */
private transient IMarkupFragment markup;
/**
* The object that holds the component state.
* <p>
* What's stored here depends on what attributes are set on component. Data can contains
* combination of following attributes:
* <ul>
* <li>Model (indicated by {@link #FLAG_MODEL_SET})
* <li>MetaDataEntry (optionally {@link MetaDataEntry}[] if more metadata entries are present) *
* <li>{@link Behavior}(s) added to component. The behaviors are not stored in separate array,
* they are part of the {@link #data} array (this is in order to save the space of the pointer
* to an empty array as most components have no behaviours). - FIXME - explain why - is this
* correct?
* </ul>
* If there is only one attribute set (i.e. model or MetaDataEntry([]) or one behavior), the
* #data object points directly to value of that attribute. Otherwise the data is of type
* Object[] where the attributes are ordered as specified above.
* <p>
*/
Object data = null;
final int data_start()
{
return getFlag(FLAG_MODEL_SET) ? 1 : 0;
}
final int data_length()
{
if (data == null)
{
return 0;
}
else if (data instanceof Object[] && !(data instanceof MetaDataEntry<?>[]))
{
return ((Object[])data).length;
}
else
{
return 1;
}
}
final Object data_get(int index)
{
if (data == null)
{
return null;
}
else if (data instanceof Object[] && !(data instanceof MetaDataEntry<?>[]))
{
Object[] array = (Object[])data;
return index < array.length ? array[index] : null;
}
else if (index == 0)
{
return data;
}
else
{
return null;
}
}
final Object data_set(int index, Object object)
{
if (index > data_length() - 1)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0 && !(data instanceof Object[] && !(data instanceof MetaDataEntry<?>[])))
{
Object old = data;
data = object;
return old;
}
else
{
Object[] array = (Object[])data;
Object old = array[index];
array[index] = object;
return old;
}
}
final void data_add(Object object)
{
data_insert(-1, object);
}
final void data_insert(int position, Object object)
{
int currentLength = data_length();
if (position == -1)
{
position = currentLength;
}
if (position > currentLength)
{
throw new IndexOutOfBoundsException();
}
if (currentLength == 0)
{
data = object;
}
else if (currentLength == 1)
{
Object[] array = new Object[2];
if (position == 0)
{
array[0] = object;
array[1] = data;
}
else
{
array[0] = data;
array[1] = object;
}
data = array;
}
else
{
Object[] array = new Object[currentLength + 1];
Object[] current = (Object[])data;
int after = currentLength - position;
if (position > 0)
{
System.arraycopy(current, 0, array, 0, position);
}
array[position] = object;
if (after > 0)
{
System.arraycopy(current, position, array, position + 1, after);
}
data = array;
}
}
Object data_remove(int position)
{
int currentLength = data_length();
if (position > currentLength - 1)
{
throw new IndexOutOfBoundsException();
}
else if (currentLength == 1)
{
Object old = data;
data = null;
return old;
}
else if (currentLength == 2)
{
Object[] current = (Object[])data;
if (position == 0)
{
data = current[1];
return current[0];
}
else
{
data = current[0];
return current[1];
}
}
else
{
Object[] current = (Object[])data;
data = new Object[currentLength - 1];
if (position > 0)
{
System.arraycopy(current, 0, data, 0, position);
}
if (position != currentLength - 1)
{
final int left = currentLength - position - 1;
System.arraycopy(current, position + 1, data, position, left);
}
return current[position];
}
}
/**
* Constructor. All components have names. A component's id cannot be null. This is the minimal
* constructor of component. It does not register a model.
*
* @param id
* The non-null id of this component
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id)
{
this(id, null);
}
/**
* Constructor. All components have names. A component's id cannot be null. This constructor
* includes a model.
*
* @param id
* The non-null id of this component
* @param model
* The component's model
*
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id, final IModel<?> model)
{
setId(id);
getApplication().getComponentInstantiationListeners().onInstantiation(this);
final IDebugSettings debugSettings = Application.get().getDebugSettings();
if (debugSettings.isLinePreciseReportingOnNewComponentEnabled())
{
setMetaData(CONSTRUCTED_AT_KEY,
ComponentStrings.toString(this, new MarkupException("constructed")));
}
if (model != null)
{
setModelImpl(wrap(model));
}
}
/**
* Get the Markup associated with the Component. If not subclassed, the parent container is
* asked to return the markup of this child component.
* <p/>
* Components like Panel and Border should return the "calling" markup fragment, e.g.
* <code><span wicket:id="myPanel">body</span></code>. You may use
* Panel/Border/Enclosure.getMarkup(null) to return the associated markup file. And
* Panel/Border/Enclosure.getMarkup(child) will search the child in the appropriate markup
* fragment.
*
* @see MarkupContainer#getMarkup(Component)
*
* @return The markup fragment
*/
public IMarkupFragment getMarkup()
{
if (markup != null)
{
return markup;
}
if (parent == null)
{
throw new MarkupException(
"Can not determine Markup. Component is not yet connected to a parent. " +
toString());
}
markup = parent.getMarkup(this);
return markup;
}
/**
* Called when the component gets added to a parent
*
* @return false, if it was called the first time
*/
final boolean internalOnMarkupAttached()
{
boolean rtn = getFlag(FLAG_MARKUP_ATTACHED);
if (rtn == false)
{
setFlag(FLAG_MARKUP_ATTACHED, true);
onMarkupAttached();
}
return rtn;
}
/**
* Can be subclassed by any user to implement init-like logic which requires the markup to be
* available
*/
protected void onMarkupAttached()
{
if (log.isDebugEnabled())
{
log.debug("Markup available " + toString());
}
// move the component to its real parent if necessary
// moveComponentToItsRealParent();
}
/**
* Move the component to its real parent if necessary
*
* @return true, if it has been moved
*/
private boolean moveComponentToItsRealParent()
{
MarkupContainer parent = getParent();
IMarkupFragment markup = getMarkup();
if ((parent != null) && (markup != null))
{
IMarkupFragment parentMarkup = parent.getMarkup(null);
if ((parentMarkup != null) && (markup != parentMarkup))
{
// The component's markup must be in the same file as its parent
if (markup.getMarkupResourceStream() == parentMarkup.getMarkupResourceStream())
{
MarkupStream stream = new MarkupStream(markup);
stream.skipUntil(ComponentTag.class);
ComponentTag openTag = stream.getTag();
if (openTag != null)
{
MarkupStream parentStream = new MarkupStream(parentMarkup);
if (parentStream.skipUntil(ComponentTag.class))
{
parentStream.next();
}
Stack<ComponentTag> stack = new Stack<ComponentTag>();
while (parentStream.skipUntil(ComponentTag.class))
{
ComponentTag tag = parentStream.getTag();
if (openTag == tag)
{
if (stack.isEmpty() == false)
{
// This tag belong to the real parent
final ComponentTag lastTag = stack.pop();
parent.visitChildren(MarkupContainer.class,
new IVisitor<MarkupContainer, Void>()
{
public void component(final MarkupContainer component,
final IVisit<Void> visit)
{
IMarkupFragment m = component.getMarkup();
MarkupStream ms = new MarkupStream(m);
ms.skipUntil(ComponentTag.class);
if (ms.hasMore() && (lastTag == ms.getTag()))
{
component.add(Component.this);
visit.stop();
return;
}
}
});
}
return false;
}
if (tag.isOpen())
{
if (tag.hasNoCloseTag() == false)
{
stack.push(tag);
}
}
else if (tag.isOpenClose())
{
// noop
}
else if (tag.isClose())
{
if (stack.isEmpty() == false)
{
stack.pop();
}
}
parentStream.next();
}
}
}
}
}
return false;
}
/**
* @return The 'id' attribute from the associated markup tag
*/
public final String getMarkupIdFromMarkup()
{
ComponentTag tag = getMarkupTag();
if (tag != null)
{
String id = tag.getAttribute("id");
if (Strings.isEmpty(id) == false)
{
return id.trim();
}
}
return null;
}
/**
* Set the markup for the component. Note that the component's markup variable is transient and
* thus must only be used for one render cycle. E.g. auto-component are using it. You may also
* it if you subclassed getMarkup().
*
* @param markup
*/
public final void setMarkup(final IMarkupFragment markup)
{
this.markup = markup;
}
/**
* Called once per request on components before they are about to be rendered. This method
* should be used to configure such things as visibility and enabled flags.
* <p>
* Overrides must call {@code super.onConfigure()}, usually before any other code
* </p>
* <p>
* NOTE: Component hierarchy should not be modified inside this method, instead it should be
* done in {@link #onBeforeRender()}
* </p>
* <p>
* NOTE: Why this method is preferrable to directly overriding {@link #isVisible()} and
* {@link #isEnabled()}? Because those methods are called multiple times even for processing of
* a single request. If they contain expensive logic they can slow down the response time of the
* entire page. Further, overriding those methods directly on form components may lead to
* inconsistent or unexpected state depending on when those methods are called in the form
* processing workflow. It is a better practice to push changes to state rather than pull.
* </p>
* <p>
* NOTE: If component's visibility or another property depends on another component you may call
* {@code other.configure()} followed by {@code other.isVisible()} as mentioned in
* {@link #configure()} javadoc.
* </p>
* <p>
* NOTE: Why should {@link #onBeforeRender()} not be used for this? Because if visibility of a
* component is toggled inside {@link #onBeforeRender()} another method needs to be overridden
* to make sure {@link #onBeforeRender()} will be invoked on invisible components:
*
* <pre>
* class MyComponent extends WebComponent
* {
* protected void onBeforeRender()
* {
* setVisible(Math.rand() > 0.5f);
* super.onBeforeRender();
* }
*
* // if this override is forgotten, once invisible component will never become visible
* protected boolean callOnBeforeRenderIfNotVisible()
* {
* return true;
* }
* }
* </pre>
*
* VS
*
* <pre>
* class MyComponent extends WebComponent
* {
* protected void onConfigure()
* {
* setVisible(Math.rand() > 0.5f);
* super.onConfigure();
* }
* }
* </pre>
*/
protected void onConfigure()
{
}
/**
* This method is meant to be used as an alternative to initialize components. Usually the
* component's constructor is used for this task, but sometimes a component cannot be
* initialized in isolation, it may need to access its parent component or its markup in order
* to fully initialize. This method is invoked once per component's lifecycle when a path exists
* from this component to the {@link Page} thus providing the component with an atomic callback
* when the component's environment is built out.
* <p>
* Overrides must call super#{@link #onInitialize()}. Usually this should be the first thing an
* override does, much like a constructor.
* </p>
* <p>
* Parent containers are guaranteed to be initialized before their children
* </p>
*
* <p>
* It is safe to use {@link #getPage()} in this method
* </p>
*
* <p>
* NOTE:The timing of this call is not precise, the contract is that it is called sometime
* before {@link Component#onBeforeRender()}.
* </p>
*
*/
protected void onInitialize()
{
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, true);
}
/**
* Checks if the component has been initialized - {@link #onInitialize()} has been called
*
* @return {@code true} if component has been initialized
*/
final boolean isInitialized()
{
return getFlag(FLAG_INITIALIZED);
}
/**
* Used to call {@link #onInitialize()}
*/
void initialize()
{
fireInitialize();
}
/**
* Used to call {@link #onInitialize()}
*/
final void fireInitialize()
{
if (!getFlag(FLAG_INITIALIZED))
{
setFlag(FLAG_INITIALIZED, true);
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, false);
onInitialize();
if (!getRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly initialized. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onInitialize() in the override of onInitialize() method");
}
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, false);
getApplication().getComponentInitializationListeners().onInitialize(this);
}
}
/**
* Called on very component after the page is rendered. It will call onAfterRender for it self
* and its children.
*/
public final void afterRender()
{
// if the component has been previously attached via attach()
// detach it now
try
{
setFlag(FLAG_AFTER_RENDERING, true);
onAfterRender();
getApplication().getComponentOnAfterRenderListeners().onAfterRender(this);
if (getFlag(FLAG_AFTER_RENDERING))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly detached. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onAfterRender() in the override of onAfterRender() method");
}
// always detach children because components can be attached
// independently of their parents
onAfterRenderChildren();
}
finally
{
// this flag must always be set to false.
setFlag(FLAG_RENDERING, false);
}
}
/**
*
*/
private final void internalBeforeRender()
{
configure();
if ((determineVisibility()) && !getFlag(FLAG_RENDERING) &&
!getFlag(FLAG_PREPARED_FOR_RENDER))
{
setRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED, false);
getApplication().getComponentPreOnBeforeRenderListeners().onBeforeRender(this);
onBeforeRender();
getApplication().getComponentPostOnBeforeRenderListeners().onBeforeRender(this);
if (!getRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly rendered. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onBeforeRender() in the override of onBeforeRender() method");
}
}
}
/**
* We need to postpone calling beforeRender() on components that implement {@link IFeedback}, to
* be sure that all other component's beforeRender() has been already called, so that IFeedbacks
* can collect all feedback messages. This is the key under list of postponed {@link IFeedback}
* is stored to request cycle metadata. The List is then iterated over in
* {@link #prepareForRender()} after calling {@link #beforeRender()}, to initialize postponed
* components.
*/
private static final MetaDataKey<List<Component>> FEEDBACK_LIST = new MetaDataKey<List<Component>>()
{
private static final long serialVersionUID = 1L;
};
/**
* Called for every component when the page is getting to be rendered. it will call
* onBeforeRender for this component and all the child components
*/
public final void beforeRender()
{
if (!(this instanceof IFeedback))
{
internalBeforeRender();
}
else
{
// this component is a feedback. Feedback must be initialized last, so that
// they can collect messages from other components
List<Component> feedbacks = getRequestCycle().getMetaData(FEEDBACK_LIST);
if (feedbacks == null)
{
feedbacks = new ArrayList<Component>();
getRequestCycle().setMetaData(FEEDBACK_LIST, feedbacks);
}
if (this instanceof MarkupContainer)
{
((MarkupContainer)this).visitChildren(IFeedback.class,
new IVisitor<Component, Void>()
{
public void component(Component component, IVisit<Void> visit)
{
component.beforeRender();
}
});
}
if (!feedbacks.contains(this))
{
feedbacks.add(this);
}
}
}
/**
* Triggers {@link #onConfigure()} to be invoked on this component if it has not already during
* this request.
* <p>
* This method should be invoked before any calls to {@link #isVisible()} or
* {@link #isEnabled()}. Usually this method will be called by the framework before the
* component is rendered and so users should not need to call it; however, in cases where
* visibility or enabled or other state of one component depends on the state of another this
* method should be manually invoked on the other component by the user. EG to link visiliby of
* two markup containers the following should be done:
*
* <pre>
* final WebMarkupContainer source=new WebMarkupContainer("a") {
* protected void onConfigure() {
* setVisible(Math.rand()>0.5f);
* }
* };
*
* WebMarkupContainer linked=new WebMarkupContainer("b") {
* protected void onConfigure() {
* source.configure(); // make sure source is configured
* setVisible(source.isVisible());
* }
* }
* </pre>
*
* </p>
*/
public final void configure()
{
if (!getRequestFlag(RFLAG_CONFIGURED))
{
clearEnabledInHierarchyCache();
clearVisibleInHierarchyCache();
onConfigure();
setRequestFlag(RFLAG_CONFIGURED, true);
}
}
/**
* Redirects to any intercept page previously specified by a call to redirectToInterceptPage.
*
* @return True if an original destination was redirected to
* @see Component#redirectToInterceptPage(Page)
*/
public final boolean continueToOriginalDestination()
{
return RestartResponseAtInterceptPageException.continueToOriginalDestination();
}
/**
* Registers a debug feedback message for this component
*
* @param message
* The feedback message
*/
public final void debug(final Serializable message)
{
Session.get().getFeedbackMessages().debug(this, message);
Session.get().dirty();
}
/**
* Signals this Component that it is removed from the Component hierarchy.
*/
final void internalOnRemove()
{
setFlag(FLAG_REMOVING_FROM_HIERARCHY, true);
onRemove();
if (getFlag(FLAG_REMOVING_FROM_HIERARCHY))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly removed from hierachy. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onRemovalFromHierarchy() in the override of onRemovalFromHierarchy() method");
}
removeChildren();
}
/**
* Detaches the component. This is called at the end of the request for all the pages that are
* touched in that request.
*/
public final void detach()
{
// if the component has been previously attached via attach()
// detach it now
setFlag(FLAG_DETACHING, true);
onDetach();
if (getFlag(FLAG_DETACHING))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly detached. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onDetach() in the override of onDetach() method");
}
// always detach models because they can be attached without the
// component. eg component has a compoundpropertymodel and one of its
// children component's getmodelobject is called
detachModels();
// detach any behaviors
new Behaviors(this).detach();
// always detach children because components can be attached
// independently of their parents
detachChildren();
// reset the model to null when the current model is a IWrapModel and
// the model that created it/wrapped in it is a IComponentInheritedModel
// The model will be created next time.
if (getFlag(FLAG_INHERITABLE_MODEL))
{
setModelImpl(null);
setFlag(FLAG_INHERITABLE_MODEL, false);
}
clearEnabledInHierarchyCache();
clearVisibleInHierarchyCache();
requestFlags = 0;
// notify any detach listener
IDetachListener detachListener = getApplication().getFrameworkSettings()
.getDetachListener();
if (detachListener != null)
{
detachListener.onDetach(this);
}
}
/**
* Detaches all models
*/
public void detachModels()
{
// Detach any detachable model from this component
detachModel();
}
/**
* Registers an error feedback message for this component
*
* @param message
* The feedback message
*/
public final void error(final Serializable message)
{
Session.get().getFeedbackMessages().error(this, message);
Session.get().dirty();
}
/**
* Registers an fatal error feedback message for this component
*
* @param message
* The feedback message
*/
public final void fatal(final Serializable message)
{
Session.get().getFeedbackMessages().fatal(this, message);
Session.get().dirty();
}
/**
* Finds the first container parent of this component of the given class.
*
* @param <Z>
* type of parent
*
*
* @param c
* MarkupContainer class to search for
* @return First container parent that is an instance of the given class, or null if none can be
* found
*/
public final <Z> Z findParent(final Class<Z> c)
{
// Start with immediate parent
MarkupContainer current = parent;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
return c.cast(current);
}
// Check parent
current = current.getParent();
}
// Failed to find component
return null;
}
/**
* @return The nearest markup container with associated markup
*/
public final MarkupContainer findParentWithAssociatedMarkup()
{
MarkupContainer container = parent;
while (container != null)
{
if (container.hasAssociatedMarkup())
{
return container;
}
container = container.getParent();
}
// This should never happen since Page always has associated markup
throw new WicketRuntimeException("Unable to find parent with associated markup");
}
/**
* Gets interface to application that this component is a part of.
*
* @return The application associated with the session that this component is in.
* @see Application
*/
public final Application getApplication()
{
return Application.get();
}
/**
* @return A path of the form [page-class-name].[page-relative-path]
* @see Component#getPageRelativePath()
*/
public final String getClassRelativePath()
{
return getClass().getName() + PATH_SEPARATOR + getPageRelativePath();
}
/**
* Gets the converter that should be used by this component.
*
* @param type
* The type to convert to
*
* @return The converter that should be used by this component
*/
public <C> IConverter<C> getConverter(Class<C> type)
{
return getApplication().getConverterLocator().getConverter(type);
}
/**
* Gets whether model strings should be escaped.
*
* @return Returns whether model strings should be escaped
*/
public final boolean getEscapeModelStrings()
{
return getFlag(FLAG_ESCAPE_MODEL_STRINGS);
}
/**
* @return Any feedback message for this component
*/
public final FeedbackMessage getFeedbackMessage()
{
return Session.get().getFeedbackMessages().messageForComponent(this);
}
/**
* Gets the id of this component.
*
* @return The id of this component
*/
public String getId()
{
return id;
}
/**
* @return Innermost model for this component
*/
public final IModel<?> getInnermostModel()
{
return getInnermostModel(getDefaultModel());
}
/**
* Gets the locale for this component. By default, it searches its parents for a locale. If no
* parents (it's a recursive search) returns a locale, it gets one from the session.
*
* @return The locale to be used for this component
* @see Session#getLocale()
*/
public Locale getLocale()
{
if (parent != null)
{
return parent.getLocale();
}
return getSession().getLocale();
}
/**
* Convenience method to provide easy access to the localizer object within any component.
*
* @return The localizer object
*/
public final Localizer getLocalizer()
{
return getApplication().getResourceSettings().getLocalizer();
}
/**
* Get the first component tag in the associated markup
*
* @return first component tag
*/
private final ComponentTag getMarkupTag()
{
IMarkupFragment markup = getMarkup();
if (markup != null)
{
for (int i = 0; i < markup.size(); i++)
{
MarkupElement elem = markup.get(i);
if (elem instanceof ComponentTag)
{
return (ComponentTag)elem;
}
}
}
return null;
}
/**
* THIS IS WICKET INTERNAL ONLY. DO NOT USE IT.
*
* Get a copy of the markup's attributes which are associated with the component.
* <p>
* Modifications to the map returned don't change the tags attributes. It is just a copy.
* <p>
* Note: The component must have been added (directly or indirectly) to a container with an
* associated markup file (Page, Panel or Border).
*
* @return markup attributes
*/
public final ValueMap getMarkupAttributes()
{
ComponentTag tag = getMarkupTag();
if (tag != null)
{
ValueMap attrs = new ValueMap(tag.getAttributes());
attrs.makeImmutable();
return attrs;
}
return ValueMap.EMPTY_MAP;
}
/**
* Get the markupId
*
* @return MarkupId
*/
public final Object getMarkupIdImpl()
{
String id = getMarkupIdFromMarkup();
if (id != null)
{
return id;
}
if (generatedMarkupId != -1)
{
return generatedMarkupId;
}
return getMetaData(MARKUP_ID_KEY);
}
/**
* Find the Page and get net value from an auto-index
*
* @return autoIndex
*/
private final int nextAutoIndex()
{
Page page = findPage();
if (page == null)
{
throw new WicketRuntimeException(
"This component is not (yet) coupled to a page. It has to be able "
+ "to find the page it is supposed to operate in before you can call "
+ "this method (Component#getMarkupId)");
}
return page.getAutoIndex();
}
/**
* Retrieves id by which this component is represented within the markup. This is either the id
* attribute set explicitly via a call to {@link #setMarkupId(String)}, id attribute defined in
* the markup, or an automatically generated id - in that order.
* <p>
* If no id is set and <code>createIfDoesNotExist</code> is false, this method will return null.
* Otherwise it will generate an id value which by default will be unique in the page. This is
* the preferred way as there is no chance of id collision.
* <p>
*
* <p>
* Note: This method should only be called after the component or its parent have been added to
* the page.
*
* @param createIfDoesNotExist
* When there is no existing markup id, determines whether it should be generated or
* whether <code>null</code> should be returned.
*
* @return markup id of the component
*/
public String getMarkupId(boolean createIfDoesNotExist)
{
Object storedMarkupId = getMarkupIdImpl();
if (storedMarkupId instanceof String)
{
return (String)storedMarkupId;
}
if (storedMarkupId == null && createIfDoesNotExist == false)
{
return null;
}
final int generatedMarkupId = storedMarkupId instanceof Integer ? (Integer)storedMarkupId
: Session.get().nextSequenceValue();
if (storedMarkupId == null)
{
setMarkupIdImpl(generatedMarkupId);
}
String markupIdPrefix = "id";
if (!getApplication().usesDeploymentConfig())
{
// in non-deployment mode we make the markup id include component id
// so it is easier to debug
markupIdPrefix = getId();
}
String markupIdPostfix = Integer.toHexString(generatedMarkupId).toLowerCase();
String markupId = markupIdPrefix + markupIdPostfix;
// make sure id is compliant with w3c requirements (starts with a letter)
char c = markupId.charAt(0);
if (!Character.isLetter(c))
{
markupId = "id" + markupId;
}
// escape some noncompliant characters
markupId = Strings.replaceAll(markupId, "_", "__").toString();
markupId = markupId.replace('.', '_');
markupId = markupId.replace('-', '_');
markupId = markupId.replace(' ', '_');
return markupId;
}
/**
* Retrieves id by which this component is represented within the markup. This is either the id
* attribute set explicitly via a call to {@link #setMarkupId(String)}, id attribute defined in
* the markup, or an automatically generated id - in that order.
* <p>
* If no explicit id is set this function will generate an id value that will be unique in the
* page. This is the preferred way as there is no chance of id collision.
* <p>
* Note: This method should only be called after the component or its parent have been added to
* the page.
*
* @return markup id of the component
*/
public String getMarkupId()
{
return getMarkupId(true);
}
/**
* Gets metadata for this component using the given key.
*
* @param <M>
* The type of the metadata.
*
* @param key
* The key for the data
* @return The metadata or null of no metadata was found for the given key
* @see MetaDataKey
*/
public final <M extends Serializable> M getMetaData(final MetaDataKey<M> key)
{
return key.get(getMetaData());
}
/**
*
* @return meta data entry
*/
private MetaDataEntry<?>[] getMetaData()
{
MetaDataEntry<?>[] metaData = null;
// index where we should expect the entry
int index = getFlag(FLAG_MODEL_SET) ? 1 : 0;
int length = data_length();
if (index < length)
{
Object object = data_get(index);
if (object instanceof MetaDataEntry<?>[])
{
metaData = (MetaDataEntry<?>[])object;
}
else if (object instanceof MetaDataEntry)
{
metaData = new MetaDataEntry[] { (MetaDataEntry<?>)object };
}
}
return metaData;
}
/**
* Gets the model. It returns the object that wraps the backing model.
*
* @return The model
*/
public final IModel<?> getDefaultModel()
{
IModel<?> model = getModelImpl();
// If model is null
if (model == null)
{
// give subclass a chance to lazy-init model
model = initModel();
setModelImpl(model);
}
return model;
}
/**
* Gets the backing model object. Unlike getDefaultModel().getObject(), this method returns null
* for a null model.
*
* @return The backing model object
*/
public final Object getDefaultModelObject()
{
final IModel<?> model = getDefaultModel();
if (model != null)
{
try
{
// Get model value for this component.
return model.getObject();
}
catch (RuntimeException ex)
{
log.error("Error while getting default model object for Component: " +
this.toString(true));
throw ex;
}
}
return null;
}
/**
* Gets a model object as a string. Depending on the "escape model strings" flag of the
* component, the string is either HTML escaped or not. "HTML escaped" meaning that only HTML
* sensitive chars are escaped but not all none-ascii chars. Proper HTML encoding should be used
* instead. In case you really need a fully escaped model string you may call
* {@link Strings#escapeMarkup(String, boolean, boolean)} on the model string returned.
*
* @see Strings#escapeMarkup(String, boolean, boolean)
* @see #getEscapeModelStrings()
*
* @return Model object for this component as a string
*/
public final String getDefaultModelObjectAsString()
{
return getDefaultModelObjectAsString(getDefaultModelObject());
}
/**
* Gets a model object as a string. Depending on the "escape model strings" flag of the
* component, the string is either HTML escaped or not. "HTML escaped" meaning that only HTML
* sensitive chars are escaped but not all none-ascii chars. Proper HTML encoding should be used
* instead. In case you really need a fully escaped model string you may call
* {@link Strings#escapeMarkup(String, boolean, boolean)} on the model string returned.
*
* @see Strings#escapeMarkup(String, boolean, boolean)
* @see #getEscapeModelStrings()
*
* @param modelObject
* Model object to convert to string
* @return The string
*/
public final String getDefaultModelObjectAsString(final Object modelObject)
{
if (modelObject != null)
{
// Get converter
final Class<?> objectClass = modelObject.getClass();
final IConverter converter = getConverter(objectClass);
// Model string from property
final String modelString = converter.convertToString(modelObject, getLocale());
if (modelString != null)
{
// If we should escape the markup
if (getFlag(FLAG_ESCAPE_MODEL_STRINGS))
{
// Escape HTML sensitive characters only. Not all none-ascii chars
return Strings.escapeMarkup(modelString, false, false).toString();
}
return modelString;
}
}
return "";
}
/**
* Gets whether or not component will output id attribute into the markup. id attribute will be
* set to the value returned from {@link Component#getMarkupId()}.
*
* @return whether or not component will output id attribute into the markup
*/
public final boolean getOutputMarkupId()
{
return getFlag(FLAG_OUTPUT_MARKUP_ID);
}
/**
* Gets whether or not an invisible component will render a placeholder tag.
*
* @return true if a placeholder tag should be rendered
*/
public final boolean getOutputMarkupPlaceholderTag()
{
return getFlag(FLAG_PLACEHOLDER);
}
/**
* Gets the page holding this component.
*
* @return The page holding this component
* @throws IllegalStateException
* Thrown if component is not yet attached to a Page.
*/
public final Page getPage()
{
// Search for nearest Page
final Page page = findPage();
// If no Page was found
if (page == null)
{
// Give up with a nice exception
throw new WicketRuntimeException("No Page found for component " + this);
}
return page;
}
/**
* Gets the path to this component relative to the page it is in.
*
* @return The path to this component relative to the page it is in
*/
public final String getPageRelativePath()
{
return Strings.afterFirstPathComponent(getPath(), PATH_SEPARATOR);
}
/**
* Gets any parent container, or null if there is none.
*
* @return Any parent container, or null if there is none
*/
public final MarkupContainer getParent()
{
return parent;
}
/**
* Gets this component's path.
*
* @return Colon separated path to this component in the component hierarchy
*/
public final String getPath()
{
final PrependingStringBuffer buffer = new PrependingStringBuffer(32);
for (Component c = this; c != null; c = c.getParent())
{
if (buffer.length() > 0)
{
buffer.prepend(PATH_SEPARATOR);
}
buffer.prepend(c.getId());
}
return buffer.toString();
}
/**
* If false the component's tag will be printed as well as its body (which is default). If true
* only the body will be printed, but not the component's tag.
*
* @return If true, the component tag will not be printed
*/
public final boolean getRenderBodyOnly()
{
return getFlag(FLAG_RENDER_BODY_ONLY);
}
/**
* @return The request for this component's active request cycle
*/
public final Request getRequest()
{
RequestCycle requestCycle = getRequestCycle();
if (requestCycle == null)
{
// Happens often with WicketTester when one forgets to call
// createRequestCycle()
throw new WicketRuntimeException("No RequestCycle is currently set!");
}
return requestCycle.getRequest();
}
/**
* Gets the active request cycle for this component
*
* @return The request cycle
*/
public final RequestCycle getRequestCycle()
{
return RequestCycle.get();
}
/**
* @return The response for this component's active request cycle
*/
public final Response getResponse()
{
return getRequestCycle().getResponse();
}
/**
* Gets the current Session object.
*
* @return The Session that this component is in
*/
public Session getSession()
{
return Session.get();
}
/**
* @return Size of this Component in bytes
*/
public long getSizeInBytes()
{
final MarkupContainer originalParent = parent;
parent = null;
long size = -1;
try
{
size = WicketObjects.sizeof(this);
}
catch (Exception e)
{
log.error("Exception getting size for component " + this, e);
}
parent = originalParent;
return size;
}
/**
* @param key
* Key of string resource in property file
* @return The String
* @see Localizer
*/
public final String getString(final String key)
{
return getString(key, null);
}
/**
* @param key
* The resource key
* @param model
* The model
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel<?> model)
{
return getLocalizer().getString(key, this, model);
}
/**
* @param key
* The resource key
* @param model
* The model
* @param defaultValue
* A default value if the string cannot be found
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel<?> model, final String defaultValue)
{
return getLocalizer().getString(key, this, model, defaultValue);
}
/**
* A convinient method. Same as Session.get().getStyle().
*
* @return The style of this component respectively the style of the Session.
*
* @see org.apache.wicket.Session#getStyle()
*/
public final String getStyle()
{
Session session = getSession();
if (session == null)
{
throw new WicketRuntimeException("Wicket Session object not avaiable");
}
return session.getStyle();
}
/**
* Gets the variation string of this component that will be used to look up markup for this
* component. Subclasses can override this method to define by an instance what markup variation
* should be picked up. By default it will return null or the value of a parent.
*
* @return The variation of this component.
*/
public String getVariation()
{
if (parent != null)
{
return parent.getVariation();
}
return null;
}
/**
* Gets whether this component was rendered at least once.
*
* @return true if the component has been rendered before, false if it is merely constructed
*/
public final boolean hasBeenRendered()
{
return getFlag(FLAG_HAS_BEEN_RENDERED);
}
/**
* @return True if this component has an error message
*/
public final boolean hasErrorMessage()
{
return Session.get().getFeedbackMessages().hasErrorMessageFor(this);
}
/**
* @return True if this component has some kind of feedback message
*/
public final boolean hasFeedbackMessage()
{
return Session.get().getFeedbackMessages().hasMessageFor(this);
}
/**
* Registers an informational feedback message for this component
*
* @param message
* The feedback message
*/
public final void info(final Serializable message)
{
Session.get().getFeedbackMessages().info(this, message);
Session.get().dirty();
}
/**
* Authorizes an action for a component.
*
* @param action
* The action to authorize
* @return True if the action is allowed
* @throws AuthorizationException
* Can be thrown by implementation if action is unauthorized
*/
public final boolean isActionAuthorized(Action action)
{
IAuthorizationStrategy authorizationStrategy = getSession().getAuthorizationStrategy();
if (authorizationStrategy != null)
{
return authorizationStrategy.isActionAuthorized(this, action);
}
return true;
}
/**
* @return true if this component is authorized to be enabled, false otherwise
*/
public final boolean isEnableAllowed()
{
return isActionAuthorized(ENABLE);
}
/**
* Gets whether this component is enabled. Specific components may decide to implement special
* behavior that uses this property, like web form components that add a disabled='disabled'
* attribute when enabled is false.
*
* @return Whether this component is enabled.
*/
public boolean isEnabled()
{
return getFlag(FLAG_ENABLED);
}
/**
* Checks the security strategy if the {@link Component#RENDER} action is allowed on this
* component
*
* @return ture if {@link Component#RENDER} action is allowed, false otherwise
*/
public final boolean isRenderAllowed()
{
return getFlag(FLAG_IS_RENDER_ALLOWED);
}
/**
* Returns if the component is stateless or not. It checks the stateless hint if that is false
* it returns directly false. If that is still true it checks all its behaviors if they can be
* stateless.
*
* @return whether the component is stateless.
*/
public final boolean isStateless()
{
if (!getStatelessHint())
{
return false;
}
for (Behavior behavior : getBehaviors())
{
if (!behavior.getStatelessHint(this))
{
return false;
}
}
return true;
}
/**
* @return True if this component is versioned
*/
public boolean isVersioned()
{
// Is the component itself versioned?
if (!getFlag(FLAG_VERSIONED))
{
return false;
}
else
{
// If there's a parent and this component is versioned
if (parent != null)
{
// Check if the parent is unversioned. If any parent
// (recursively) is unversioned, then this component is too
if (!parent.isVersioned())
{
return false;
}
}
return true;
}
}
/**
* Gets whether this component and any children are visible.
* <p>
* WARNING: this method can be called multiple times during a request. If you override this
* method, it is a good idea to keep it cheap in terms of processing. Alternatively, you can
* call {@link #setVisible(boolean)}.
* <p>
*
* @return True if component and any children are visible
*/
public boolean isVisible()
{
return getFlag(FLAG_VISIBLE);
}
/**
* Checks if the component itself and all its parents are visible.
*
* @return true if the component and all its parents are visible.
*/
public final boolean isVisibleInHierarchy()
{
Component parent = getParent();
if (parent != null && !parent.isVisibleInHierarchy())
{
return false;
}
else
{
return determineVisibility();
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Sets the RENDERING flag and removes the PREPARED_FOR_RENDER flag on component and it's
* children.
*
* @param setRenderingFlag
* if this is false only the PREPARED_FOR_RENDER flag is removed from component, the
* RENDERING flag is not set.
*
* @see #internalPrepareForRender(boolean)
*/
public final void markRendering(boolean setRenderingFlag)
{
internalMarkRendering(setRenderingFlag);
}
/**
* Called to indicate that the model content for this component has been changed
*/
public final void modelChanged()
{
// Call user code
internalOnModelChanged();
onModelChanged();
}
/**
* Called to indicate that the model content for this component is about to change
*/
public final void modelChanging()
{
checkHierarchyChange(this);
// Call user code
onModelChanging();
// Tell the page that our model changed
final Page page = findPage();
if (page != null)
{
page.componentModelChanging(this);
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
* <p>
* Prepares the component and it's children for rendering. On whole page render this method must
* be called on the page. On AJAX request, this method must be called on updated component.
*
* @param setRenderingFlag
* Whether to set the rendering flag. This must be true if the page is about to be
* rendered. However, there are usecases to call this method without an immediate
* render (e.g. on stateless listner request target to build the component
* hierarchy), in that case setRenderingFlag should be false
*/
public void internalPrepareForRender(boolean setRenderingFlag)
{
beforeRender();
if (setRenderingFlag)
{
// only process feedback panel when we are about to be rendered.
// setRenderingFlag is false in case prepareForRender is called only to build component
// hierarchy (i.e. in BookmarkableListenerInterfaceRequestTarget).
// prepareForRender(true) is always called before the actual rendering is done so
// that's where feedback panels gather the messages
List<Component> feedbacks = getRequestCycle().getMetaData(FEEDBACK_LIST);
if (feedbacks != null)
{
for (Component feedback : feedbacks)
{
feedback.internalBeforeRender();
}
}
getRequestCycle().setMetaData(FEEDBACK_LIST, null);
}
markRendering(setRenderingFlag);
// check authorization
// first the component itself
// (after attach as otherwise list views etc wont work)
setRenderAllowed();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Prepares the component and it's children for rendering. On whole page render this method must
* be called on the page. On AJAX request, this method must be called on updated component.
*/
public final void prepareForRender()
{
internalPrepareForRender(true);
}
/**
* Redirects browser to an intermediate page such as a sign-in page. The current request's url
* is saved for future use by method continueToOriginalDestination(); Only use this method when
* you plan to continue to the current url at some later time; otherwise just use
* setResponsePage or - when you are in a constructor or checkAccessMethod, call redirectTo.
*
* @param page
* The sign in page
*
* @see Component#continueToOriginalDestination()
*/
public final void redirectToInterceptPage(final Page page)
{
throw new RestartResponseAtInterceptPageException(page);
}
/**
* Removes this component from its parent. It's important to remember that a component that is
* removed cannot be referenced from the markup still.
*/
public final void remove()
{
if (parent == null)
{
throw new IllegalStateException("Cannot remove " + this + " from null parent!");
}
parent.remove(this);
}
/**
* Render the Component.
*/
public final void render()
{
RuntimeException exception = null;
try
{
// Invoke prepareForRender only if this is the root component to be rendered
MarkupContainer parent = getParent();
if ((parent == null) || (parent.getFlag(FLAG_RENDERING) == false) || isAuto())
{
internalPrepareForRender(true);
}
// Do the render
internalRender();
}
catch (final RuntimeException ex)
{
// Remember it as the originating exception
exception = ex;
}
finally
{
try
{
// Cleanup
afterRender();
}
catch (RuntimeException ex2)
{
// Only remember it if not already another exception happened
if (exception == null)
{
exception = ex2;
}
}
}
// Re-throw if needed
if (exception != null)
{
throw exception;
}
}
/**
* Performs a render of this component as part of a Page level render process.
*/
private final void internalRender()
{
// Make sure there is a markup available for the Component
IMarkupFragment markup = getMarkup();
if (markup == null)
{
throw new MarkupNotFoundException("Markup not found for Component: " + toString());
}
// MarkupStream is an Iterator for the markup
MarkupStream markupStream = new MarkupStream(markup);
// Flag: we stated the render process
markRendering(true);
MarkupElement elem = markup.get(0);
if (elem instanceof ComponentTag)
{
// Guarantee that the markupStream is set and determineVisibility not yet tested
// See WICKET-2049
((ComponentTag)elem).onBeforeRender(this, markupStream);
}
// Determine if component is visible using it's authorization status
// and the isVisible property.
if (determineVisibility())
{
setFlag(FLAG_HAS_BEEN_RENDERED, true);
// Rendering is beginning
if (log.isDebugEnabled())
{
log.debug("Begin render " + this);
}
try
{
notifyBehaviorsComponentBeforeRender();
onRender();
notifyBehaviorsComponentRendered();
// Component has been rendered
rendered();
}
catch (RuntimeException ex)
{
onException(ex);
}
if (log.isDebugEnabled())
{
log.debug("End render " + this);
}
}
// elem is null when rendering a page
else if ((elem != null) && (elem instanceof ComponentTag))
{
if (getFlag(FLAG_PLACEHOLDER))
{
renderPlaceholderTag((ComponentTag)elem, getResponse());
}
}
}
/**
* Called when a runtime exception is caught during the render process
*
* @param ex
* The exception caught.
*/
private void onException(final RuntimeException ex)
{
// Call each behaviors onException() to allow the
// behavior to clean up
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
try
{
behavior.onException(this, ex);
}
catch (Throwable ex2)
{
log.error("Error while cleaning up after exception", ex2);
}
}
}
// Re-throw the exception
throw ex;
}
/**
* Renders a placeholder tag for the component when it is invisible and
* {@link #setOutputMarkupPlaceholderTag(boolean)} has been called with <code>true</code>.
*
* @param tag
* component tag
* @param response
* response
*/
protected void renderPlaceholderTag(final ComponentTag tag, final Response response)
{
String ns = Strings.isEmpty(tag.getNamespace()) ? null : tag.getNamespace() + ":";
response.write("<");
if (ns != null)
{
response.write(ns);
}
response.write(tag.getName());
response.write(" id=\"");
response.write(getMarkupId());
response.write("\" style=\"display:none\"></");
if (ns != null)
{
response.write(ns);
}
response.write(tag.getName());
response.write(">");
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT.
* <p>
* Renders the component at the current position in the given markup stream. The method
* onComponentTag() is called to allow the component to mutate the start tag. The method
* onComponentTagBody() is then called to permit the component to render its body.
*/
public final void internalRenderComponent()
{
final IMarkupFragment markup = getMarkup();
if (markup == null)
{
throw new MarkupException("Markup not found. Component: " + toString());
}
final MarkupStream markupStream = new MarkupStream(markup);
// Get mutable copy of next tag
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
// Call any tag handler
onComponentTag(tag);
// If we're an openclose tag
if (!tag.isOpenClose() && !tag.isOpen())
{
// We were something other than <tag> or <tag/>
markupStream.throwMarkupException("Method renderComponent called on bad markup element: " +
tag);
}
if (tag.isOpenClose() && openTag.isOpen())
{
markupStream.throwMarkupException("You can not modify a open tag to open-close: " + tag);
}
try
{
// Render open tag
if (getRenderBodyOnly() == false)
{
renderComponentTag(tag);
}
markupStream.next();
// Render the body only if open-body-close. Do not render if open-close.
if (tag.isOpen())
{
// Render the body
onComponentTagBody(markupStream, tag);
}
// Render close tag
if (tag.isOpen())
{
if (openTag.isOpen())
{
renderClosingComponentTag(markupStream, tag, getRenderBodyOnly());
}
else if (getRenderBodyOnly() == false)
{
if (needToRenderTag(openTag))
{
// Close the manually opened tag. And since the user might have changed the
// tag name ...
getResponse().write(tag.syntheticCloseTagString());
}
}
}
}
catch (WicketRuntimeException wre)
{
throw wre;
}
catch (RuntimeException re)
{
throw new WicketRuntimeException("Exception in rendering component: " + this, re);
}
}
/**
*
* @param openTag
* @return true, if the tag shall be rendered
*/
private boolean needToRenderTag(final ComponentTag openTag)
{
// If a open-close tag has been modified to be open-body-close than a
// synthetic close tag must be rendered.
boolean renderTag = (openTag == null ? false : !(openTag instanceof WicketTag));
if (renderTag == false)
{
renderTag = !((getRequest() instanceof WebRequest) && ((WebRequest)getRequest()).isAjax());
renderTag &= !getApplication().getMarkupSettings().getStripWicketTags();
}
return renderTag;
}
/**
* Called to indicate that a component has been rendered. This method should only very rarely be
* called at all. Some components may render its children without calling render() on them.
* These components need to call rendered() to indicate that its child components were actually
* rendered, the framework would think they had never been rendered, and in development mode
* this would result in a runtime exception.
*/
public final void rendered()
{
Page page = findPage();
if (page != null)
{
// Tell the page that the component rendered
page.componentRendered(this);
}
else
{
log.error("Component is not connected to a Page. Cannot register the component as being rendered. Component: " +
toString());
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT.
*
* Print to the web response what ever the component wants to contribute to the head section.
* Make sure that all attached behaviors are asked as well.
* <p>
* NOT intended for overriding by framework clients. Rather, use
* {@link IHeaderContributor#renderHead(org.apache.wicket.markup.html.IHeaderResponse)}
* </p>
*
* @param container
* The HtmlHeaderContainer
*/
public void renderHead(final HtmlHeaderContainer container)
{
if (isVisibleInHierarchy() && isRenderAllowed())
{
if (log.isDebugEnabled())
{
log.debug("renderHead: " + toString(false));
}
IHeaderResponse response = container.getHeaderResponse();
// Allow component to contribute
if (response.wasRendered(this) == false)
{
renderHead(response);
response.markRendered(this);
}
// Than ask all behaviors
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
if (response.wasRendered(behavior) == false)
{
behavior.renderHead(this, response);
response.markRendered(behavior);
}
}
}
}
}
/**
* Replaces this component with another. The replacing component must have the same component id
* as this component. This method serves as a shortcut to
*
* <code>this.getParent().replace(replacement)</code>
*
* and provides a better context for errors.
* <p>
* Usage: <code>component = component.replaceWith(replacement);</code>
* </p>
*
* @since 1.2.1
*
* @param replacement
* component to replace this one
* @return the component which replaced this one
*/
public Component replaceWith(Component replacement)
{
if (replacement == null)
{
throw new IllegalArgumentException("Argument [[replacement]] cannot be null.");
}
if (!getId().equals(replacement.getId()))
{
throw new IllegalArgumentException(
"Replacement component must have the same id as the component it will replace. Replacement id [[" +
replacement.getId() + "]], replaced id [[" + getId() + "]].");
}
if (parent == null)
{
throw new IllegalStateException(
"This method can only be called on a component that has already been added to its parent.");
}
parent.replace(replacement);
return replacement;
}
/**
* @param component
* The component to compare with
* @return True if the given component's model is the same as this component's model.
*/
public final boolean sameInnermostModel(final Component component)
{
return sameInnermostModel(component.getDefaultModel());
}
/**
* @param model
* The model to compare with
* @return True if the given component's model is the same as this component's model.
*/
public final boolean sameInnermostModel(final IModel<?> model)
{
// Get the two models
IModel<?> thisModel = getDefaultModel();
// If both models are non-null they could be the same
if (thisModel != null && model != null)
{
return getInnermostModel(thisModel) == getInnermostModel(model);
}
return false;
}
/**
* Sets whether this component is enabled. Specific components may decide to implement special
* behavior that uses this property, like web form components that add a disabled='disabled'
* attribute when enabled is false. If it is not enabled, it will not be allowed to call any
* listener method on it (e.g. Link.onClick) and the model object will be protected (for the
* common use cases, not for programmer's misuse)
*
* @param enabled
* whether this component is enabled
* @return This
*/
public final Component setEnabled(final boolean enabled)
{
// Is new enabled state a change?
if (enabled != getFlag(FLAG_ENABLED))
{
// Tell the page that this component's enabled was changed
if (isVersioned())
{
final Page page = findPage();
if (page != null)
{
addStateChange();
}
}
// Change visibility
setFlag(FLAG_ENABLED, enabled);
onEnabledStateChanged();
}
return this;
}
void clearEnabledInHierarchyCache()
{
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET, false);
}
void onEnabledStateChanged()
{
clearEnabledInHierarchyCache();
}
/**
* Sets whether model strings should be escaped.
*
* @param escapeMarkup
* True is model strings should be escaped
* @return This
*/
public final Component setEscapeModelStrings(final boolean escapeMarkup)
{
setFlag(FLAG_ESCAPE_MODEL_STRINGS, escapeMarkup);
return this;
}
/**
* Set markup ID, which must be String or Integer
*
* @param markupId
*/
public final void setMarkupIdImpl(Object markupId)
{
if (markupId != null && !(markupId instanceof String) && !(markupId instanceof Integer))
{
throw new IllegalArgumentException("markupId must be String or Integer");
}
if (markupId instanceof Integer)
{
generatedMarkupId = (Integer)markupId;
setMetaData(MARKUP_ID_KEY, null);
return;
}
generatedMarkupId = -1;
setMetaData(MARKUP_ID_KEY, (String)markupId);
setOutputMarkupId(true);
}
/**
* Copy markupId
*
* @param comp
*/
final void setMarkupId(Component comp)
{
Args.notNull(comp, "comp");
generatedMarkupId = comp.generatedMarkupId;
setMetaData(MARKUP_ID_KEY, comp.getMetaData(MARKUP_ID_KEY));
setOutputMarkupId(comp.getOutputMarkupId());
}
/**
* Sets this component's markup id to a user defined value. It is up to the user to ensure this
* value is unique.
* <p>
* The recommended way is to let wicket generate the value automatically, this method is here to
* serve as an override for that value in cases where a specific id must be used.
* <p>
* If null is passed in the user defined value is cleared and markup id value will fall back on
* automatically generated value
*
* @see #getMarkupId()
*
* @param markupId
* markup id value or null to clear any previous user defined value
* @return this for chaining
*/
public Component setMarkupId(String markupId)
{
if (markupId != null && Strings.isEmpty(markupId))
{
throw new IllegalArgumentException("Markup id cannot be an empty string");
}
// TODO check if an automatic id has already been generated or getmarkupid() called
// previously and throw an illegalstateexception because something else might be depending
// on previous id
setMarkupIdImpl(markupId);
return this;
}
/**
* Sets the metadata for this component using the given key. If the metadata object is not of
* the correct type for the metadata key, an IllegalArgumentException will be thrown. For
* information on creating MetaDataKeys, see {@link MetaDataKey}.
*
* @param <M>
* The type of the metadata
*
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @throws IllegalArgumentException
* @see MetaDataKey
*/
public final <M> void setMetaData(final MetaDataKey<M> key, final M object)
{
MetaDataEntry<?>[] old = getMetaData();
Object metaData = null;
MetaDataEntry<?>[] metaDataArray = key.set(getMetaData(), object);
if (metaDataArray != null && metaDataArray.length > 0)
{
metaData = (metaDataArray.length > 1) ? metaDataArray : metaDataArray[0];
}
int index = getFlag(FLAG_MODEL_SET) ? 1 : 0;
if (old == null && metaData != null)
{
data_insert(index, metaData);
}
else if (old != null && metaData != null)
{
data_set(index, metaData);
}
else if (old != null && metaData == null)
{
data_remove(index);
}
}
/**
* Sets the given model.
* <p>
* WARNING: DO NOT OVERRIDE THIS METHOD UNLESS YOU HAVE A VERY GOOD REASON FOR IT. OVERRIDING
* THIS MIGHT OPEN UP SECURITY LEAKS AND BREAK BACK-BUTTON SUPPORT.
* </p>
*
* @param model
* The model
* @return This
*/
public Component setDefaultModel(final IModel<?> model)
{
IModel<?> prevModel = getModelImpl();
// Detach current model
if (prevModel != null)
{
prevModel.detach();
}
IModel<?> wrappedModel = prevModel;
if (prevModel instanceof IWrapModel)
{
wrappedModel = ((IWrapModel<?>)prevModel).getWrappedModel();
}
// Change model
if (wrappedModel != model)
{
if (wrappedModel != null)
{
addStateChange();
}
setModelImpl(wrap(model));
}
modelChanged();
return this;
}
/**
* @return model
*/
IModel<?> getModelImpl()
{
if (getFlag(FLAG_MODEL_SET))
{
return (IModel<?>)data_get(0);
}
return null;
}
/**
*
* @param model
*/
void setModelImpl(IModel<?> model)
{
if (getFlag(FLAG_MODEL_SET))
{
if (model != null)
{
data_set(0, model);
}
else
{
data_remove(0);
setFlag(FLAG_MODEL_SET, false);
}
}
else
{
if (model != null)
{
data_insert(0, model);
setFlag(FLAG_MODEL_SET, true);
}
}
}
/**
* Sets the backing model object. Unlike <code>getDefaultModel().setObject(object)</code>, this
* method checks authorisation and model comparator, and invokes <code>modelChanging</code> and
* <code>modelChanged</code> if the value really changes.
*
* @param object
* The object to set
* @return This
*/
@SuppressWarnings("unchecked")
public final Component setDefaultModelObject(final Object object)
{
final IModel<Object> model = (IModel<Object>)getDefaultModel();
// Check whether anything can be set at all
if (model == null)
{
throw new IllegalStateException(
"Attempt to set model object on null model of component: " + getPageRelativePath());
}
// Check authorization
if (!isActionAuthorized(ENABLE))
{
throw new UnauthorizedActionException(this, ENABLE);
}
// Check whether this will result in an actual change
if (!getModelComparator().compare(this, object))
{
modelChanging();
model.setObject(object);
modelChanged();
}
return this;
}
/**
* Sets whether or not component will output id attribute into the markup. id attribute will be
* set to the value returned from {@link Component#getMarkupId()}.
*
* @param output
* True if the component will output the id attribute into markup. Please note that
* the default behavior is to use the same id as the component. This means that your
* component must begin with [a-zA-Z] in order to generate a valid markup id
* according to: http://www.w3.org/TR/html401/types.html#type-name
*
* @return this for chaining
*/
public final Component setOutputMarkupId(final boolean output)
{
setFlag(FLAG_OUTPUT_MARKUP_ID, output);
return this;
}
/**
* Render a placeholder tag when the component is not visible. The tag is of form:
* <componenttag style="display:none;" id="markupid"/>. This method will also call
* <code>setOutputMarkupId(true)</code>.
*
* This is useful, for example, in ajax situations where the component starts out invisible and
* then becomes visible through an ajax update. With a placeholder tag already in the markup you
* do not need to repaint this component's parent, instead you can repaint the component
* directly.
*
* When this method is called with parameter <code>false</code> the outputmarkupid flag is not
* reverted to false.
*
* @param outputTag
* @return this for chaining
*/
public final Component setOutputMarkupPlaceholderTag(final boolean outputTag)
{
if (outputTag != getFlag(FLAG_PLACEHOLDER))
{
if (outputTag)
{
setOutputMarkupId(true);
setFlag(FLAG_PLACEHOLDER, true);
}
else
{
setFlag(FLAG_PLACEHOLDER, false);
// I think it's better to not setOutputMarkupId to false...
// user can do it if we want
}
}
return this;
}
/**
* If false the component's tag will be printed as well as its body (which is default). If true
* only the body will be printed, but not the component's tag.
*
* @param renderTag
* If true, the component tag will not be printed
* @return This
*/
public final Component setRenderBodyOnly(final boolean renderTag)
{
setFlag(FLAG_RENDER_BODY_ONLY, renderTag);
return this;
}
/**
* Sets the page that will respond to this request
*
* @param <C>
*
* @param cls
* The response page class
* @see RequestCycle#setResponsePage(Class)
*/
public final <C extends IRequestablePage> void setResponsePage(final Class<C> cls)
{
getRequestCycle().setResponsePage(cls, null);
}
/**
* Sets the page class and its parameters that will respond to this request
*
* @param <C>
*
* @param cls
* The response page class
* @param parameters
* The parameters for this bookmarkable page.
* @see RequestCycle#setResponsePage(Class, PageParameters)
*/
public final <C extends IRequestablePage> void setResponsePage(final Class<C> cls,
PageParameters parameters)
{
getRequestCycle().setResponsePage(cls, parameters);
}
/**
* Sets the page that will respond to this request
*
* @param page
* The response page
*
* @see RequestCycle#setResponsePage(org.apache.wicket.request.component.IRequestablePage)
*/
public final void setResponsePage(final Page page)
{
getRequestCycle().setResponsePage(page);
}
/**
* @param versioned
* True to turn on versioning for this component, false to turn it off for this
* component and any children.
* @return This
*/
public Component setVersioned(boolean versioned)
{
setFlag(FLAG_VERSIONED, versioned);
return this;
}
/**
* Sets whether this component and any children are visible.
*
* @param visible
* True if this component and any children should be visible
* @return This
*/
public final Component setVisible(final boolean visible)
{
// Is new visibility state a change?
if (visible != getFlag(FLAG_VISIBLE))
{
// record component's visibility change
addStateChange();
// Change visibility
setFlag(FLAG_VISIBLE, visible);
onVisibleStateChanged();
}
return this;
}
void clearVisibleInHierarchyCache()
{
setRequestFlag(RFLAG_VISIBLE_IN_HIERARCHY_SET, false);
}
void onVisibleStateChanged()
{
clearVisibleInHierarchyCache();
}
/**
* Gets the string representation of this component.
*
* @return The path to this component
*/
@Override
public String toString()
{
return toString(false);
}
/**
* @param detailed
* True if a detailed string is desired
* @return The string
*/
public String toString(final boolean detailed)
{
if (detailed)
{
final Page page = findPage();
if (page == null)
{
return new StringBuilder("[Component id = ").append(getId())
.append(", page = <No Page>, path = ")
.append(getPath())
.append(".")
.append(Classes.simpleName(getClass()))
.append("]")
.toString();
}
else
{
return new StringBuilder("[Component id = ").append(getId())
.append(", page = ")
.append(getPage().getClass().getName())
.append(", path = ")
.append(getPath())
.append(".")
.append(Classes.simpleName(getClass()))
.append(", isVisible = ")
.append((determineVisibility()))
.append(", isVersioned = ")
.append(isVersioned())
.append("]")
.toString();
}
}
else
{
return "[Component id = " + getId() + "]";
}
}
/**
* Returns a bookmarkable URL that references a given page class using a given set of page
* parameters. Since the URL which is returned contains all information necessary to instantiate
* and render the page, it can be stored in a user's browser as a stable bookmark.
*
* @param <C>
*
* @see RequestCycle#urlFor(Class, org.apache.wicket.request.mapper.parameter.PageParameters)
*
* @param pageClass
* Class of page
* @param parameters
* Parameters to page
* @return Bookmarkable URL to page
*/
public final <C extends Page> CharSequence urlFor(final Class<C> pageClass,
final PageParameters parameters)
{
return getRequestCycle().urlFor(pageClass, parameters);
}
/**
* Gets a URL for the listener interface on a behavior (e.g. IBehaviorListener on
* AjaxPagingNavigationBehavior).
*
* @param behaviour
* The behavior that the URL should point to
* @param listener
* The listener interface that the URL should call
* @return The URL
*/
public final CharSequence urlFor(final Behavior behaviour,
final RequestListenerInterface listener)
{
PageAndComponentProvider provider = new PageAndComponentProvider(getPage(), this);
int id = getBehaviorId(behaviour);
IRequestHandler handler;
if (getPage().isPageStateless())
{
handler = new BookmarkableListenerInterfaceRequestHandler(provider, listener, id);
}
else
{
handler = new ListenerInterfaceRequestHandler(provider, listener, id);
}
return getRequestCycle().urlFor(handler);
}
/**
* Returns a URL that references the given request target.
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param requestHandler
* the request target to reference
*
* @return a URL that references the given request target
*/
public final CharSequence urlFor(final IRequestHandler requestHandler)
{
return getRequestCycle().urlFor(requestHandler);
}
/**
* Gets a URL for the listener interface (e.g. ILinkListener).
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param listener
* The listener interface that the URL should call
* @return The URL
*/
public final CharSequence urlFor(final RequestListenerInterface listener)
{
PageAndComponentProvider provider = new PageAndComponentProvider(getPage(), this);
IRequestHandler handler;
if (getPage().isPageStateless())
{
handler = new BookmarkableListenerInterfaceRequestHandler(provider, listener);
}
else
{
handler = new ListenerInterfaceRequestHandler(provider, listener);
}
return getRequestCycle().urlFor(handler);
}
/**
* Returns a URL that references a shared resource through the provided resource reference.
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param resourceReference
* The resource reference
* @param parameters
* parameters or {@code null} if none
* @return The url for the shared resource
*/
public final CharSequence urlFor(final ResourceReference resourceReference,
PageParameters parameters)
{
return getRequestCycle().urlFor(resourceReference, parameters);
}
/**
* Traverses all parent components of the given class in this container, calling the visitor's
* visit method at each one.
*
* @param c
* Class
* @param visitor
* The visitor to call at each parent of the given type
* @return First non-null value returned by visitor callback
*/
public final <R> R visitParents(final Class<?> c, final IVisitor<Component, R> visitor)
{
// Start here
Component current = getParent();
Visit<R> visit = new Visit<R>();
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
visitor.component(current, visit);
if (visit.isStopped())
{
return visit.getResult();
}
}
// Check parent
current = current.getParent();
}
return null;
}
/**
* Registers a warning feedback message for this component.
*
* @param message
* The feedback message
*/
public final void warn(final Serializable message)
{
Session.get().getFeedbackMessages().warn(this, message);
Session.get().dirty();
}
/**
* {@link Behavior#beforeRender(Component)} Notify all behaviors that are assigned to this
* component that the component is about to be rendered.
*/
private void notifyBehaviorsComponentBeforeRender()
{
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
behavior.beforeRender(this);
}
}
}
/**
* {@link Behavior#afterRender(Component)} Notify all behaviors that are assigned to this
* component that the component has rendered.
*/
private void notifyBehaviorsComponentRendered()
{
// notify the behaviors that component has been rendered
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
behavior.afterRender(this);
}
}
}
/**
* TODO WICKET-NG rename to something more useful - like componentChanged(), this method used to
* be called with a Change object
*
* Adds state change to page.
*/
protected final void addStateChange()
{
checkHierarchyChange(this);
final Page page = findPage();
if (page != null)
{
page.componentStateChanging(this);
}
}
/**
* Checks whether the given type has the expected name.
*
* @param tag
* The tag to check
* @param name
* The expected tag name
* @throws MarkupException
* Thrown if the tag is not of the right name
*/
protected final void checkComponentTag(final ComponentTag tag, final String name)
{
if (!tag.getName().equalsIgnoreCase(name))
{
String msg = String.format("Component [%s] (path = [%s]) must be "
+ "applied to a tag of type [%s], not: %s", getId(), getPath(), name,
tag.toUserDebugString());
findMarkupStream().throwMarkupException(msg);
}
}
/**
* Checks that a given tag has a required attribute value.
*
* @param tag
* The tag
* @param key
* The attribute key
* @param value
* The required value for the attribute key
* @throws MarkupException
* Thrown if the tag does not have the required attribute value
*/
protected final void checkComponentTagAttribute(final ComponentTag tag, final String key,
final String value)
{
if (key != null)
{
final String tagAttributeValue = tag.getAttributes().getString(key);
if (tagAttributeValue == null || !value.equalsIgnoreCase(tagAttributeValue))
{
String msg = String.format("Component [%s] (path = [%s]) must be applied to a tag "
+ "with [%s] attribute matching [%s], not [%s]", getId(), getPath(), key,
value, tagAttributeValue);
findMarkupStream().throwMarkupException(msg);
}
}
}
/**
* Checks whether the hierarchy may be changed at all, and throws an exception if this is not
* the case.
*
* @param component
* the component which is about to be added or removed
*/
protected void checkHierarchyChange(final Component component)
{
// Throw exception if modification is attempted during rendering
if (!component.isAuto() && getFlag(FLAG_RENDERING))
{
throw new WicketRuntimeException(
"Cannot modify component hierarchy after render phase has started (page version cant change then anymore)");
}
}
/**
* Detaches the model for this component if it is detachable.
*/
protected void detachModel()
{
IModel<?> model = getModelImpl();
if (model != null)
{
model.detach();
}
// also detach the wrapped model of a component assigned wrap (not
// inherited)
if (model instanceof IWrapModel && !getFlag(FLAG_INHERITABLE_MODEL))
{
((IWrapModel<?>)model).getWrappedModel().detach();
}
}
/**
* Prefixes an exception message with useful information about this. component.
*
* @param message
* The message
* @return The modified message
*/
protected final String exceptionMessage(final String message)
{
return message + ":\n" + toString();
}
/**
* Finds the markup stream for this component.
*
* @return The markup stream for this component. Since a Component cannot have a markup stream,
* we ask this component's parent to search for it.
* @TODO can be removed in 1.5
*/
protected final MarkupStream findMarkupStream()
{
return new MarkupStream(getMarkup());
}
/**
* If this Component is a Page, returns self. Otherwise, searches for the nearest Page parent in
* the component hierarchy. If no Page parent can be found, null is returned.
*
* @return The Page or null if none can be found
*/
protected final Page findPage()
{
// Search for page
return (Page)(this instanceof Page ? this : findParent(Page.class));
}
/**
* Gets the subset of the currently coupled {@link Behavior}s that are of the provided type as a
* unmodifiable list. Returns an empty list rather than null if there are no behaviors coupled
* to this component.
*
* @param type
* The type or null for all
* @return The subset of the currently coupled behaviors that are of the provided type as a
* unmodifiable list or null
* @param <M>
* A class derived from IBehavior
*/
public <M extends Behavior> List<M> getBehaviors(Class<M> type)
{
return new Behaviors(this).getBehaviors(type);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getFlag(final int flag)
{
return (flags & flag) != 0;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getRequestFlag(final short flag)
{
return (requestFlags & flag) != 0;
}
/**
* Finds the innermost IModel object for an IModel that might contain nested IModel(s).
*
* @param model
* The model
* @return The innermost (most nested) model
*/
protected final IModel<?> getInnermostModel(final IModel<?> model)
{
IModel<?> nested = model;
while (nested != null && nested instanceof IWrapModel)
{
final IModel<?> next = ((IWrapModel<?>)nested).getWrappedModel();
if (nested == next)
{
throw new WicketRuntimeException("Model for " + nested + " is self-referential");
}
nested = next;
}
return nested;
}
/**
* Gets the component's current model comparator. Implementations can be used for testing the
* current value of the components model data with the new value that is given.
*
* @return the value defaultModelComparator
*/
public IModelComparator getModelComparator()
{
return defaultModelComparator;
}
/**
* Returns whether the component can be stateless. Also the component behaviors must be
* stateless, otherwise the component will be treat as stateful. In order for page to be
* stateless (and not to be stored in session), all components (and component behaviors) must be
* stateless.
*
* @return whether the component can be stateless
*/
protected boolean getStatelessHint()
{
return true;
}
/**
* Called when a null model is about to be retrieved in order to allow a subclass to provide an
* initial model. This gives FormComponent, for example, an opportunity to instantiate a model
* on the fly using the containing Form's model.
*
* @return The model
*/
protected IModel<?> initModel()
{
IModel<?> foundModel = null;
// Search parents for CompoundPropertyModel
for (Component current = getParent(); current != null; current = current.getParent())
{
// Get model
// Don't call the getModel() that could initialize many inbetween
// completely useless models.
// IModel model = current.getModel();
IModel<?> model = current.getModelImpl();
if (model instanceof IWrapModel && !(model instanceof IComponentInheritedModel))
{
model = ((IWrapModel<?>)model).getWrappedModel();
}
if (model instanceof IComponentInheritedModel)
{
// return the shared inherited
foundModel = ((IComponentInheritedModel<?>)model).wrapOnInheritance(this);
setFlag(FLAG_INHERITABLE_MODEL, true);
break;
}
}
// No model for this component!
return foundModel;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE.
*
* <p>
* Called anytime a model is changed via setModel or setModelObject.
* </p>
*/
protected void internalOnModelChanged()
{
}
/**
* Components are allowed to reject behavior modifiers.
*
* @param behavior
* @return False, if the component should not apply this behavior
*/
protected boolean isBehaviorAccepted(final Behavior behavior)
{
// Ignore AttributeModifiers when FLAG_IGNORE_ATTRIBUTE_MODIFIER is set
if ((behavior instanceof AttributeModifier) &&
(getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER) != false))
{
return false;
}
return behavior.isEnabled(this);
}
/**
* If true, all attribute modifiers will be ignored
*
* @return True, if attribute modifiers are to be ignored
*/
protected final boolean isIgnoreAttributeModifier()
{
return getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER);
}
/**
* @return Component's markup stream
*/
protected MarkupStream locateMarkupStream()
{
return new MarkupStream(getMarkup());
}
/**
* Called just after a component is rendered.
*/
protected void onAfterRender()
{
setFlag(FLAG_AFTER_RENDERING, false);
}
/**
* Called just before a component is rendered.
* <p>
* <strong>NOTE</strong>: If you override this, you *must* call super.onBeforeRender() within
* your implementation.
*
* Because this method is responsible for cascading {@link #onBeforeRender()} call to its
* children it is strongly recommended that super call is made at the end of the override.
* </p>
*
* @see Component#callOnBeforeRenderIfNotVisible()
*/
protected void onBeforeRender()
{
setFlag(FLAG_PREPARED_FOR_RENDER, true);
onBeforeRenderChildren();
setRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED, true);
}
/**
* Processes the component tag.
* <p/>
* Overrides of this method most likely should call the super implementation.
*
* @param tag
* Tag to modify
*/
protected void onComponentTag(final ComponentTag tag)
{
// We can't try to get the ID from markup. This could be different than
// id returned from getMarkupId() prior first rendering the component
// (due to transparent resolvers and borders which break the 1:1
// component <-> markup relation)
if (getFlag(FLAG_OUTPUT_MARKUP_ID))
{
tag.put(MARKUP_ID_ATTR_NAME, getMarkupId());
}
if (getApplication().getDebugSettings().isOutputComponentPath())
{
String path = getPageRelativePath();
path = path.replace("_", "__");
path = path.replace(":", "_");
tag.put("wicketpath", path);
}
}
/**
* Processes the body.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
}
/**
* Called to allow a component to detach resources after use.
*
* Overrides of this method MUST call the super implementation, the most logical place to do
* this is the last line of the override method.
*/
protected void onDetach()
{
setFlag(FLAG_DETACHING, false);
}
/**
* Called to notify the component it is being removed from the component hierarchy
*
* Overrides of this method MUST call the super implementation, the most logical place to do
* this is the last line of the override method.
*
*
*/
protected void onRemove()
{
setFlag(FLAG_REMOVING_FROM_HIERARCHY, false);
}
/**
* Called anytime a model is changed after the change has occurred
*/
protected void onModelChanged()
{
}
/**
* Called anytime a model is changed, but before the change actually occurs
*/
protected void onModelChanging()
{
}
/**
* Implementation that renders this component.
*/
protected abstract void onRender();
/**
* Writes a simple tag out to the response stream. Any components that might be referenced by
* the tag are ignored. Also undertakes any tag attribute modifications if they have been added
* to the component.
*
* @param tag
* The tag to write
*/
protected final void renderComponentTag(ComponentTag tag)
{
if (needToRenderTag(tag))
{
// Apply behavior modifiers
List<? extends Behavior> behaviors = getBehaviors();
if ((behaviors != null) && !behaviors.isEmpty() && !tag.isClose() &&
(isIgnoreAttributeModifier() == false))
{
tag = tag.mutable();
for (Behavior behavior : behaviors)
{
// Components may reject some behavior components
if (isBehaviorAccepted(behavior))
{
behavior.onComponentTag(this, tag);
}
}
}
// apply behaviors that are attached to the component tag.
if (tag.hasBehaviors())
{
Iterator<? extends Behavior> tagBehaviors = tag.getBehaviors();
while (tagBehaviors.hasNext())
{
final Behavior behavior = tagBehaviors.next();
if (behavior.isEnabled(this))
{
behavior.onComponentTag(this, tag);
}
behavior.detach(this);
}
}
if ((tag instanceof WicketTag) && !tag.isClose())
{
if (getFlag(FLAG_OUTPUT_MARKUP_ID))
{
log.warn(String.format(
"Markup id set on a component that is usually not rendered into markup. "
+ "Markup id: %s, component id: %s, component tag: %s.", getId(),
tag.getName()));
}
if (getFlag(FLAG_PLACEHOLDER))
{
log.warn(String.format(
"Placeholder tag set on a component that is usually not rendered into markup. "
+ "Component id: %s, component tag: %s.", getId(), tag.getName()));
}
}
// Write the tag
tag.writeOutput(getResponse(), !needToRenderTag(null),
getMarkup().getMarkupResourceStream().getWicketNamespace());
}
}
/**
* Replaces the body with the given one.
*
* @param markupStream
* The markup stream to replace the tag body in
* @param tag
* The tag
* @param body
* The new markup
*/
protected final void replaceComponentTagBody(final MarkupStream markupStream,
final ComponentTag tag, final CharSequence body)
{
// The tag might have been changed from open-close to open. Hence
// we'll need what was in the markup itself
ComponentTag markupOpenTag = null;
// If tag has a body
if (tag.isOpen())
{
// Get what tag was in the markup; not what the user it might
// have changed it to.
markupOpenTag = markupStream.getPreviousTag();
// If it was an open tag in the markup as well, than ...
if (markupOpenTag.isOpen())
{
// skip any raw markup in the body
markupStream.skipRawMarkup();
}
}
if (body != null)
{
// Write the new body
getResponse().write(body);
}
// If we had an open tag (and not an openclose tag) and we found a
// close tag, we're good
if (tag.isOpen())
{
// If it was an open tag in the markup, than there must be
// a close tag as well.
if ((markupOpenTag != null) && markupOpenTag.isOpen() && !markupStream.atCloseTag())
{
// There must be a component in this discarded body
markupStream.throwMarkupException("Expected close tag for '" + markupOpenTag +
"' Possible attempt to embed component(s) '" + markupStream.get() +
"' in the body of this component which discards its body");
}
}
}
/**
* @param auto
* True to put component into auto-add mode
*/
protected final void setAuto(final boolean auto)
{
setFlag(FLAG_AUTO, auto);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setFlag(final int flag, final boolean set)
{
if (set)
{
flags |= flag;
}
else
{
flags &= ~flag;
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setRequestFlag(final short flag, final boolean set)
{
if (set)
{
requestFlags |= flag;
}
else
{
requestFlags &= ~flag;
}
}
/**
* If true, all attribute modifiers will be ignored
*
* @param ignore
* If true, all attribute modifiers will be ignored
* @return This
*/
protected final Component setIgnoreAttributeModifier(final boolean ignore)
{
setFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER, ignore);
return this;
}
/**
* @param <V>
* The model type
* @param model
* The model to wrap if need be
* @return The wrapped model
*/
protected final <V> IModel<V> wrap(final IModel<V> model)
{
if (model instanceof IComponentAssignedModel)
{
return ((IComponentAssignedModel<V>)model).wrapOnAssignment(this);
}
return model;
}
/**
* Detaches any child components
*/
void detachChildren()
{
}
/**
* Signals this components removal from hierarchy to all its children.
*/
void removeChildren()
{
}
/**
* Gets the component at the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
public Component get(final String path)
{
// Path to this component is an empty path
if (path.equals(""))
{
return this;
}
throw new IllegalArgumentException(
exceptionMessage("Component is not a container and so does " + "not contain the path " +
path));
}
/**
* Checks whether or not this component has a markup id value generated, whether it is automatic
* or user defined
*
* @return true if this component has a markup id value generated
*/
final boolean hasMarkupIdMetaData()
{
return getMarkupId() != null;
}
/**
* @param setRenderingFlag
* rendering flag
*/
void internalMarkRendering(boolean setRenderingFlag)
{
if (setRenderingFlag)
{
setFlag(FLAG_PREPARED_FOR_RENDER, false);
setFlag(FLAG_RENDERING, true);
}
}
/**
* @return True if this component or any of its parents is in auto-add mode
*/
public final boolean isAuto()
{
// Search up hierarchy for FLAG_AUTO
for (Component current = this; current != null; current = current.getParent())
{
if (current.getFlag(FLAG_AUTO))
{
return true;
}
}
return false;
}
/**
*
* @return <code>true</code> if component has been prepared for render
*/
boolean isPreparedForRender()
{
return getFlag(FLAG_PREPARED_FOR_RENDER);
}
/**
*
*/
void onAfterRenderChildren()
{
}
/**
* This method is here for {@link MarkupContainer}. It is broken out of
* {@link #onBeforeRender()} so we can guarantee that it executes as the last in
* onBeforeRender() chain no matter where user places the <code>super.onBeforeRender()</code>
* call.
*/
void onBeforeRenderChildren()
{
}
/**
* Renders the close tag at the current position in the markup stream.
*
* @param markupStream
* the markup stream
* @param openTag
* the tag to render
* @param renderBodyOnly
* if true, the tag will not be written to the output
*/
final void renderClosingComponentTag(final MarkupStream markupStream,
final ComponentTag openTag, final boolean renderBodyOnly)
{
// Tag should be open tag and not openclose tag
if (openTag.isOpen())
{
// If we found a close tag and it closes the open tag, we're good
if (markupStream.atCloseTag() && markupStream.getTag().closes(openTag))
{
// Render the close tag
if (renderBodyOnly == false)
{
// Get the close tag from the stream
ComponentTag closeTag = markupStream.getTag();
// If the open tag had its id changed
if (openTag.getNameChanged())
{
// change the id of the close tag
closeTag = closeTag.mutable();
closeTag.setName(openTag.getName());
closeTag.setNamespace(openTag.getNamespace());
}
renderComponentTag(closeTag);
}
}
else if (openTag.requiresCloseTag())
{
// Missing close tag. Some tags, e.g. <p> are handled like <p/> by most browsers and
// thus will not throw an exception.
markupStream.throwMarkupException("Expected close tag for " + openTag);
}
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Sets the id of this component.
*
* @param id
* The non-null id of this component
*/
final void setId(final String id)
{
if (!(this instanceof Page))
{
if (Strings.isEmpty(id))
{
throw new WicketRuntimeException("Null or empty component ID's are not allowed.");
}
}
if ((id != null) && (id.indexOf(':') != -1))
{
throw new WicketRuntimeException("The component ID must not contain ':' chars.");
}
this.id = id;
}
/**
* THIS IS A WICKET INTERNAL API. DO NOT USE IT.
*
* Sets the parent of a component. Typically what you really want is parent.add(child).
* <p/>
* Note that calling setParent() and not parent.add() will connect the child to the parent, but
* the parent will not know the child. This might not be a problem in some cases, but e.g.
* child.onDetach() will not be invoked (since the parent doesn't know it is his child).
*
* @param parent
* The parent container
*/
public final void setParent(final MarkupContainer parent)
{
if (this.parent != null && log.isDebugEnabled())
{
log.debug("Replacing parent " + this.parent + " with " + parent);
}
this.parent = parent;
}
/**
* Sets the render allowed flag.
*
* @param renderAllowed
*/
final void setRenderAllowed(boolean renderAllowed)
{
setFlag(FLAG_IS_RENDER_ALLOWED, renderAllowed);
}
/**
* Sets the render allowed flag.
*
* Visit all this page's children (overridden in MarkupContainer) to check rendering
* authorization, as appropriate. We set any result; positive or negative as a temporary boolean
* in the components, and when a authorization exception is thrown it will block the rendering
* of this page
*/
void setRenderAllowed()
{
setRenderAllowed(isActionAuthorized(RENDER));
}
/**
* Sets whether or not this component is allowed to be visible. This method is meant to be used
* by components to control visibility of other components. A call to
* {@link #setVisible(boolean)} will not always have a desired effect because that component may
* have {@link #isVisible()} overridden. Both {@link #setVisibilityAllowed(boolean)} and
* {@link #isVisibilityAllowed()} are <code>final</code> so their contract is enforced always.
*
* @param allowed
* @return <code>this</code> for chaining
*/
public final Component setVisibilityAllowed(boolean allowed)
{
setFlag(FLAG_VISIBILITY_ALLOWED, allowed);
return this;
}
/**
* Gets whether or not visibility is allowed on this component. See
* {@link #setVisibilityAllowed(boolean)} for details.
*
* @return true if this component is allowed to be visible, false otherwise.
*/
public final boolean isVisibilityAllowed()
{
return getFlag(FLAG_VISIBILITY_ALLOWED);
}
/**
* Determines whether or not a component should be visible, taking into account all the factors:
* {@link #isVisible()}, {@link #isVisibilityAllowed()}, {@link #isRenderAllowed()}
*
* @return <code>true</code> if the component should be visible, <code>false</code> otherwise
*/
public final boolean determineVisibility()
{
return isVisible() && isRenderAllowed() && isVisibilityAllowed();
}
/**
* Calculates enabled state of the component taking its hierarchy into account. A component is
* enabled iff it is itself enabled ({@link #isEnabled()} and {@link #isEnableAllowed()} both
* return <code>true</code>), and all of its parents are enabled.
*
* @return <code>true</code> if this component is enabled</code>
*/
public final boolean isEnabledInHierarchy()
{
if (getRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET))
{
return getRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_VALUE);
}
final boolean state;
Component parent = getParent();
if (parent != null && !parent.isEnabledInHierarchy())
{
state = false;
}
else
{
state = isEnabled() && isEnableAllowed();
}
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET, true);
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_VALUE, state);
return state;
}
/** TODO WICKET-NG javadoc */
public final boolean canCallListenerInterface()
{
return isEnabledInHierarchy() && isVisibleInHierarchy();
}
/** {@inheritDoc} */
public void renderHead(IHeaderResponse response)
{
// noop
}
/** {@inheritDoc} */
public void onEvent(IEvent<?> event)
{
}
/** {@inheritDoc} */
public final void send(IEventSink sink, Broadcast type, Object payload)
{
new ComponentEventSender(this).send(sink, type, payload);
}
/**
* Removes behavior from component
*
* @param behaviors
* behaviors to remove
*
* @return this (to allow method call chaining)
*/
public Component remove(final Behavior... behaviors)
{
Behaviors helper = new Behaviors(this);
for (Behavior behavior : behaviors)
{
helper.remove(behavior);
}
return this;
}
/** {@inheritDoc} */
public final Behavior getBehaviorById(int id)
{
return new Behaviors(this).getBehaviorById(id);
}
/** {@inheritDoc} */
public final int getBehaviorId(Behavior behavior)
{
return new Behaviors(this).getBehaviorId(behavior);
}
/**
* Adds a behavior modifier to the component.
*
* <p>
* Note: this method is override to enable users to do things like discussed in <a
* href="http://www.nabble.com/Why-add%28IBehavior%29-is-final--tf2598263.html#a7248198">this
* thread</a>.
* </p>
*
* @param behaviors
* The behavior modifier(s) to be added
* @return this (to allow method call chaining)
*/
public Component add(final Behavior... behaviors)
{
new Behaviors(this).add(behaviors);
return this;
}
/**
* Gets the currently coupled {@link Behavior}s as a unmodifiable list. Returns an empty list
* rather than null if there are no behaviors coupled to this component.
*
* @return The currently coupled behaviors as a unmodifiable list
*/
public final List<? extends Behavior> getBehaviors()
{
return getBehaviors(Behavior.class);
}
}
|
wicket/src/main/java/org/apache/wicket/Component.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.AuthorizationException;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.authorization.UnauthorizedActionException;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.event.IEventSink;
import org.apache.wicket.event.IEventSource;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.IMarkupFragment;
import org.apache.wicket.markup.MarkupElement;
import org.apache.wicket.markup.MarkupException;
import org.apache.wicket.markup.MarkupNotFoundException;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.WicketTag;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.model.IComponentAssignedModel;
import org.apache.wicket.model.IComponentInheritedModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.IModelComparator;
import org.apache.wicket.model.IWrapModel;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.component.IRequestableComponent;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.handler.BookmarkableListenerInterfaceRequestHandler;
import org.apache.wicket.request.handler.ListenerInterfaceRequestHandler;
import org.apache.wicket.request.handler.PageAndComponentProvider;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.settings.IDebugSettings;
import org.apache.wicket.util.IHierarchical;
import org.apache.wicket.util.convert.IConverter;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Classes;
import org.apache.wicket.util.lang.WicketObjects;
import org.apache.wicket.util.string.ComponentStrings;
import org.apache.wicket.util.string.PrependingStringBuffer;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.apache.wicket.util.visit.Visit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Component serves as the highest level abstract base class for all components.
*
* <ul>
* <li><b>Identity </b>- All Components must have a non-null id which is retrieved by calling
* getId(). The id must be unique within the MarkupContainer that holds the Component, but does not
* have to be globally unique or unique within a Page's component hierarchy.
*
* <li><b>Hierarchy </b>- A component has a parent which can be retrieved with {@link #getParent()}.
* If a component is an instance of MarkupContainer, it may have children. In this way it has a
* place in the hierarchy of components contained on a given page.
*
* <li><b>Component Paths </b>- The path from the Page at the root of the component hierarchy to a
* given Component is simply the concatenation with dot separators of each id along the way. For
* example, the path "a.b.c" would refer to the component named "c" inside the MarkupContainer named
* "b" inside the container named "a". The path to a component can be retrieved by calling
* getPath(). This path is an absolute path beginning with the id of the Page at the root. Pages
* bear a PageMap/Session-relative identifier as their id, so each absolute path will begin with a
* number, such as "0.a.b.c". To get a Component path relative to the page that contains it, you can
* call getPageRelativePath().
*
* <li><b>LifeCycle </b>- Components participate in the following lifecycle phases:
* <ul>
* <li><b>Construction </b>- A Component is constructed with the Java language new operator.
* Children may be added during construction if the Component is a MarkupContainer.
*
* <li><b>Request Handling </b>- An incoming request is processed by a protocol request handler such
* as WicketServlet. An associated Application object creates Session, Request and Response objects
* for use by a given Component in updating its model and rendering a response. These objects are
* stored inside a container called {@link RequestCycle} which is accessible via
* {@link Component#getRequestCycle()}. The convenience methods {@link Component#getRequest()},
* {@link Component#getResponse()} and {@link Component#getSession()} provide easy access to the
* contents of this container.
*
* <li><b>Listener Invocation </b>- If the request references a listener on an existing Component,
* that listener is called, allowing arbitrary user code to handle events such as link clicks or
* form submits. Although arbitrary listeners are supported in Wicket, the need to implement a new
* class of listener is unlikely for a web application and even the need to implement a listener
* interface directly is highly discouraged. Instead, calls to listeners are routed through logic
* specific to the event, resulting in calls to user code through other overridable methods. For
* example, the {@link org.apache.wicket.markup.html.form.IFormSubmitListener#onFormSubmitted()}
* method implemented by the Form class is really a private implementation detail of the Form class
* that is not designed to be overridden (although unfortunately, it must be public since all
* interface methods in Java must be public). Instead, Form subclasses should override user-oriented
* methods such as onValidate(), onSubmit() and onError() (although only the latter two are likely
* to be overridden in practice).
*
* <li><b>Form Submit </b>- If a Form has been submitted and the Component is a FormComponent, the
* component's model is validated by a call to FormComponent.validate().
*
* <li><b>Form Model Update </b>- If a valid Form has been submitted and the Component is a
* FormComponent, the component's model is updated by a call to FormComponent.updateModel().
*
* <li><b>Rendering </b>- A markup response is generated by the Component via
* {@link Component#render()}, which calls subclass implementation code contained in
* {@link org.apache.wicket.Component#onRender()}. Once this phase begins, a Component becomes
* immutable. Attempts to alter the Component will result in a WicketRuntimeException.
*
* </ul>
*
* <li><b>Component Models </b>- The primary responsibility of a component is to use its model (an
* object that implements IModel), which can be set via
* {@link Component#setDefaultModel(IModel model)} and retrieved via
* {@link Component#getDefaultModel()}, to render a response in an appropriate markup language, such
* as HTML. In addition, form components know how to update their models based on request
* information. Since the IModel interface is a wrapper around an actual model object, a convenience
* method {@link Component#getDefaultModelObject()} is provided to retrieve the model Object from
* its IModel wrapper. A further convenience method,
* {@link Component#getDefaultModelObjectAsString()} , is provided for the very common operation of
* converting the wrapped model Object to a String.
*
* <li><b>Visibility </b>- Components which have setVisible(false) will return false from
* isVisible() and will not render a response (nor will their children).
*
* <li><b>Page </b>- The Page containing any given Component can be retrieved by calling
* {@link Component#getPage()}. If the Component is not attached to a Page, an IllegalStateException
* will be thrown. An equivalent method, {@link Component#findPage()} is available for special
* circumstances where it might be desirable to get a null reference back instead.
*
* <li><b>Session </b>- The Page for a Component points back to the Session that contains the Page.
* The Session for a component can be accessed with the convenience method getSession(), which
* simply calls getPage().getSession().
*
* <li><b>Locale </b>- The Locale for a Component is available through the convenience method
* getLocale(), which is equivalent to getSession().getLocale().
*
* <li><b>String Resources </b>- Components can have associated String resources via the
* Application's Localizer, which is available through the method {@link Component#getLocalizer()}.
* The convenience methods {@link Component#getString(String key)} and
* {@link Component#getString(String key, IModel model)} wrap the identical methods on the
* Application Localizer for easy access in Components.
*
* <li><b>Style </b>- The style ("skin") for a component is available through
* {@link org.apache.wicket.Component#getStyle()}, which is equivalent to getSession().getStyle().
* Styles are intended to give a particular look to a Component or Resource that is independent of
* its Locale. For example, a style might be a set of resources, including images and markup files,
* which gives the design look of "ocean" to the user. If the Session's style is set to "ocean" and
* these resources are given names suffixed with "_ocean", Wicket's resource management logic will
* prefer these resources to other resources, such as default resources, which are not as good of a
* match.
*
* <li><b>Variation </b>- Whereas Styles are Session (user) specific, variations are component
* specific. E.g. if the Style is "ocean" and the Variation is "NorthSea", than the resources are
* given the names suffixed with "_ocean_NorthSea".
*
* <li><b>AttributeModifiers </b>- You can add one or more {@link AttributeModifier}s to any
* component if you need to programmatically manipulate attributes of the markup tag to which a
* Component is attached.
*
* <li><b>Application, ApplicationSettings and ApplicationPages </b>- The getApplication() method
* provides convenient access to the Application for a Component via getSession().getApplication().
* The getApplicationSettings() method is equivalent to getApplication().getSettings(). The
* getApplicationPages is equivalent to getApplication().getPages().
*
* <li><b>Feedback Messages </b>- The {@link Component#debug(String)},
* {@link Component#info(String)}, {@link Component#warn(String)},
* {@link Component#error(java.io.Serializable)} and {@link Component#fatal(String)} methods
* associate feedback messages with a Component. It is generally not necessary to use these methods
* directly since Wicket validators automatically register feedback messages on Components. Any
* feedback message for a given Component can be retrieved with {@link Component#getFeedbackMessage}.
*
* <li><b>Versioning </b>- Pages are the unit of versioning in Wicket, but fine-grained control of
* which Components should participate in versioning is possible via the
* {@link Component#setVersioned(boolean)} method. The versioning participation of a given Component
* can be retrieved with {@link Component#isVersioned()}.
*
* <li><b>AJAX support</b>- Components can be re-rendered after the whole Page has been rendered at
* least once by calling doRender().
*
* @author Jonathan Locke
* @author Chris Turner
* @author Eelco Hillenius
* @author Johan Compagner
* @author Juergen Donnerstag
* @author Igor Vaynberg (ivaynberg)
*/
public abstract class Component
implements
IClusterable,
IConverterLocator,
IRequestableComponent,
IHeaderContributor,
IHierarchical<Component>,
IEventSink,
IEventSource
{
/** Log. */
private static final Logger log = LoggerFactory.getLogger(Component.class);
private static final long serialVersionUID = 1L;
/**
* Action used with IAuthorizationStrategy to determine whether a component is allowed to be
* enabled.
* <p>
* If enabling is authorized, a component may decide by itself (typically using it's enabled
* property) whether it is enabled or not. If enabling is not authorized, the given component is
* marked disabled, regardless its enabled property.
* <p>
* When a component is not allowed to be enabled (in effect disabled through the implementation
* of this interface), Wicket will try to prevent model updates too. This is not completely fail
* safe, as constructs like:
*
* <pre>
*
* User u = (User)getModelObject();
* u.setName("got you there!");
*
* </pre>
*
* can't be prevented. Indeed it can be argued that any model protection is best dealt with in
* your model objects to be completely secured. Wicket will catch all normal framework-directed
* use though.
*/
public static final Action ENABLE = new Action(Action.ENABLE);
/** Separator for component paths */
public static final char PATH_SEPARATOR = ':';
/**
* Action used with IAuthorizationStrategy to determine whether a component and its children are
* allowed to be rendered.
* <p>
* There are two uses for this method:
* <ul>
* <li>The 'normal' use is for controlling whether a component is rendered without having any
* effect on the rest of the processing. If a strategy lets this method return 'false', then the
* target component and its children will not be rendered, in the same fashion as if that
* component had visibility property 'false'.</li>
* <li>The other use is when a component should block the rendering of the whole page. So
* instead of 'hiding' a component, what we generally want to achieve here is that we force the
* user to logon/give-credentials for a higher level of authorization. For this functionality,
* the strategy implementation should throw a {@link AuthorizationException}, which will then be
* handled further by the framework.</li>
* </ul>
* </p>
*/
public static final Action RENDER = new Action(Action.RENDER);
/** meta data for user specified markup id */
private static final MetaDataKey<String> MARKUP_ID_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/** Basic model IModelComparator implementation for normal object models */
private static final IModelComparator defaultModelComparator = new IModelComparator()
{
private static final long serialVersionUID = 1L;
public boolean compare(Component component, Object b)
{
final Object a = component.getDefaultModelObject();
if (a == null && b == null)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.equals(b);
}
};
/** an unused flag */
private static final int FLAG_UNUSED0 = 0x20000000;
private static final int FLAG_UNUSED1 = 0x800000;
private static final int FLAG_UNUSED2 = 0x1000000;
private static final int FLAG_UNUSED3 = 0x10000000;
/** True when a component is being auto-added */
private static final int FLAG_AUTO = 0x0001;
/** Flag for escaping HTML in model strings */
private static final int FLAG_ESCAPE_MODEL_STRINGS = 0x0002;
/** Boolean whether this component's model is inheritable. */
static final int FLAG_INHERITABLE_MODEL = 0x0004;
/** Versioning boolean */
private static final int FLAG_VERSIONED = 0x0008;
/** Visibility boolean */
private static final int FLAG_VISIBLE = 0x0010;
/** Render tag boolean */
private static final int FLAG_RENDER_BODY_ONLY = 0x0020;
/** Ignore attribute modifiers */
private static final int FLAG_IGNORE_ATTRIBUTE_MODIFIER = 0x0040;
/** True when a component is enabled for model updates and is reachable. */
private static final int FLAG_ENABLED = 0x0080;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED1 = 0x0100;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED2 = 0x0200;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED3 = 0x0400;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED4 = 0x0800;
/** Boolean whether this component was rendered at least once for tracking changes. */
private static final int FLAG_HAS_BEEN_RENDERED = 0x1000;
/**
* Internal indicator of whether this component may be rendered given the current context's
* authorization. It overrides the visible flag in case this is false. Authorization is done
* before trying to render any component (otherwise we would end up with a half rendered page in
* the buffer)
*/
private static final int FLAG_IS_RENDER_ALLOWED = 0x2000;
/** Whether or not the component should print out its markup id into the id attribute */
private static final int FLAG_OUTPUT_MARKUP_ID = 0x4000;
/**
* Output a placeholder tag if the component is not visible. This is useful in ajax mode to go
* to visible(false) to visible(true) without the overhead of repainting a visible parent
* container
*/
private static final int FLAG_PLACEHOLDER = 0x8000;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED5 = 0x10000;
/** onInitialize called */
protected static final int FLAG_INITIALIZED = 0x20000;
/** Reserved subclass-definable flag bit */
private static final int FLAG_NOTUSED7 = 0x40000;
/** Reserved subclass-definable flag bit */
protected static final int FLAG_RESERVED8 = 0x80000;
/**
* Flag that determines whether the model is set. This is necessary because of the way we
* represent component state ({@link #data}). We can't distinguish between model and behavior
* using instanceof, because one object can implement both interfaces. Thus we need this flag -
* when the flag is set, first object in {@link #data} is always model.
*/
private static final int FLAG_MODEL_SET = 0x100000;
/** True when a component is being removed from the hierarchy */
protected static final int FLAG_REMOVING_FROM_HIERARCHY = 0x200000;
/**
* Flag that makes we are in before-render callback phase Set after component.onBeforeRender is
* invoked (right before invoking beforeRender on children)
*/
private static final int FLAG_RENDERING = 0x2000000;
private static final int FLAG_PREPARED_FOR_RENDER = 0x4000000;
private static final int FLAG_AFTER_RENDERING = 0x8000000;
private static final int FLAG_MARKUP_ATTACHED = 0x10000000;
/**
* Flag that restricts visibility of a component when set to true. This is usually used when a
* component wants to restrict visibility of another component. Calling
* {@link #setVisible(boolean)} on a component does not always have the desired effect because
* isVisible() can be overwritten thus this flag offers an alternative that should always work.
*/
private static final int FLAG_VISIBILITY_ALLOWED = 0x40000000;
private static final int FLAG_DETACHING = 0x80000000;
/**
* The name of attribute that will hold markup id
*/
private static final String MARKUP_ID_ATTR_NAME = "id";
/**
* Meta data key for line precise error logging for the moment of addition. Made package private
* for access in {@link MarkupContainer} and {@link Page}
*/
static final MetaDataKey<String> ADDED_AT_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/**
* meta data key for line precise error logging for the moment of construction. Made package
* private for access in {@link Page}
*/
static final MetaDataKey<String> CONSTRUCTED_AT_KEY = new MetaDataKey<String>()
{
private static final long serialVersionUID = 1L;
};
/** Component flags. See FLAG_* for possible non-exclusive flag values. */
private int flags = FLAG_VISIBLE | FLAG_ESCAPE_MODEL_STRINGS | FLAG_VERSIONED | FLAG_ENABLED |
FLAG_IS_RENDER_ALLOWED | FLAG_VISIBILITY_ALLOWED;
private static final short RFLAG_ENABLED_IN_HIERARCHY_VALUE = 0x1;
private static final short RFLAG_ENABLED_IN_HIERARCHY_SET = 0x2;
private static final short RFLAG_VISIBLE_IN_HIEARARCHY_VALUE = 0x4;
private static final short RFLAG_VISIBLE_IN_HIERARCHY_SET = 0x8;
/** onconfigure has been called */
private static final short RFLAG_CONFIGURED = 0x10;
private static final short RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED = 0x20;
private static final short RFLAG_INITIALIZE_SUPER_CALL_VERIFIED = 0x40;
/**
* Flags that only keep their value during the request. Useful for cache markers, etc. At the
* end of the request the value of this variable is reset to 0
*/
private transient short requestFlags = 0;
/** Component id. */
private String id;
/** Any parent container. */
private MarkupContainer parent;
/**
* Instead of remembering the whole markupId, we just remember the number for this component so
* we can "reconstruct" the markupId on demand. While this could be part of {@link #data},
* profiling showed that having it as separate property consumes less memory.
*/
int generatedMarkupId = -1;
/** Must only be used by auto components */
private transient IMarkupFragment markup;
/**
* The object that holds the component state.
* <p>
* What's stored here depends on what attributes are set on component. Data can contains
* combination of following attributes:
* <ul>
* <li>Model (indicated by {@link #FLAG_MODEL_SET})
* <li>MetaDataEntry (optionally {@link MetaDataEntry}[] if more metadata entries are present) *
* <li>{@link Behavior}(s) added to component. The behaviors are not stored in separate array,
* they are part of the {@link #data} array (this is in order to save the space of the pointer
* to an empty array as most components have no behaviours). - FIXME - explain why - is this
* correct?
* </ul>
* If there is only one attribute set (i.e. model or MetaDataEntry([]) or one behavior), the
* #data object points directly to value of that attribute. Otherwise the data is of type
* Object[] where the attributes are ordered as specified above.
* <p>
*/
Object data = null;
final int data_start()
{
return getFlag(FLAG_MODEL_SET) ? 1 : 0;
}
final int data_length()
{
if (data == null)
{
return 0;
}
else if (data instanceof Object[] && !(data instanceof MetaDataEntry<?>[]))
{
return ((Object[])data).length;
}
else
{
return 1;
}
}
final Object data_get(int index)
{
if (data == null)
{
return null;
}
else if (data instanceof Object[] && !(data instanceof MetaDataEntry<?>[]))
{
Object[] array = (Object[])data;
return index < array.length ? array[index] : null;
}
else if (index == 0)
{
return data;
}
else
{
return null;
}
}
final Object data_set(int index, Object object)
{
if (index > data_length() - 1)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0 && !(data instanceof Object[] && !(data instanceof MetaDataEntry<?>[])))
{
Object old = data;
data = object;
return old;
}
else
{
Object[] array = (Object[])data;
Object old = array[index];
array[index] = object;
return old;
}
}
final void data_add(Object object)
{
data_insert(-1, object);
}
final void data_insert(int position, Object object)
{
int currentLength = data_length();
if (position == -1)
{
position = currentLength;
}
if (position > currentLength)
{
throw new IndexOutOfBoundsException();
}
if (currentLength == 0)
{
data = object;
}
else if (currentLength == 1)
{
Object[] array = new Object[2];
if (position == 0)
{
array[0] = object;
array[1] = data;
}
else
{
array[0] = data;
array[1] = object;
}
data = array;
}
else
{
Object[] array = new Object[currentLength + 1];
Object[] current = (Object[])data;
int after = currentLength - position;
if (position > 0)
{
System.arraycopy(current, 0, array, 0, position);
}
array[position] = object;
if (after > 0)
{
System.arraycopy(current, position, array, position + 1, after);
}
data = array;
}
}
Object data_remove(int position)
{
int currentLength = data_length();
if (position > currentLength - 1)
{
throw new IndexOutOfBoundsException();
}
else if (currentLength == 1)
{
Object old = data;
data = null;
return old;
}
else if (currentLength == 2)
{
Object[] current = (Object[])data;
if (position == 0)
{
data = current[1];
return current[0];
}
else
{
data = current[0];
return current[1];
}
}
else
{
Object[] current = (Object[])data;
data = new Object[currentLength - 1];
if (position > 0)
{
System.arraycopy(current, 0, data, 0, position);
}
if (position != currentLength - 1)
{
final int left = currentLength - position - 1;
System.arraycopy(current, position + 1, data, position, left);
}
return current[position];
}
}
/**
* Constructor. All components have names. A component's id cannot be null. This is the minimal
* constructor of component. It does not register a model.
*
* @param id
* The non-null id of this component
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id)
{
this(id, null);
}
/**
* Constructor. All components have names. A component's id cannot be null. This constructor
* includes a model.
*
* @param id
* The non-null id of this component
* @param model
* The component's model
*
* @throws WicketRuntimeException
* Thrown if the component has been given a null id.
*/
public Component(final String id, final IModel<?> model)
{
setId(id);
getApplication().getComponentInstantiationListeners().onInstantiation(this);
final IDebugSettings debugSettings = Application.get().getDebugSettings();
if (debugSettings.isLinePreciseReportingOnNewComponentEnabled())
{
setMetaData(CONSTRUCTED_AT_KEY,
ComponentStrings.toString(this, new MarkupException("constructed")));
}
if (model != null)
{
setModelImpl(wrap(model));
}
}
/**
* Get the Markup associated with the Component. If not subclassed, the parent container is
* asked to return the markup of this child component.
* <p/>
* Components like Panel and Border should return the "calling" markup fragment, e.g.
* <code><span wicket:id="myPanel">body</span></code>. You may use
* Panel/Border/Enclosure.getMarkup(null) to return the associated markup file. And
* Panel/Border/Enclosure.getMarkup(child) will search the child in the appropriate markup
* fragment.
*
* @see MarkupContainer#getMarkup(Component)
*
* @return The markup fragment
*/
public IMarkupFragment getMarkup()
{
if (markup != null)
{
return markup;
}
if (parent == null)
{
throw new MarkupException(
"Can not determine Markup. Component is not yet connected to a parent. " +
toString());
}
markup = parent.getMarkup(this);
return markup;
}
/**
* Called when the component gets added to a parent
*
* @return false, if it was called the first time
*/
final boolean internalOnMarkupAttached()
{
boolean rtn = getFlag(FLAG_MARKUP_ATTACHED);
if (rtn == false)
{
setFlag(FLAG_MARKUP_ATTACHED, true);
onMarkupAttached();
}
return rtn;
}
/**
* Can be subclassed by any user to implement init-like logic which requires the markup to be
* available
*/
protected void onMarkupAttached()
{
if (log.isDebugEnabled())
{
log.debug("Markup available " + toString());
}
// move the component to its real parent if necessary
// moveComponentToItsRealParent();
}
/**
* Move the component to its real parent if necessary
*
* @return true, if it has been moved
*/
private boolean moveComponentToItsRealParent()
{
MarkupContainer parent = getParent();
IMarkupFragment markup = getMarkup();
if ((parent != null) && (markup != null))
{
IMarkupFragment parentMarkup = parent.getMarkup(null);
if ((parentMarkup != null) && (markup != parentMarkup))
{
// The component's markup must be in the same file as its parent
if (markup.getMarkupResourceStream() == parentMarkup.getMarkupResourceStream())
{
MarkupStream stream = new MarkupStream(markup);
stream.skipUntil(ComponentTag.class);
ComponentTag openTag = stream.getTag();
if (openTag != null)
{
MarkupStream parentStream = new MarkupStream(parentMarkup);
if (parentStream.skipUntil(ComponentTag.class))
{
parentStream.next();
}
Stack<ComponentTag> stack = new Stack<ComponentTag>();
while (parentStream.skipUntil(ComponentTag.class))
{
ComponentTag tag = parentStream.getTag();
if (openTag == tag)
{
if (stack.isEmpty() == false)
{
// This tag belong to the real parent
final ComponentTag lastTag = stack.pop();
parent.visitChildren(MarkupContainer.class,
new IVisitor<MarkupContainer, Void>()
{
public void component(final MarkupContainer component,
final IVisit<Void> visit)
{
IMarkupFragment m = component.getMarkup();
MarkupStream ms = new MarkupStream(m);
ms.skipUntil(ComponentTag.class);
if (ms.hasMore() && (lastTag == ms.getTag()))
{
component.add(Component.this);
visit.stop();
return;
}
}
});
}
return false;
}
if (tag.isOpen())
{
if (tag.hasNoCloseTag() == false)
{
stack.push(tag);
}
}
else if (tag.isOpenClose())
{
// noop
}
else if (tag.isClose())
{
if (stack.isEmpty() == false)
{
stack.pop();
}
}
parentStream.next();
}
}
}
}
}
return false;
}
/**
* @return The 'id' attribute from the associated markup tag
*/
public final String getMarkupIdFromMarkup()
{
ComponentTag tag = getMarkupTag();
if (tag != null)
{
String id = tag.getAttribute("id");
if (Strings.isEmpty(id) == false)
{
return id.trim();
}
}
return null;
}
/**
* Set the markup for the component. Note that the component's markup variable is transient and
* thus must only be used for one render cycle. E.g. auto-component are using it. You may also
* it if you subclassed getMarkup().
*
* @param markup
*/
public final void setMarkup(final IMarkupFragment markup)
{
this.markup = markup;
}
/**
* Called once per request on components before they are about to be rendered. This method
* should be used to configure such things as visibility and enabled flags.
* <p>
* Overrides must call {@code super.onConfigure()}, usually before any other code
* </p>
* <p>
* NOTE: Component hierarchy should not be modified inside this method, instead it should be
* done in {@link #onBeforeRender()}
* </p>
* <p>
* NOTE: Why this method is preferrable to directly overriding {@link #isVisible()} and
* {@link #isEnabled()}? Because those methods are called multiple times even for processing of
* a single request. If they contain expensive logic they can slow down the response time of the
* entire page. Further, overriding those methods directly on form components may lead to
* inconsistent or unexpected state depending on when those methods are called in the form
* processing workflow. It is a better practice to push changes to state rather than pull.
* </p>
* <p>
* NOTE: If component's visibility or another property depends on another component you may call
* {@code other.configure()} followed by {@code other.isVisible()} as mentioned in
* {@link #configure()} javadoc.
* </p>
* <p>
* NOTE: Why should {@link #onBeforeRender()} not be used for this? Because if visibility of a
* component is toggled inside {@link #onBeforeRender()} another method needs to be overridden
* to make sure {@link #onBeforeRender()} will be invoked on invisible components:
*
* <pre>
* class MyComponent extends WebComponent
* {
* protected void onBeforeRender()
* {
* setVisible(Math.rand() > 0.5f);
* super.onBeforeRender();
* }
*
* // if this override is forgotten, once invisible component will never become visible
* protected boolean callOnBeforeRenderIfNotVisible()
* {
* return true;
* }
* }
* </pre>
*
* VS
*
* <pre>
* class MyComponent extends WebComponent
* {
* protected void onConfigure()
* {
* setVisible(Math.rand() > 0.5f);
* super.onConfigure();
* }
* }
* </pre>
*/
protected void onConfigure()
{
}
/**
* This method is meant to be used as an alternative to initialize components. Usually the
* component's constructor is used for this task, but sometimes a component cannot be
* initialized in isolation, it may need to access its parent component or its markup in order
* to fully initialize. This method is invoked once per component's lifecycle when a path exists
* from this component to the {@link Page} thus providing the component with an atomic callback
* when the component's environment is built out.
* <p>
* Overrides must call super#{@link #onInitialize()}. Usually this should be the first thing an
* override does, much like a constructor.
* </p>
* <p>
* Parent containers are guaranteed to be initialized before their children
* </p>
*
* <p>
* It is safe to use {@link #getPage()} in this method
* </p>
*
* <p>
* NOTE:The timing of this call is not precise, the contract is that it is called sometime
* before {@link Component#onBeforeRender()}.
* </p>
*
*/
protected void onInitialize()
{
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, true);
}
/**
* Checks if the component has been initialized - {@link #onInitialize()} has been called
*
* @return {@code true} if component has been initialized
*/
final boolean isInitialized()
{
return getFlag(FLAG_INITIALIZED);
}
/**
* Used to call {@link #onInitialize()}
*/
void initialize()
{
fireInitialize();
}
/**
* Used to call {@link #onInitialize()}
*/
final void fireInitialize()
{
if (!getFlag(FLAG_INITIALIZED))
{
setFlag(FLAG_INITIALIZED, true);
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, false);
onInitialize();
if (!getRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly initialized. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onInitialize() in the override of onInitialize() method");
}
setRequestFlag(RFLAG_INITIALIZE_SUPER_CALL_VERIFIED, false);
getApplication().getComponentInitializationListeners().onInitialize(this);
}
}
/**
* Called on very component after the page is rendered. It will call onAfterRender for it self
* and its children.
*/
public final void afterRender()
{
// if the component has been previously attached via attach()
// detach it now
try
{
setFlag(FLAG_AFTER_RENDERING, true);
onAfterRender();
getApplication().getComponentOnAfterRenderListeners().onAfterRender(this);
if (getFlag(FLAG_AFTER_RENDERING))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly detached. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onAfterRender() in the override of onAfterRender() method");
}
// always detach children because components can be attached
// independently of their parents
onAfterRenderChildren();
}
finally
{
// this flag must always be set to false.
setFlag(FLAG_RENDERING, false);
}
}
/**
*
*/
private final void internalBeforeRender()
{
configure();
if ((determineVisibility()) && !getFlag(FLAG_RENDERING) &&
!getFlag(FLAG_PREPARED_FOR_RENDER))
{
setRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED, false);
getApplication().getComponentPreOnBeforeRenderListeners().onBeforeRender(this);
onBeforeRender();
getApplication().getComponentPostOnBeforeRenderListeners().onBeforeRender(this);
if (!getRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly rendered. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onBeforeRender() in the override of onBeforeRender() method");
}
}
}
/**
* We need to postpone calling beforeRender() on components that implement {@link IFeedback}, to
* be sure that all other component's beforeRender() has been already called, so that IFeedbacks
* can collect all feedback messages. This is the key under list of postponed {@link IFeedback}
* is stored to request cycle metadata. The List is then iterated over in
* {@link #prepareForRender()} after calling {@link #beforeRender()}, to initialize postponed
* components.
*/
private static final MetaDataKey<List<Component>> FEEDBACK_LIST = new MetaDataKey<List<Component>>()
{
private static final long serialVersionUID = 1L;
};
/**
* Called for every component when the page is getting to be rendered. it will call
* onBeforeRender for this component and all the child components
*/
public final void beforeRender()
{
if (!(this instanceof IFeedback))
{
internalBeforeRender();
}
else
{
// this component is a feedback. Feedback must be initialized last, so that
// they can collect messages from other components
List<Component> feedbacks = getRequestCycle().getMetaData(FEEDBACK_LIST);
if (feedbacks == null)
{
feedbacks = new ArrayList<Component>();
getRequestCycle().setMetaData(FEEDBACK_LIST, feedbacks);
}
if (this instanceof MarkupContainer)
{
((MarkupContainer)this).visitChildren(IFeedback.class,
new IVisitor<Component, Void>()
{
public void component(Component component, IVisit<Void> visit)
{
component.beforeRender();
}
});
}
if (!feedbacks.contains(this))
{
feedbacks.add(this);
}
}
}
/**
* Triggers {@link #onConfigure()} to be invoked on this component if it has not already during
* this request.
* <p>
* This method should be invoked before any calls to {@link #isVisible()} or
* {@link #isEnabled()}. Usually this method will be called by the framework before the
* component is rendered and so users should not need to call it; however, in cases where
* visibility or enabled or other state of one component depends on the state of another this
* method should be manually invoked on the other component by the user. EG to link visiliby of
* two markup containers the following should be done:
*
* <pre>
* final WebMarkupContainer source=new WebMarkupContainer("a") {
* protected void onConfigure() {
* setVisible(Math.rand()>0.5f);
* }
* };
*
* WebMarkupContainer linked=new WebMarkupContainer("b") {
* protected void onConfigure() {
* source.configure(); // make sure source is configured
* setVisible(source.isVisible());
* }
* }
* </pre>
*
* </p>
*/
public final void configure()
{
if (!getRequestFlag(RFLAG_CONFIGURED))
{
clearEnabledInHierarchyCache();
clearVisibleInHierarchyCache();
onConfigure();
setRequestFlag(RFLAG_CONFIGURED, true);
}
}
/**
* Redirects to any intercept page previously specified by a call to redirectToInterceptPage.
*
* @return True if an original destination was redirected to
* @see Component#redirectToInterceptPage(Page)
*/
public final boolean continueToOriginalDestination()
{
return RestartResponseAtInterceptPageException.continueToOriginalDestination();
}
/**
* Registers a debug feedback message for this component
*
* @param message
* The feedback message
*/
public final void debug(final Serializable message)
{
Session.get().getFeedbackMessages().debug(this, message);
Session.get().dirty();
}
/**
* Signals this Component that it is removed from the Component hierarchy.
*/
final void internalOnRemove()
{
setFlag(FLAG_REMOVING_FROM_HIERARCHY, true);
onRemove();
if (getFlag(FLAG_REMOVING_FROM_HIERARCHY))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly removed from hierachy. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onRemovalFromHierarchy() in the override of onRemovalFromHierarchy() method");
}
removeChildren();
}
/**
* Detaches the component. This is called at the end of the request for all the pages that are
* touched in that request.
*/
public final void detach()
{
// if the component has been previously attached via attach()
// detach it now
setFlag(FLAG_DETACHING, true);
onDetach();
if (getFlag(FLAG_DETACHING))
{
throw new IllegalStateException(Component.class.getName() +
" has not been properly detached. Something in the hierarchy of " +
getClass().getName() +
" has not called super.onDetach() in the override of onDetach() method");
}
// always detach models because they can be attached without the
// component. eg component has a compoundpropertymodel and one of its
// children component's getmodelobject is called
detachModels();
// detach any behaviors
new Behaviors(this).detach();
// always detach children because components can be attached
// independently of their parents
detachChildren();
// reset the model to null when the current model is a IWrapModel and
// the model that created it/wrapped in it is a IComponentInheritedModel
// The model will be created next time.
if (getFlag(FLAG_INHERITABLE_MODEL))
{
setModelImpl(null);
setFlag(FLAG_INHERITABLE_MODEL, false);
}
clearEnabledInHierarchyCache();
clearVisibleInHierarchyCache();
requestFlags = 0;
// notify any detach listener
IDetachListener detachListener = getApplication().getFrameworkSettings()
.getDetachListener();
if (detachListener != null)
{
detachListener.onDetach(this);
}
}
/**
* Detaches all models
*/
public void detachModels()
{
// Detach any detachable model from this component
detachModel();
}
/**
* Registers an error feedback message for this component
*
* @param message
* The feedback message
*/
public final void error(final Serializable message)
{
Session.get().getFeedbackMessages().error(this, message);
Session.get().dirty();
}
/**
* Registers an fatal error feedback message for this component
*
* @param message
* The feedback message
*/
public final void fatal(final Serializable message)
{
Session.get().getFeedbackMessages().fatal(this, message);
Session.get().dirty();
}
/**
* Finds the first container parent of this component of the given class.
*
* @param <Z>
* type of parent
*
*
* @param c
* MarkupContainer class to search for
* @return First container parent that is an instance of the given class, or null if none can be
* found
*/
public final <Z> Z findParent(final Class<Z> c)
{
// Start with immediate parent
MarkupContainer current = parent;
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
return c.cast(current);
}
// Check parent
current = current.getParent();
}
// Failed to find component
return null;
}
/**
* @return The nearest markup container with associated markup
*/
public final MarkupContainer findParentWithAssociatedMarkup()
{
MarkupContainer container = parent;
while (container != null)
{
if (container.hasAssociatedMarkup())
{
return container;
}
container = container.getParent();
}
// This should never happen since Page always has associated markup
throw new WicketRuntimeException("Unable to find parent with associated markup");
}
/**
* Gets interface to application that this component is a part of.
*
* @return The application associated with the session that this component is in.
* @see Application
*/
public final Application getApplication()
{
return Application.get();
}
/**
* @return A path of the form [page-class-name].[page-relative-path]
* @see Component#getPageRelativePath()
*/
public final String getClassRelativePath()
{
return getClass().getName() + PATH_SEPARATOR + getPageRelativePath();
}
/**
* Gets the converter that should be used by this component.
*
* @param type
* The type to convert to
*
* @return The converter that should be used by this component
*/
public <C> IConverter<C> getConverter(Class<C> type)
{
return getApplication().getConverterLocator().getConverter(type);
}
/**
* Gets whether model strings should be escaped.
*
* @return Returns whether model strings should be escaped
*/
public final boolean getEscapeModelStrings()
{
return getFlag(FLAG_ESCAPE_MODEL_STRINGS);
}
/**
* @return Any feedback message for this component
*/
public final FeedbackMessage getFeedbackMessage()
{
return Session.get().getFeedbackMessages().messageForComponent(this);
}
/**
* Gets the id of this component.
*
* @return The id of this component
*/
public String getId()
{
return id;
}
/**
* @return Innermost model for this component
*/
public final IModel<?> getInnermostModel()
{
return getInnermostModel(getDefaultModel());
}
/**
* Gets the locale for this component. By default, it searches its parents for a locale. If no
* parents (it's a recursive search) returns a locale, it gets one from the session.
*
* @return The locale to be used for this component
* @see Session#getLocale()
*/
public Locale getLocale()
{
if (parent != null)
{
return parent.getLocale();
}
return getSession().getLocale();
}
/**
* Convenience method to provide easy access to the localizer object within any component.
*
* @return The localizer object
*/
public final Localizer getLocalizer()
{
return getApplication().getResourceSettings().getLocalizer();
}
/**
* Get the first component tag in the associated markup
*
* @return first component tag
*/
private final ComponentTag getMarkupTag()
{
IMarkupFragment markup = getMarkup();
if (markup != null)
{
for (int i = 0; i < markup.size(); i++)
{
MarkupElement elem = markup.get(i);
if (elem instanceof ComponentTag)
{
return (ComponentTag)elem;
}
}
}
return null;
}
/**
* THIS IS WICKET INTERNAL ONLY. DO NOT USE IT.
*
* Get a copy of the markup's attributes which are associated with the component.
* <p>
* Modifications to the map returned don't change the tags attributes. It is just a copy.
* <p>
* Note: The component must have been added (directly or indirectly) to a container with an
* associated markup file (Page, Panel or Border).
*
* @return markup attributes
*/
public final ValueMap getMarkupAttributes()
{
ComponentTag tag = getMarkupTag();
if (tag != null)
{
ValueMap attrs = new ValueMap(tag.getAttributes());
attrs.makeImmutable();
return attrs;
}
return ValueMap.EMPTY_MAP;
}
/**
* Get the markupId
*
* @return MarkupId
*/
public final Object getMarkupIdImpl()
{
String id = getMarkupIdFromMarkup();
if (id != null)
{
return id;
}
if (generatedMarkupId != -1)
{
return generatedMarkupId;
}
return getMetaData(MARKUP_ID_KEY);
}
/**
* Find the Page and get net value from an auto-index
*
* @return autoIndex
*/
private final int nextAutoIndex()
{
Page page = findPage();
if (page == null)
{
throw new WicketRuntimeException(
"This component is not (yet) coupled to a page. It has to be able "
+ "to find the page it is supposed to operate in before you can call "
+ "this method (Component#getMarkupId)");
}
return page.getAutoIndex();
}
/**
* Retrieves id by which this component is represented within the markup. This is either the id
* attribute set explicitly via a call to {@link #setMarkupId(String)}, id attribute defined in
* the markup, or an automatically generated id - in that order.
* <p>
* If no id is set and <code>createIfDoesNotExist</code> is false, this method will return null.
* Otherwise it will generate an id value which by default will be unique in the page. This is
* the preferred way as there is no chance of id collision.
* <p>
*
* <p>
* Note: This method should only be called after the component or its parent have been added to
* the page.
*
* @param createIfDoesNotExist
* When there is no existing markup id, determines whether it should be generated or
* whether <code>null</code> should be returned.
*
* @return markup id of the component
*/
public String getMarkupId(boolean createIfDoesNotExist)
{
Object storedMarkupId = getMarkupIdImpl();
if (storedMarkupId instanceof String)
{
return (String)storedMarkupId;
}
if (storedMarkupId == null && createIfDoesNotExist == false)
{
return null;
}
final int generatedMarkupId = storedMarkupId instanceof Integer ? (Integer)storedMarkupId
: Session.get().nextSequenceValue();
if (storedMarkupId == null)
{
setMarkupIdImpl(generatedMarkupId);
}
String markupIdPrefix = "id";
if (!getApplication().usesDeploymentConfig())
{
// in non-deployment mode we make the markup id include component id
// so it is easier to debug
markupIdPrefix = getId();
}
String markupIdPostfix = Integer.toHexString(generatedMarkupId).toLowerCase();
String markupId = markupIdPrefix + markupIdPostfix;
// make sure id is compliant with w3c requirements (starts with a letter)
char c = markupId.charAt(0);
if (!Character.isLetter(c))
{
markupId = "id" + markupId;
}
// escape some noncompliant characters
markupId = Strings.replaceAll(markupId, "_", "__").toString();
markupId = markupId.replace('.', '_');
markupId = markupId.replace('-', '_');
markupId = markupId.replace(' ', '_');
return markupId;
}
/**
* Retrieves id by which this component is represented within the markup. This is either the id
* attribute set explicitly via a call to {@link #setMarkupId(String)}, id attribute defined in
* the markup, or an automatically generated id - in that order.
* <p>
* If no explicit id is set this function will generate an id value that will be unique in the
* page. This is the preferred way as there is no chance of id collision.
* <p>
* Note: This method should only be called after the component or its parent have been added to
* the page.
*
* @return markup id of the component
*/
public String getMarkupId()
{
return getMarkupId(true);
}
/**
* Gets metadata for this component using the given key.
*
* @param <M>
* The type of the metadata.
*
* @param key
* The key for the data
* @return The metadata or null of no metadata was found for the given key
* @see MetaDataKey
*/
public final <M extends Serializable> M getMetaData(final MetaDataKey<M> key)
{
return key.get(getMetaData());
}
/**
*
* @return meta data entry
*/
private MetaDataEntry<?>[] getMetaData()
{
MetaDataEntry<?>[] metaData = null;
// index where we should expect the entry
int index = getFlag(FLAG_MODEL_SET) ? 1 : 0;
int length = data_length();
if (index < length)
{
Object object = data_get(index);
if (object instanceof MetaDataEntry<?>[])
{
metaData = (MetaDataEntry<?>[])object;
}
else if (object instanceof MetaDataEntry)
{
metaData = new MetaDataEntry[] { (MetaDataEntry<?>)object };
}
}
return metaData;
}
/**
* Gets the model. It returns the object that wraps the backing model.
*
* @return The model
*/
public final IModel<?> getDefaultModel()
{
IModel<?> model = getModelImpl();
// If model is null
if (model == null)
{
// give subclass a chance to lazy-init model
model = initModel();
setModelImpl(model);
}
return model;
}
/**
* Gets the backing model object. Unlike getDefaultModel().getObject(), this method returns null
* for a null model.
*
* @return The backing model object
*/
public final Object getDefaultModelObject()
{
final IModel<?> model = getDefaultModel();
if (model != null)
{
try
{
// Get model value for this component.
return model.getObject();
}
catch (RuntimeException ex)
{
log.error("Error while getting default model object for Component: " +
this.toString(true));
throw ex;
}
}
return null;
}
/**
* Gets a model object as a string. Depending on the "escape model strings" flag of the
* component, the string is either HTML escaped or not. "HTML escaped" meaning that only HTML
* sensitive chars are escaped but not all none-ascii chars. Proper HTML encoding should be used
* instead. In case you really need a fully escaped model string you may call
* {@link Strings#escapeMarkup(String, boolean, boolean)} on the model string returned.
*
* @see Strings#escapeMarkup(String, boolean, boolean)
* @see #getEscapeModelStrings()
*
* @return Model object for this component as a string
*/
public final String getDefaultModelObjectAsString()
{
return getDefaultModelObjectAsString(getDefaultModelObject());
}
/**
* Gets a model object as a string. Depending on the "escape model strings" flag of the
* component, the string is either HTML escaped or not. "HTML escaped" meaning that only HTML
* sensitive chars are escaped but not all none-ascii chars. Proper HTML encoding should be used
* instead. In case you really need a fully escaped model string you may call
* {@link Strings#escapeMarkup(String, boolean, boolean)} on the model string returned.
*
* @see Strings#escapeMarkup(String, boolean, boolean)
* @see #getEscapeModelStrings()
*
* @param modelObject
* Model object to convert to string
* @return The string
*/
public final String getDefaultModelObjectAsString(final Object modelObject)
{
if (modelObject != null)
{
// Get converter
final Class<?> objectClass = modelObject.getClass();
final IConverter converter = getConverter(objectClass);
// Model string from property
final String modelString = converter.convertToString(modelObject, getLocale());
if (modelString != null)
{
// If we should escape the markup
if (getFlag(FLAG_ESCAPE_MODEL_STRINGS))
{
// Escape HTML sensitive characters only. Not all none-ascii chars
return Strings.escapeMarkup(modelString, false, false).toString();
}
return modelString;
}
}
return "";
}
/**
* Gets whether or not component will output id attribute into the markup. id attribute will be
* set to the value returned from {@link Component#getMarkupId()}.
*
* @return whether or not component will output id attribute into the markup
*/
public final boolean getOutputMarkupId()
{
return getFlag(FLAG_OUTPUT_MARKUP_ID);
}
/**
* Gets whether or not an invisible component will render a placeholder tag.
*
* @return true if a placeholder tag should be rendered
*/
public final boolean getOutputMarkupPlaceholderTag()
{
return getFlag(FLAG_PLACEHOLDER);
}
/**
* Gets the page holding this component.
*
* @return The page holding this component
* @throws IllegalStateException
* Thrown if component is not yet attached to a Page.
*/
public final Page getPage()
{
// Search for nearest Page
final Page page = findPage();
// If no Page was found
if (page == null)
{
// Give up with a nice exception
throw new WicketRuntimeException("No Page found for component " + this);
}
return page;
}
/**
* Gets the path to this component relative to the page it is in.
*
* @return The path to this component relative to the page it is in
*/
public final String getPageRelativePath()
{
return Strings.afterFirstPathComponent(getPath(), PATH_SEPARATOR);
}
/**
* Gets any parent container, or null if there is none.
*
* @return Any parent container, or null if there is none
*/
public final MarkupContainer getParent()
{
return parent;
}
/**
* Gets this component's path.
*
* @return Colon separated path to this component in the component hierarchy
*/
public final String getPath()
{
final PrependingStringBuffer buffer = new PrependingStringBuffer(32);
for (Component c = this; c != null; c = c.getParent())
{
if (buffer.length() > 0)
{
buffer.prepend(PATH_SEPARATOR);
}
buffer.prepend(c.getId());
}
return buffer.toString();
}
/**
* If false the component's tag will be printed as well as its body (which is default). If true
* only the body will be printed, but not the component's tag.
*
* @return If true, the component tag will not be printed
*/
public final boolean getRenderBodyOnly()
{
return getFlag(FLAG_RENDER_BODY_ONLY);
}
/**
* @return The request for this component's active request cycle
*/
public final Request getRequest()
{
RequestCycle requestCycle = getRequestCycle();
if (requestCycle == null)
{
// Happens often with WicketTester when one forgets to call
// createRequestCycle()
throw new WicketRuntimeException("No RequestCycle is currently set!");
}
return requestCycle.getRequest();
}
/**
* Gets the active request cycle for this component
*
* @return The request cycle
*/
public final RequestCycle getRequestCycle()
{
return RequestCycle.get();
}
/**
* @return The response for this component's active request cycle
*/
public final Response getResponse()
{
return getRequestCycle().getResponse();
}
/**
* Gets the current Session object.
*
* @return The Session that this component is in
*/
public Session getSession()
{
return Session.get();
}
/**
* @return Size of this Component in bytes
*/
public long getSizeInBytes()
{
final MarkupContainer originalParent = parent;
parent = null;
long size = -1;
try
{
size = WicketObjects.sizeof(this);
}
catch (Exception e)
{
log.error("Exception getting size for component " + this, e);
}
parent = originalParent;
return size;
}
/**
* @param key
* Key of string resource in property file
* @return The String
* @see Localizer
*/
public final String getString(final String key)
{
return getString(key, null);
}
/**
* @param key
* The resource key
* @param model
* The model
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel<?> model)
{
return getLocalizer().getString(key, this, model);
}
/**
* @param key
* The resource key
* @param model
* The model
* @param defaultValue
* A default value if the string cannot be found
* @return The formatted string
* @see Localizer
*/
public final String getString(final String key, final IModel<?> model, final String defaultValue)
{
return getLocalizer().getString(key, this, model, defaultValue);
}
/**
* A convinient method. Same as Session.get().getStyle().
*
* @return The style of this component respectively the style of the Session.
*
* @see org.apache.wicket.Session#getStyle()
*/
public final String getStyle()
{
Session session = getSession();
if (session == null)
{
throw new WicketRuntimeException("Wicket Session object not avaiable");
}
return session.getStyle();
}
/**
* Gets the variation string of this component that will be used to look up markup for this
* component. Subclasses can override this method to define by an instance what markup variation
* should be picked up. By default it will return null or the value of a parent.
*
* @return The variation of this component.
*/
public String getVariation()
{
if (parent != null)
{
return parent.getVariation();
}
return null;
}
/**
* Gets whether this component was rendered at least once.
*
* @return true if the component has been rendered before, false if it is merely constructed
*/
public final boolean hasBeenRendered()
{
return getFlag(FLAG_HAS_BEEN_RENDERED);
}
/**
* @return True if this component has an error message
*/
public final boolean hasErrorMessage()
{
return Session.get().getFeedbackMessages().hasErrorMessageFor(this);
}
/**
* @return True if this component has some kind of feedback message
*/
public final boolean hasFeedbackMessage()
{
return Session.get().getFeedbackMessages().hasMessageFor(this);
}
/**
* Registers an informational feedback message for this component
*
* @param message
* The feedback message
*/
public final void info(final Serializable message)
{
Session.get().getFeedbackMessages().info(this, message);
Session.get().dirty();
}
/**
* Authorizes an action for a component.
*
* @param action
* The action to authorize
* @return True if the action is allowed
* @throws AuthorizationException
* Can be thrown by implementation if action is unauthorized
*/
public final boolean isActionAuthorized(Action action)
{
IAuthorizationStrategy authorizationStrategy = getSession().getAuthorizationStrategy();
if (authorizationStrategy != null)
{
return authorizationStrategy.isActionAuthorized(this, action);
}
return true;
}
/**
* @return true if this component is authorized to be enabled, false otherwise
*/
public final boolean isEnableAllowed()
{
return isActionAuthorized(ENABLE);
}
/**
* Gets whether this component is enabled. Specific components may decide to implement special
* behavior that uses this property, like web form components that add a disabled='disabled'
* attribute when enabled is false.
*
* @return Whether this component is enabled.
*/
public boolean isEnabled()
{
return getFlag(FLAG_ENABLED);
}
/**
* Checks the security strategy if the {@link Component#RENDER} action is allowed on this
* component
*
* @return ture if {@link Component#RENDER} action is allowed, false otherwise
*/
public final boolean isRenderAllowed()
{
return getFlag(FLAG_IS_RENDER_ALLOWED);
}
/**
* Returns if the component is stateless or not. It checks the stateless hint if that is false
* it returns directly false. If that is still true it checks all its behaviors if they can be
* stateless.
*
* @return whether the component is stateless.
*/
public final boolean isStateless()
{
if (!getStatelessHint())
{
return false;
}
for (Behavior behavior : getBehaviors())
{
if (!behavior.getStatelessHint(this))
{
return false;
}
}
return true;
}
/**
* @return True if this component is versioned
*/
public boolean isVersioned()
{
// Is the component itself versioned?
if (!getFlag(FLAG_VERSIONED))
{
return false;
}
else
{
// If there's a parent and this component is versioned
if (parent != null)
{
// Check if the parent is unversioned. If any parent
// (recursively) is unversioned, then this component is too
if (!parent.isVersioned())
{
return false;
}
}
return true;
}
}
/**
* Gets whether this component and any children are visible.
* <p>
* WARNING: this method can be called multiple times during a request. If you override this
* method, it is a good idea to keep it cheap in terms of processing. Alternatively, you can
* call {@link #setVisible(boolean)}.
* <p>
*
* @return True if component and any children are visible
*/
public boolean isVisible()
{
return getFlag(FLAG_VISIBLE);
}
/**
* Checks if the component itself and all its parents are visible.
*
* @return true if the component and all its parents are visible.
*/
public final boolean isVisibleInHierarchy()
{
Component parent = getParent();
if (parent != null && !parent.isVisibleInHierarchy())
{
return false;
}
else
{
return determineVisibility();
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Sets the RENDERING flag and removes the PREPARED_FOR_RENDER flag on component and it's
* children.
*
* @param setRenderingFlag
* if this is false only the PREPARED_FOR_RENDER flag is removed from component, the
* RENDERING flag is not set.
*
* @see #internalPrepareForRender(boolean)
*/
public final void markRendering(boolean setRenderingFlag)
{
internalMarkRendering(setRenderingFlag);
}
/**
* Called to indicate that the model content for this component has been changed
*/
public final void modelChanged()
{
// Call user code
internalOnModelChanged();
onModelChanged();
}
/**
* Called to indicate that the model content for this component is about to change
*/
public final void modelChanging()
{
checkHierarchyChange(this);
// Call user code
onModelChanging();
// Tell the page that our model changed
final Page page = findPage();
if (page != null)
{
page.componentModelChanging(this);
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
* <p>
* Prepares the component and it's children for rendering. On whole page render this method must
* be called on the page. On AJAX request, this method must be called on updated component.
*
* @param setRenderingFlag
* Whether to set the rendering flag. This must be true if the page is about to be
* rendered. However, there are usecases to call this method without an immediate
* render (e.g. on stateless listner request target to build the component
* hierarchy), in that case setRenderingFlag should be false
*/
public void internalPrepareForRender(boolean setRenderingFlag)
{
beforeRender();
if (setRenderingFlag)
{
// only process feedback panel when we are about to be rendered.
// setRenderingFlag is false in case prepareForRender is called only to build component
// hierarchy (i.e. in BookmarkableListenerInterfaceRequestTarget).
// prepareForRender(true) is always called before the actual rendering is done so
// that's where feedback panels gather the messages
List<Component> feedbacks = getRequestCycle().getMetaData(FEEDBACK_LIST);
if (feedbacks != null)
{
for (Component feedback : feedbacks)
{
feedback.internalBeforeRender();
}
}
getRequestCycle().setMetaData(FEEDBACK_LIST, null);
}
markRendering(setRenderingFlag);
// check authorization
// first the component itself
// (after attach as otherwise list views etc wont work)
setRenderAllowed();
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Prepares the component and it's children for rendering. On whole page render this method must
* be called on the page. On AJAX request, this method must be called on updated component.
*/
public final void prepareForRender()
{
internalPrepareForRender(true);
}
/**
* Redirects browser to an intermediate page such as a sign-in page. The current request's url
* is saved for future use by method continueToOriginalDestination(); Only use this method when
* you plan to continue to the current url at some later time; otherwise just use
* setResponsePage or - when you are in a constructor or checkAccessMethod, call redirectTo.
*
* @param page
* The sign in page
*
* @see Component#continueToOriginalDestination()
*/
public final void redirectToInterceptPage(final Page page)
{
throw new RestartResponseAtInterceptPageException(page);
}
/**
* Removes this component from its parent. It's important to remember that a component that is
* removed cannot be referenced from the markup still.
*/
public final void remove()
{
if (parent == null)
{
throw new IllegalStateException("Cannot remove " + this + " from null parent!");
}
parent.remove(this);
}
/**
* Render the Component.
*/
public final void render()
{
RuntimeException exception = null;
try
{
// Invoke prepareForRender only if this is the root component to be rendered
MarkupContainer parent = getParent();
if ((parent == null) || (parent.getFlag(FLAG_RENDERING) == false) || isAuto())
{
internalPrepareForRender(true);
}
// Do the render
internalRender();
}
catch (final RuntimeException ex)
{
// Remember it as the originating exception
exception = ex;
}
finally
{
try
{
// Cleanup
afterRender();
}
catch (RuntimeException ex2)
{
// Only remember it if not already another exception happened
if (exception == null)
{
exception = ex2;
}
}
}
// Re-throw if needed
if (exception != null)
{
throw exception;
}
}
/**
* Performs a render of this component as part of a Page level render process.
*/
private final void internalRender()
{
// Make sure there is a markup available for the Component
IMarkupFragment markup = getMarkup();
if (markup == null)
{
throw new MarkupNotFoundException("Markup not found for Component: " + toString());
}
// MarkupStream is an Iterator for the markup
MarkupStream markupStream = new MarkupStream(markup);
// Flag: we stated the render process
markRendering(true);
MarkupElement elem = markup.get(0);
if (elem instanceof ComponentTag)
{
// Guarantee that the markupStream is set and determineVisibility not yet tested
// See WICKET-2049
((ComponentTag)elem).onBeforeRender(this, markupStream);
}
// Determine if component is visible using it's authorization status
// and the isVisible property.
if (determineVisibility())
{
setFlag(FLAG_HAS_BEEN_RENDERED, true);
// Rendering is beginning
if (log.isDebugEnabled())
{
log.debug("Begin render " + this);
}
try
{
notifyBehaviorsComponentBeforeRender();
onRender();
notifyBehaviorsComponentRendered();
// Component has been rendered
rendered();
}
catch (RuntimeException ex)
{
onException(ex);
}
if (log.isDebugEnabled())
{
log.debug("End render " + this);
}
}
// elem is null when rendering a page
else if ((elem != null) && (elem instanceof ComponentTag))
{
if (getFlag(FLAG_PLACEHOLDER))
{
renderPlaceholderTag((ComponentTag)elem, getResponse());
}
}
}
/**
* Called when a runtime exception is caught during the render process
*
* @param ex
* The exception caught.
*/
private void onException(final RuntimeException ex)
{
// Call each behaviors onException() to allow the
// behavior to clean up
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
try
{
behavior.onException(this, ex);
}
catch (Throwable ex2)
{
log.error("Error while cleaning up after exception", ex2);
}
}
}
// Re-throw the exception
throw ex;
}
/**
* Renders a placeholder tag for the component when it is invisible and
* {@link #setOutputMarkupPlaceholderTag(boolean)} has been called with <code>true</code>.
*
* @param tag
* component tag
* @param response
* response
*/
protected void renderPlaceholderTag(final ComponentTag tag, final Response response)
{
String ns = Strings.isEmpty(tag.getNamespace()) ? null : tag.getNamespace() + ":";
response.write("<");
if (ns != null)
{
response.write(ns);
}
response.write(tag.getName());
response.write(" id=\"");
response.write(getMarkupId());
response.write("\" style=\"display:none\"></");
if (ns != null)
{
response.write(ns);
}
response.write(tag.getName());
response.write(">");
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT.
* <p>
* Renders the component at the current position in the given markup stream. The method
* onComponentTag() is called to allow the component to mutate the start tag. The method
* onComponentTagBody() is then called to permit the component to render its body.
*/
public final void internalRenderComponent()
{
final IMarkupFragment markup = getMarkup();
if (markup == null)
{
throw new MarkupException("Markup not found. Component: " + toString());
}
final MarkupStream markupStream = new MarkupStream(markup);
// Get mutable copy of next tag
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
// Call any tag handler
onComponentTag(tag);
// If we're an openclose tag
if (!tag.isOpenClose() && !tag.isOpen())
{
// We were something other than <tag> or <tag/>
markupStream.throwMarkupException("Method renderComponent called on bad markup element: " +
tag);
}
if (tag.isOpenClose() && openTag.isOpen())
{
markupStream.throwMarkupException("You can not modify a open tag to open-close: " + tag);
}
try
{
// Render open tag
if (getRenderBodyOnly() == false)
{
renderComponentTag(tag);
}
markupStream.next();
// Render the body only if open-body-close. Do not render if open-close.
if (tag.isOpen())
{
// Render the body
onComponentTagBody(markupStream, tag);
}
// Render close tag
if (tag.isOpen())
{
if (openTag.isOpen())
{
renderClosingComponentTag(markupStream, tag, getRenderBodyOnly());
}
else if (getRenderBodyOnly() == false)
{
if (needToRenderTag(openTag))
{
// Close the manually opened tag. And since the user might have changed the
// tag name ...
getResponse().write(tag.syntheticCloseTagString());
}
}
}
}
catch (WicketRuntimeException wre)
{
throw wre;
}
catch (RuntimeException re)
{
throw new WicketRuntimeException("Exception in rendering component: " + this, re);
}
}
/**
*
* @param openTag
* @return true, if the tag shall be rendered
*/
private boolean needToRenderTag(final ComponentTag openTag)
{
// If a open-close tag has been modified to be open-body-close than a
// synthetic close tag must be rendered.
boolean renderTag = (openTag == null ? false : !(openTag instanceof WicketTag));
if (renderTag == false)
{
renderTag = !((getRequest() instanceof WebRequest) && ((WebRequest)getRequest()).isAjax());
renderTag &= !getApplication().getMarkupSettings().getStripWicketTags();
}
return renderTag;
}
/**
* Called to indicate that a component has been rendered. This method should only very rarely be
* called at all. Some components may render its children without calling render() on them.
* These components need to call rendered() to indicate that its child components were actually
* rendered, the framework would think they had never been rendered, and in development mode
* this would result in a runtime exception.
*/
public final void rendered()
{
Page page = findPage();
if (page != null)
{
// Tell the page that the component rendered
page.componentRendered(this);
}
else
{
log.error("Component is not connected to a Page. Cannot register the component as being rendered. Component: " +
toString());
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT.
*
* Print to the web response what ever the component wants to contribute to the head section.
* Make sure that all attached behaviors are asked as well.
* <p>
* NOT intended for overriding by framework clients. Rather, use
* {@link IHeaderContributor#renderHead(org.apache.wicket.markup.html.IHeaderResponse)}
* </p>
*
* @param container
* The HtmlHeaderContainer
*/
public void renderHead(final HtmlHeaderContainer container)
{
if (isVisibleInHierarchy() && isRenderAllowed())
{
if (log.isDebugEnabled())
{
log.debug("renderHead: " + toString(false));
}
IHeaderResponse response = container.getHeaderResponse();
// Allow component to contribute
if (response.wasRendered(this) == false)
{
renderHead(response);
response.markRendered(this);
}
// Than ask all behaviors
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
if (response.wasRendered(behavior) == false)
{
behavior.renderHead(this, response);
response.markRendered(behavior);
}
}
}
}
}
/**
* Replaces this component with another. The replacing component must have the same component id
* as this component. This method serves as a shortcut to
*
* <code>this.getParent().replace(replacement)</code>
*
* and provides a better context for errors.
* <p>
* Usage: <code>component = component.replaceWith(replacement);</code>
* </p>
*
* @since 1.2.1
*
* @param replacement
* component to replace this one
* @return the component which replaced this one
*/
public Component replaceWith(Component replacement)
{
if (replacement == null)
{
throw new IllegalArgumentException("Argument [[replacement]] cannot be null.");
}
if (!getId().equals(replacement.getId()))
{
throw new IllegalArgumentException(
"Replacement component must have the same id as the component it will replace. Replacement id [[" +
replacement.getId() + "]], replaced id [[" + getId() + "]].");
}
if (parent == null)
{
throw new IllegalStateException(
"This method can only be called on a component that has already been added to its parent.");
}
parent.replace(replacement);
return replacement;
}
/**
* @param component
* The component to compare with
* @return True if the given component's model is the same as this component's model.
*/
public final boolean sameInnermostModel(final Component component)
{
return sameInnermostModel(component.getDefaultModel());
}
/**
* @param model
* The model to compare with
* @return True if the given component's model is the same as this component's model.
*/
public final boolean sameInnermostModel(final IModel<?> model)
{
// Get the two models
IModel<?> thisModel = getDefaultModel();
// If both models are non-null they could be the same
if (thisModel != null && model != null)
{
return getInnermostModel(thisModel) == getInnermostModel(model);
}
return false;
}
/**
* Sets whether this component is enabled. Specific components may decide to implement special
* behavior that uses this property, like web form components that add a disabled='disabled'
* attribute when enabled is false. If it is not enabled, it will not be allowed to call any
* listener method on it (e.g. Link.onClick) and the model object will be protected (for the
* common use cases, not for programmer's misuse)
*
* @param enabled
* whether this component is enabled
* @return This
*/
public final Component setEnabled(final boolean enabled)
{
// Is new enabled state a change?
if (enabled != getFlag(FLAG_ENABLED))
{
// Tell the page that this component's enabled was changed
if (isVersioned())
{
final Page page = findPage();
if (page != null)
{
addStateChange();
}
}
// Change visibility
setFlag(FLAG_ENABLED, enabled);
onEnabledStateChanged();
}
return this;
}
void clearEnabledInHierarchyCache()
{
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET, false);
}
void onEnabledStateChanged()
{
clearEnabledInHierarchyCache();
}
/**
* Sets whether model strings should be escaped.
*
* @param escapeMarkup
* True is model strings should be escaped
* @return This
*/
public final Component setEscapeModelStrings(final boolean escapeMarkup)
{
setFlag(FLAG_ESCAPE_MODEL_STRINGS, escapeMarkup);
return this;
}
/**
* Set markup ID, which must be String or Integer
*
* @param markupId
*/
public final void setMarkupIdImpl(Object markupId)
{
if (markupId != null && !(markupId instanceof String) && !(markupId instanceof Integer))
{
throw new IllegalArgumentException("markupId must be String or Integer");
}
if (markupId instanceof Integer)
{
generatedMarkupId = (Integer)markupId;
setMetaData(MARKUP_ID_KEY, null);
return;
}
generatedMarkupId = -1;
setMetaData(MARKUP_ID_KEY, (String)markupId);
setOutputMarkupId(true);
}
/**
* Copy markupId
*
* @param comp
*/
final void setMarkupId(Component comp)
{
Args.notNull(comp, "comp");
generatedMarkupId = comp.generatedMarkupId;
setMetaData(MARKUP_ID_KEY, comp.getMetaData(MARKUP_ID_KEY));
setOutputMarkupId(comp.getOutputMarkupId());
}
/**
* Sets this component's markup id to a user defined value. It is up to the user to ensure this
* value is unique.
* <p>
* The recommended way is to let wicket generate the value automatically, this method is here to
* serve as an override for that value in cases where a specific id must be used.
* <p>
* If null is passed in the user defined value is cleared and markup id value will fall back on
* automatically generated value
*
* @see #getMarkupId()
*
* @param markupId
* markup id value or null to clear any previous user defined value
* @return this for chaining
*/
public Component setMarkupId(String markupId)
{
if (markupId != null && Strings.isEmpty(markupId))
{
throw new IllegalArgumentException("Markup id cannot be an empty string");
}
// TODO check if an automatic id has already been generated or getmarkupid() called
// previously and throw an illegalstateexception because something else might be depending
// on previous id
setMarkupIdImpl(markupId);
return this;
}
/**
* Sets the metadata for this component using the given key. If the metadata object is not of
* the correct type for the metadata key, an IllegalArgumentException will be thrown. For
* information on creating MetaDataKeys, see {@link MetaDataKey}.
*
* @param <M>
* The type of the metadata
*
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @throws IllegalArgumentException
* @see MetaDataKey
*/
public final <M> void setMetaData(final MetaDataKey<M> key, final M object)
{
MetaDataEntry<?>[] old = getMetaData();
Object metaData = null;
MetaDataEntry<?>[] metaDataArray = key.set(getMetaData(), object);
if (metaDataArray != null && metaDataArray.length > 0)
{
metaData = (metaDataArray.length > 1) ? metaDataArray : metaDataArray[0];
}
int index = getFlag(FLAG_MODEL_SET) ? 1 : 0;
if (old == null && metaData != null)
{
data_insert(index, metaData);
}
else if (old != null && metaData != null)
{
data_set(index, metaData);
}
else if (old != null && metaData == null)
{
data_remove(index);
}
}
/**
* Sets the given model.
* <p>
* WARNING: DO NOT OVERRIDE THIS METHOD UNLESS YOU HAVE A VERY GOOD REASON FOR IT. OVERRIDING
* THIS MIGHT OPEN UP SECURITY LEAKS AND BREAK BACK-BUTTON SUPPORT.
* </p>
*
* @param model
* The model
* @return This
*/
public Component setDefaultModel(final IModel<?> model)
{
IModel<?> prevModel = getModelImpl();
// Detach current model
if (prevModel != null)
{
prevModel.detach();
}
IModel<?> wrappedModel = prevModel;
if (prevModel instanceof IWrapModel)
{
wrappedModel = ((IWrapModel<?>)prevModel).getWrappedModel();
}
// Change model
if (wrappedModel != model)
{
if (wrappedModel != null)
{
addStateChange();
}
setModelImpl(wrap(model));
}
modelChanged();
return this;
}
/**
* @return model
*/
IModel<?> getModelImpl()
{
if (getFlag(FLAG_MODEL_SET))
{
return (IModel<?>)data_get(0);
}
return null;
}
/**
*
* @param model
*/
void setModelImpl(IModel<?> model)
{
if (getFlag(FLAG_MODEL_SET))
{
if (model != null)
{
data_set(0, model);
}
else
{
data_remove(0);
setFlag(FLAG_MODEL_SET, false);
}
}
else
{
if (model != null)
{
data_insert(0, model);
setFlag(FLAG_MODEL_SET, true);
}
}
}
/**
* Sets the backing model object. Unlike <code>getDefaultModel().setObject(object)</code>, this
* method checks authorisation and model comparator, and invokes <code>modelChanging</code> and
* <code>modelChanged</code> if the value really changes.
*
* @param object
* The object to set
* @return This
*/
@SuppressWarnings("unchecked")
public final Component setDefaultModelObject(final Object object)
{
final IModel<Object> model = (IModel<Object>)getDefaultModel();
// Check whether anything can be set at all
if (model == null)
{
throw new IllegalStateException(
"Attempt to set model object on null model of component: " + getPageRelativePath());
}
// Check authorization
if (!isActionAuthorized(ENABLE))
{
throw new UnauthorizedActionException(this, ENABLE);
}
// Check whether this will result in an actual change
if (!getModelComparator().compare(this, object))
{
modelChanging();
model.setObject(object);
modelChanged();
}
return this;
}
/**
* Sets whether or not component will output id attribute into the markup. id attribute will be
* set to the value returned from {@link Component#getMarkupId()}.
*
* @param output
* True if the component will output the id attribute into markup. Please note that
* the default behavior is to use the same id as the component. This means that your
* component must begin with [a-zA-Z] in order to generate a valid markup id
* according to: http://www.w3.org/TR/html401/types.html#type-name
*
* @return this for chaining
*/
public final Component setOutputMarkupId(final boolean output)
{
setFlag(FLAG_OUTPUT_MARKUP_ID, output);
return this;
}
/**
* Render a placeholder tag when the component is not visible. The tag is of form:
* <componenttag style="display:none;" id="markupid"/>. This method will also call
* <code>setOutputMarkupId(true)</code>.
*
* This is useful, for example, in ajax situations where the component starts out invisible and
* then becomes visible through an ajax update. With a placeholder tag already in the markup you
* do not need to repaint this component's parent, instead you can repaint the component
* directly.
*
* When this method is called with parameter <code>false</code> the outputmarkupid flag is not
* reverted to false.
*
* @param outputTag
* @return this for chaining
*/
public final Component setOutputMarkupPlaceholderTag(final boolean outputTag)
{
if (outputTag != getFlag(FLAG_PLACEHOLDER))
{
if (outputTag)
{
setOutputMarkupId(true);
setFlag(FLAG_PLACEHOLDER, true);
}
else
{
setFlag(FLAG_PLACEHOLDER, false);
// I think it's better to not setOutputMarkupId to false...
// user can do it if we want
}
}
return this;
}
/**
* If false the component's tag will be printed as well as its body (which is default). If true
* only the body will be printed, but not the component's tag.
*
* @param renderTag
* If true, the component tag will not be printed
* @return This
*/
public final Component setRenderBodyOnly(final boolean renderTag)
{
setFlag(FLAG_RENDER_BODY_ONLY, renderTag);
return this;
}
/**
* Sets the page that will respond to this request
*
* @param <C>
*
* @param cls
* The response page class
* @see RequestCycle#setResponsePage(Class)
*/
public final <C extends IRequestablePage> void setResponsePage(final Class<C> cls)
{
getRequestCycle().setResponsePage(cls, null);
}
/**
* Sets the page class and its parameters that will respond to this request
*
* @param <C>
*
* @param cls
* The response page class
* @param parameters
* The parameters for this bookmarkable page.
* @see RequestCycle#setResponsePage(Class, PageParameters)
*/
public final <C extends IRequestablePage> void setResponsePage(final Class<C> cls,
PageParameters parameters)
{
getRequestCycle().setResponsePage(cls, parameters);
}
/**
* Sets the page that will respond to this request
*
* @param page
* The response page
*
* @see RequestCycle#setResponsePage(org.apache.wicket.request.component.IRequestablePage)
*/
public final void setResponsePage(final Page page)
{
getRequestCycle().setResponsePage(page);
}
/**
* @param versioned
* True to turn on versioning for this component, false to turn it off for this
* component and any children.
* @return This
*/
public Component setVersioned(boolean versioned)
{
setFlag(FLAG_VERSIONED, versioned);
return this;
}
/**
* Sets whether this component and any children are visible.
*
* @param visible
* True if this component and any children should be visible
* @return This
*/
public final Component setVisible(final boolean visible)
{
// Is new visibility state a change?
if (visible != getFlag(FLAG_VISIBLE))
{
// record component's visibility change
addStateChange();
// Change visibility
setFlag(FLAG_VISIBLE, visible);
onVisibleStateChanged();
}
return this;
}
void clearVisibleInHierarchyCache()
{
setRequestFlag(RFLAG_VISIBLE_IN_HIERARCHY_SET, false);
}
void onVisibleStateChanged()
{
clearVisibleInHierarchyCache();
}
/**
* Gets the string representation of this component.
*
* @return The path to this component
*/
@Override
public String toString()
{
return toString(false);
}
/**
* @param detailed
* True if a detailed string is desired
* @return The string
*/
public String toString(final boolean detailed)
{
if (detailed)
{
final Page page = findPage();
if (page == null)
{
return new StringBuilder("[Component id = ").append(getId())
.append(", page = <No Page>, path = ")
.append(getPath())
.append(".")
.append(Classes.simpleName(getClass()))
.append("]")
.toString();
}
else
{
return new StringBuilder("[Component id = ").append(getId())
.append(", page = ")
.append(getPage().getClass().getName())
.append(", path = ")
.append(getPath())
.append(".")
.append(Classes.simpleName(getClass()))
.append(", isVisible = ")
.append((determineVisibility()))
.append(", isVersioned = ")
.append(isVersioned())
.append("]")
.toString();
}
}
else
{
return "[Component id = " + getId() + "]";
}
}
/**
* Returns a bookmarkable URL that references a given page class using a given set of page
* parameters. Since the URL which is returned contains all information necessary to instantiate
* and render the page, it can be stored in a user's browser as a stable bookmark.
*
* @param <C>
*
* @see RequestCycle#urlFor(Class, org.apache.wicket.request.mapper.parameter.PageParameters)
*
* @param pageClass
* Class of page
* @param parameters
* Parameters to page
* @return Bookmarkable URL to page
*/
public final <C extends Page> CharSequence urlFor(final Class<C> pageClass,
final PageParameters parameters)
{
return getRequestCycle().urlFor(pageClass, parameters);
}
/**
* Gets a URL for the listener interface on a behavior (e.g. IBehaviorListener on
* AjaxPagingNavigationBehavior).
*
* @param behaviour
* The behavior that the URL should point to
* @param listener
* The listener interface that the URL should call
* @return The URL
*/
public final CharSequence urlFor(final Behavior behaviour,
final RequestListenerInterface listener)
{
PageAndComponentProvider provider = new PageAndComponentProvider(getPage(), this);
int id = getBehaviorId(behaviour);
IRequestHandler handler;
if (getPage().isPageStateless())
{
handler = new BookmarkableListenerInterfaceRequestHandler(provider, listener, id);
}
else
{
handler = new ListenerInterfaceRequestHandler(provider, listener, id);
}
return getRequestCycle().urlFor(handler);
}
/**
* Returns a URL that references the given request target.
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param requestHandler
* the request target to reference
*
* @return a URL that references the given request target
*/
public final CharSequence urlFor(final IRequestHandler requestHandler)
{
return getRequestCycle().urlFor(requestHandler);
}
/**
* Gets a URL for the listener interface (e.g. ILinkListener).
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param listener
* The listener interface that the URL should call
* @return The URL
*/
public final CharSequence urlFor(final RequestListenerInterface listener)
{
PageAndComponentProvider provider = new PageAndComponentProvider(getPage(), this);
IRequestHandler handler;
if (getPage().isPageStateless())
{
handler = new BookmarkableListenerInterfaceRequestHandler(provider, listener);
}
else
{
handler = new ListenerInterfaceRequestHandler(provider, listener);
}
return getRequestCycle().urlFor(handler);
}
/**
* Returns a URL that references a shared resource through the provided resource reference.
*
* @see RequestCycle#urlFor(IRequestHandler)
*
* @param resourceReference
* The resource reference
* @param parameters
* parameters or {@code null} if none
* @return The url for the shared resource
*/
public final CharSequence urlFor(final ResourceReference resourceReference,
PageParameters parameters)
{
return getRequestCycle().urlFor(resourceReference, parameters);
}
/**
* Traverses all parent components of the given class in this container, calling the visitor's
* visit method at each one.
*
* @param c
* Class
* @param visitor
* The visitor to call at each parent of the given type
* @return First non-null value returned by visitor callback
*/
public final <R> R visitParents(final Class<?> c, final IVisitor<Component, R> visitor)
{
// Start here
Component current = getParent();
Visit<R> visit = new Visit<R>();
// Walk up containment hierarchy
while (current != null)
{
// Is current an instance of this class?
if (c.isInstance(current))
{
visitor.component(current, visit);
if (visit.isStopped())
{
return visit.getResult();
}
}
// Check parent
current = current.getParent();
}
return null;
}
/**
* Registers a warning feedback message for this component.
*
* @param message
* The feedback message
*/
public final void warn(final Serializable message)
{
Session.get().getFeedbackMessages().warn(this, message);
Session.get().dirty();
}
/**
* {@link Behavior#beforeRender(Component)} Notify all behaviors that are assigned to this
* component that the component is about to be rendered.
*/
private void notifyBehaviorsComponentBeforeRender()
{
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
behavior.beforeRender(this);
}
}
}
/**
* {@link Behavior#afterRender(Component)} Notify all behaviors that are assigned to this
* component that the component has rendered.
*/
private void notifyBehaviorsComponentRendered()
{
// notify the behaviors that component has been rendered
for (Behavior behavior : getBehaviors())
{
if (isBehaviorAccepted(behavior))
{
behavior.afterRender(this);
}
}
}
/**
* TODO WICKET-NG rename to something more useful - like componentChanged(), this method used to
* be called with a Change object
*
* Adds state change to page.
*/
protected final void addStateChange()
{
checkHierarchyChange(this);
final Page page = findPage();
if (page != null)
{
page.componentStateChanging(this);
}
}
/**
* Checks whether the given type has the expected name.
*
* @param tag
* The tag to check
* @param name
* The expected tag name
* @throws MarkupException
* Thrown if the tag is not of the right name
*/
protected final void checkComponentTag(final ComponentTag tag, final String name)
{
if (!tag.getName().equalsIgnoreCase(name))
{
String msg = String.format("Component [%s] (path = [%s]) must be "
+ "applied to a tag of type [%s], not: %s", getId(), getPath(), name,
tag.toUserDebugString());
findMarkupStream().throwMarkupException(msg);
}
}
/**
* Checks that a given tag has a required attribute value.
*
* @param tag
* The tag
* @param key
* The attribute key
* @param value
* The required value for the attribute key
* @throws MarkupException
* Thrown if the tag does not have the required attribute value
*/
protected final void checkComponentTagAttribute(final ComponentTag tag, final String key,
final String value)
{
if (key != null)
{
final String tagAttributeValue = tag.getAttributes().getString(key);
if (tagAttributeValue == null || !value.equalsIgnoreCase(tagAttributeValue))
{
String msg = String.format("Component [%s] (path = [%s]) must be applied to a tag "
+ "with [%s] attribute matching [%s], not [%s]", getId(), getPath(), key,
value, tagAttributeValue);
findMarkupStream().throwMarkupException(msg);
}
}
}
/**
* Checks whether the hierarchy may be changed at all, and throws an exception if this is not
* the case.
*
* @param component
* the component which is about to be added or removed
*/
protected void checkHierarchyChange(final Component component)
{
// Throw exception if modification is attempted during rendering
if (!component.isAuto() && getFlag(FLAG_RENDERING))
{
throw new WicketRuntimeException(
"Cannot modify component hierarchy after render phase has started (page version cant change then anymore)");
}
}
/**
* Detaches the model for this component if it is detachable.
*/
protected void detachModel()
{
IModel<?> model = getModelImpl();
if (model != null)
{
model.detach();
}
// also detach the wrapped model of a component assigned wrap (not
// inherited)
if (model instanceof IWrapModel && !getFlag(FLAG_INHERITABLE_MODEL))
{
((IWrapModel<?>)model).getWrappedModel().detach();
}
}
/**
* Prefixes an exception message with useful information about this. component.
*
* @param message
* The message
* @return The modified message
*/
protected final String exceptionMessage(final String message)
{
return message + ":\n" + toString();
}
/**
* Finds the markup stream for this component.
*
* @return The markup stream for this component. Since a Component cannot have a markup stream,
* we ask this component's parent to search for it.
* @TODO can be removed in 1.5
*/
protected final MarkupStream findMarkupStream()
{
return new MarkupStream(getMarkup());
}
/**
* If this Component is a Page, returns self. Otherwise, searches for the nearest Page parent in
* the component hierarchy. If no Page parent can be found, null is returned.
*
* @return The Page or null if none can be found
*/
protected final Page findPage()
{
// Search for page
return (Page)(this instanceof Page ? this : findParent(Page.class));
}
/**
* Gets the subset of the currently coupled {@link Behavior}s that are of the provided type as a
* unmodifiable list. Returns an empty list rather than null if there are no behaviors coupled
* to this component.
*
* @param type
* The type or null for all
* @return The subset of the currently coupled behaviors that are of the provided type as a
* unmodifiable list or null
* @param <M>
* A class derived from IBehavior
*/
public <M extends Behavior> List<M> getBehaviors(Class<M> type)
{
return new Behaviors(this).getBehaviors(type);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getFlag(final int flag)
{
return (flags & flag) != 0;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to test
* @return True if the flag is set
*/
protected final boolean getRequestFlag(final short flag)
{
return (requestFlags & flag) != 0;
}
/**
* Finds the innermost IModel object for an IModel that might contain nested IModel(s).
*
* @param model
* The model
* @return The innermost (most nested) model
*/
protected final IModel<?> getInnermostModel(final IModel<?> model)
{
IModel<?> nested = model;
while (nested != null && nested instanceof IWrapModel)
{
final IModel<?> next = ((IWrapModel<?>)nested).getWrappedModel();
if (nested == next)
{
throw new WicketRuntimeException("Model for " + nested + " is self-referential");
}
nested = next;
}
return nested;
}
/**
* Gets the component's current model comparator. Implementations can be used for testing the
* current value of the components model data with the new value that is given.
*
* @return the value defaultModelComparator
*/
public IModelComparator getModelComparator()
{
return defaultModelComparator;
}
/**
* Returns whether the component can be stateless. Also the component behaviors must be
* stateless, otherwise the component will be treat as stateful. In order for page to be
* stateless (and not to be stored in session), all components (and component behaviors) must be
* stateless.
*
* @return whether the component can be stateless
*/
protected boolean getStatelessHint()
{
return true;
}
/**
* Called when a null model is about to be retrieved in order to allow a subclass to provide an
* initial model. This gives FormComponent, for example, an opportunity to instantiate a model
* on the fly using the containing Form's model.
*
* @return The model
*/
protected IModel<?> initModel()
{
IModel<?> foundModel = null;
// Search parents for CompoundPropertyModel
for (Component current = getParent(); current != null; current = current.getParent())
{
// Get model
// Don't call the getModel() that could initialize many inbetween
// completely useless models.
// IModel model = current.getModel();
IModel<?> model = current.getModelImpl();
if (model instanceof IWrapModel && !(model instanceof IComponentInheritedModel))
{
model = ((IWrapModel<?>)model).getWrappedModel();
}
if (model instanceof IComponentInheritedModel)
{
// return the shared inherited
foundModel = ((IComponentInheritedModel<?>)model).wrapOnInheritance(this);
setFlag(FLAG_INHERITABLE_MODEL, true);
break;
}
}
// No model for this component!
return foundModel;
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL OR OVERRIDE.
*
* <p>
* Called anytime a model is changed via setModel or setModelObject.
* </p>
*/
protected void internalOnModelChanged()
{
}
/**
* Components are allowed to reject behavior modifiers.
*
* @param behavior
* @return False, if the component should not apply this behavior
*/
protected boolean isBehaviorAccepted(final Behavior behavior)
{
// Ignore AttributeModifiers when FLAG_IGNORE_ATTRIBUTE_MODIFIER is set
if ((behavior instanceof AttributeModifier) &&
(getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER) != false))
{
return false;
}
return behavior.isEnabled(this);
}
/**
* If true, all attribute modifiers will be ignored
*
* @return True, if attribute modifiers are to be ignored
*/
protected final boolean isIgnoreAttributeModifier()
{
return getFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER);
}
/**
* @return Component's markup stream
*/
protected MarkupStream locateMarkupStream()
{
return new MarkupStream(getMarkup());
}
/**
* Called just after a component is rendered.
*/
protected void onAfterRender()
{
setFlag(FLAG_AFTER_RENDERING, false);
}
/**
* Called just before a component is rendered.
* <p>
* <strong>NOTE</strong>: If you override this, you *must* call super.onBeforeRender() within
* your implementation.
*
* Because this method is responsible for cascading {@link #onBeforeRender()} call to its
* children it is strongly recommended that super call is made at the end of the override.
* </p>
*
* @see Component#callOnBeforeRenderIfNotVisible()
*/
protected void onBeforeRender()
{
setFlag(FLAG_PREPARED_FOR_RENDER, true);
onBeforeRenderChildren();
setRequestFlag(RFLAG_BEFORE_RENDER_SUPER_CALL_VERIFIED, true);
}
/**
* Processes the component tag.
* <p/>
* Overrides of this method most likely should call the super implementation.
*
* @param tag
* Tag to modify
*/
protected void onComponentTag(final ComponentTag tag)
{
// We can't try to get the ID from markup. This could be different than
// id returned from getMarkupId() prior first rendering the component
// (due to transparent resolvers and borders which break the 1:1
// component <-> markup relation)
if (getFlag(FLAG_OUTPUT_MARKUP_ID))
{
tag.put(MARKUP_ID_ATTR_NAME, getMarkupId());
}
if (getApplication().getDebugSettings().isOutputComponentPath())
{
String path = getPageRelativePath();
path = path.replace("_", "__");
path = path.replace(":", "_");
tag.put("wicketpath", path);
}
}
/**
* Processes the body.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
}
/**
* Called to allow a component to detach resources after use.
*
* Overrides of this method MUST call the super implementation, the most logical place to do
* this is the last line of the override method.
*/
protected void onDetach()
{
setFlag(FLAG_DETACHING, false);
}
/**
* Called to notify the component it is being removed from the component hierarchy
*
* Overrides of this method MUST call the super implementation, the most logical place to do
* this is the last line of the override method.
*
*
*/
protected void onRemove()
{
setFlag(FLAG_REMOVING_FROM_HIERARCHY, false);
}
/**
* Called anytime a model is changed after the change has occurred
*/
protected void onModelChanged()
{
}
/**
* Called anytime a model is changed, but before the change actually occurs
*/
protected void onModelChanging()
{
}
/**
* Implementation that renders this component.
*/
protected abstract void onRender();
/**
* Writes a simple tag out to the response stream. Any components that might be referenced by
* the tag are ignored. Also undertakes any tag attribute modifications if they have been added
* to the component.
*
* @param tag
* The tag to write
*/
protected final void renderComponentTag(ComponentTag tag)
{
if (needToRenderTag(tag))
{
// Apply behavior modifiers
List<? extends Behavior> behaviors = getBehaviors();
if ((behaviors != null) && !behaviors.isEmpty() && !tag.isClose() &&
(isIgnoreAttributeModifier() == false))
{
tag = tag.mutable();
for (Behavior behavior : behaviors)
{
// Components may reject some behavior components
if (isBehaviorAccepted(behavior))
{
behavior.onComponentTag(this, tag);
}
}
}
// apply behaviors that are attached to the component tag.
if (tag.hasBehaviors())
{
Iterator<? extends Behavior> tagBehaviors = tag.getBehaviors();
while (tagBehaviors.hasNext())
{
final Behavior behavior = tagBehaviors.next();
if (behavior.isEnabled(this))
{
behavior.onComponentTag(this, tag);
}
behavior.detach(this);
}
}
// Write the tag
tag.writeOutput(getResponse(), !needToRenderTag(null),
getMarkup().getMarkupResourceStream().getWicketNamespace());
}
}
/**
* Replaces the body with the given one.
*
* @param markupStream
* The markup stream to replace the tag body in
* @param tag
* The tag
* @param body
* The new markup
*/
protected final void replaceComponentTagBody(final MarkupStream markupStream,
final ComponentTag tag, final CharSequence body)
{
// The tag might have been changed from open-close to open. Hence
// we'll need what was in the markup itself
ComponentTag markupOpenTag = null;
// If tag has a body
if (tag.isOpen())
{
// Get what tag was in the markup; not what the user it might
// have changed it to.
markupOpenTag = markupStream.getPreviousTag();
// If it was an open tag in the markup as well, than ...
if (markupOpenTag.isOpen())
{
// skip any raw markup in the body
markupStream.skipRawMarkup();
}
}
if (body != null)
{
// Write the new body
getResponse().write(body);
}
// If we had an open tag (and not an openclose tag) and we found a
// close tag, we're good
if (tag.isOpen())
{
// If it was an open tag in the markup, than there must be
// a close tag as well.
if ((markupOpenTag != null) && markupOpenTag.isOpen() && !markupStream.atCloseTag())
{
// There must be a component in this discarded body
markupStream.throwMarkupException("Expected close tag for '" + markupOpenTag +
"' Possible attempt to embed component(s) '" + markupStream.get() +
"' in the body of this component which discards its body");
}
}
}
/**
* @param auto
* True to put component into auto-add mode
*/
protected final void setAuto(final boolean auto)
{
setFlag(FLAG_AUTO, auto);
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setFlag(final int flag, final boolean set)
{
if (set)
{
flags |= flag;
}
else
{
flags &= ~flag;
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* @param flag
* The flag to set
* @param set
* True to turn the flag on, false to turn it off
*/
protected final void setRequestFlag(final short flag, final boolean set)
{
if (set)
{
requestFlags |= flag;
}
else
{
requestFlags &= ~flag;
}
}
/**
* If true, all attribute modifiers will be ignored
*
* @param ignore
* If true, all attribute modifiers will be ignored
* @return This
*/
protected final Component setIgnoreAttributeModifier(final boolean ignore)
{
setFlag(FLAG_IGNORE_ATTRIBUTE_MODIFIER, ignore);
return this;
}
/**
* @param <V>
* The model type
* @param model
* The model to wrap if need be
* @return The wrapped model
*/
protected final <V> IModel<V> wrap(final IModel<V> model)
{
if (model instanceof IComponentAssignedModel)
{
return ((IComponentAssignedModel<V>)model).wrapOnAssignment(this);
}
return model;
}
/**
* Detaches any child components
*/
void detachChildren()
{
}
/**
* Signals this components removal from hierarchy to all its children.
*/
void removeChildren()
{
}
/**
* Gets the component at the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
public Component get(final String path)
{
// Path to this component is an empty path
if (path.equals(""))
{
return this;
}
throw new IllegalArgumentException(
exceptionMessage("Component is not a container and so does " + "not contain the path " +
path));
}
/**
* Checks whether or not this component has a markup id value generated, whether it is automatic
* or user defined
*
* @return true if this component has a markup id value generated
*/
final boolean hasMarkupIdMetaData()
{
return getMarkupId() != null;
}
/**
* @param setRenderingFlag
* rendering flag
*/
void internalMarkRendering(boolean setRenderingFlag)
{
if (setRenderingFlag)
{
setFlag(FLAG_PREPARED_FOR_RENDER, false);
setFlag(FLAG_RENDERING, true);
}
}
/**
* @return True if this component or any of its parents is in auto-add mode
*/
public final boolean isAuto()
{
// Search up hierarchy for FLAG_AUTO
for (Component current = this; current != null; current = current.getParent())
{
if (current.getFlag(FLAG_AUTO))
{
return true;
}
}
return false;
}
/**
*
* @return <code>true</code> if component has been prepared for render
*/
boolean isPreparedForRender()
{
return getFlag(FLAG_PREPARED_FOR_RENDER);
}
/**
*
*/
void onAfterRenderChildren()
{
}
/**
* This method is here for {@link MarkupContainer}. It is broken out of
* {@link #onBeforeRender()} so we can guarantee that it executes as the last in
* onBeforeRender() chain no matter where user places the <code>super.onBeforeRender()</code>
* call.
*/
void onBeforeRenderChildren()
{
}
/**
* Renders the close tag at the current position in the markup stream.
*
* @param markupStream
* the markup stream
* @param openTag
* the tag to render
* @param renderBodyOnly
* if true, the tag will not be written to the output
*/
final void renderClosingComponentTag(final MarkupStream markupStream,
final ComponentTag openTag, final boolean renderBodyOnly)
{
// Tag should be open tag and not openclose tag
if (openTag.isOpen())
{
// If we found a close tag and it closes the open tag, we're good
if (markupStream.atCloseTag() && markupStream.getTag().closes(openTag))
{
// Render the close tag
if (renderBodyOnly == false)
{
// Get the close tag from the stream
ComponentTag closeTag = markupStream.getTag();
// If the open tag had its id changed
if (openTag.getNameChanged())
{
// change the id of the close tag
closeTag = closeTag.mutable();
closeTag.setName(openTag.getName());
closeTag.setNamespace(openTag.getNamespace());
}
renderComponentTag(closeTag);
}
}
else if (openTag.requiresCloseTag())
{
// Missing close tag. Some tags, e.g. <p> are handled like <p/> by most browsers and
// thus will not throw an exception.
markupStream.throwMarkupException("Expected close tag for " + openTag);
}
}
}
/**
* THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT!
*
* Sets the id of this component.
*
* @param id
* The non-null id of this component
*/
final void setId(final String id)
{
if (!(this instanceof Page))
{
if (Strings.isEmpty(id))
{
throw new WicketRuntimeException("Null or empty component ID's are not allowed.");
}
}
if ((id != null) && (id.indexOf(':') != -1))
{
throw new WicketRuntimeException("The component ID must not contain ':' chars.");
}
this.id = id;
}
/**
* THIS IS A WICKET INTERNAL API. DO NOT USE IT.
*
* Sets the parent of a component. Typically what you really want is parent.add(child).
* <p/>
* Note that calling setParent() and not parent.add() will connect the child to the parent, but
* the parent will not know the child. This might not be a problem in some cases, but e.g.
* child.onDetach() will not be invoked (since the parent doesn't know it is his child).
*
* @param parent
* The parent container
*/
public final void setParent(final MarkupContainer parent)
{
if (this.parent != null && log.isDebugEnabled())
{
log.debug("Replacing parent " + this.parent + " with " + parent);
}
this.parent = parent;
}
/**
* Sets the render allowed flag.
*
* @param renderAllowed
*/
final void setRenderAllowed(boolean renderAllowed)
{
setFlag(FLAG_IS_RENDER_ALLOWED, renderAllowed);
}
/**
* Sets the render allowed flag.
*
* Visit all this page's children (overridden in MarkupContainer) to check rendering
* authorization, as appropriate. We set any result; positive or negative as a temporary boolean
* in the components, and when a authorization exception is thrown it will block the rendering
* of this page
*/
void setRenderAllowed()
{
setRenderAllowed(isActionAuthorized(RENDER));
}
/**
* Sets whether or not this component is allowed to be visible. This method is meant to be used
* by components to control visibility of other components. A call to
* {@link #setVisible(boolean)} will not always have a desired effect because that component may
* have {@link #isVisible()} overridden. Both {@link #setVisibilityAllowed(boolean)} and
* {@link #isVisibilityAllowed()} are <code>final</code> so their contract is enforced always.
*
* @param allowed
* @return <code>this</code> for chaining
*/
public final Component setVisibilityAllowed(boolean allowed)
{
setFlag(FLAG_VISIBILITY_ALLOWED, allowed);
return this;
}
/**
* Gets whether or not visibility is allowed on this component. See
* {@link #setVisibilityAllowed(boolean)} for details.
*
* @return true if this component is allowed to be visible, false otherwise.
*/
public final boolean isVisibilityAllowed()
{
return getFlag(FLAG_VISIBILITY_ALLOWED);
}
/**
* Determines whether or not a component should be visible, taking into account all the factors:
* {@link #isVisible()}, {@link #isVisibilityAllowed()}, {@link #isRenderAllowed()}
*
* @return <code>true</code> if the component should be visible, <code>false</code> otherwise
*/
public final boolean determineVisibility()
{
return isVisible() && isRenderAllowed() && isVisibilityAllowed();
}
/**
* Calculates enabled state of the component taking its hierarchy into account. A component is
* enabled iff it is itself enabled ({@link #isEnabled()} and {@link #isEnableAllowed()} both
* return <code>true</code>), and all of its parents are enabled.
*
* @return <code>true</code> if this component is enabled</code>
*/
public final boolean isEnabledInHierarchy()
{
if (getRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET))
{
return getRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_VALUE);
}
final boolean state;
Component parent = getParent();
if (parent != null && !parent.isEnabledInHierarchy())
{
state = false;
}
else
{
state = isEnabled() && isEnableAllowed();
}
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_SET, true);
setRequestFlag(RFLAG_ENABLED_IN_HIERARCHY_VALUE, state);
return state;
}
/** TODO WICKET-NG javadoc */
public final boolean canCallListenerInterface()
{
return isEnabledInHierarchy() && isVisibleInHierarchy();
}
/** {@inheritDoc} */
public void renderHead(IHeaderResponse response)
{
// noop
}
/** {@inheritDoc} */
public void onEvent(IEvent<?> event)
{
}
/** {@inheritDoc} */
public final void send(IEventSink sink, Broadcast type, Object payload)
{
new ComponentEventSender(this).send(sink, type, payload);
}
/**
* Removes behavior from component
*
* @param behaviors
* behaviors to remove
*
* @return this (to allow method call chaining)
*/
public Component remove(final Behavior... behaviors)
{
Behaviors helper = new Behaviors(this);
for (Behavior behavior : behaviors)
{
helper.remove(behavior);
}
return this;
}
/** {@inheritDoc} */
public final Behavior getBehaviorById(int id)
{
return new Behaviors(this).getBehaviorById(id);
}
/** {@inheritDoc} */
public final int getBehaviorId(Behavior behavior)
{
return new Behaviors(this).getBehaviorId(behavior);
}
/**
* Adds a behavior modifier to the component.
*
* <p>
* Note: this method is override to enable users to do things like discussed in <a
* href="http://www.nabble.com/Why-add%28IBehavior%29-is-final--tf2598263.html#a7248198">this
* thread</a>.
* </p>
*
* @param behaviors
* The behavior modifier(s) to be added
* @return this (to allow method call chaining)
*/
public Component add(final Behavior... behaviors)
{
new Behaviors(this).add(behaviors);
return this;
}
/**
* Gets the currently coupled {@link Behavior}s as a unmodifiable list. Returns an empty list
* rather than null if there are no behaviors coupled to this component.
*
* @return The currently coupled behaviors as a unmodifiable list
*/
public final List<? extends Behavior> getBehaviors()
{
return getBehaviors(Behavior.class);
}
}
|
Exception when calling setOutputMarkupId/PlaceholderTag on wicket:container
Issue: WICKET-3237
git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@1044778 13f79535-47bb-0310-9956-ffa450edef68
|
wicket/src/main/java/org/apache/wicket/Component.java
|
Exception when calling setOutputMarkupId/PlaceholderTag on wicket:container Issue: WICKET-3237
|
|
Java
|
apache-2.0
|
e8ec82beb303fa2f6824288b3b2cf85c788af103
| 0
|
droolsjbpm/jbpm-designer,jomarko/jbpm-designer,jhrcek/jbpm-designer,droolsjbpm/jbpm-designer,droolsjbpm/jbpm-designer,tsurdilo/jbpm-designer,tsurdilo/jbpm-designer,jomarko/jbpm-designer,droolsjbpm/jbpm-designer,jomarko/jbpm-designer,tsurdilo/jbpm-designer,porcelli-forks/jbpm-designer,tsurdilo/jbpm-designer,porcelli-forks/jbpm-designer,porcelli-forks/jbpm-designer,jhrcek/jbpm-designer,porcelli-forks/jbpm-designer,jhrcek/jbpm-designer,jhrcek/jbpm-designer,jomarko/jbpm-designer
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.designer.web.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.guvnor.common.services.project.model.Module;
import org.guvnor.common.services.project.service.ModuleService;
import org.guvnor.common.services.project.service.POMService;
import org.guvnor.common.services.shared.metadata.MetadataService;
import org.jbpm.designer.notification.DesignerWorkitemInstalledEvent;
import org.jbpm.designer.repository.Repository;
import org.jbpm.designer.util.ConfigurationProvider;
import org.jbpm.designer.util.Utils;
import org.jbpm.designer.web.profile.IDiagramProfile;
import org.jbpm.designer.web.profile.IDiagramProfileService;
import org.jbpm.process.workitem.WorkDefinitionImpl;
import org.jbpm.process.workitem.WorkItemRepository;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.vfs.VFSService;
import org.uberfire.java.nio.file.FileAlreadyExistsException;
import org.uberfire.workbench.events.NotificationEvent;
@WebServlet(displayName = "JbpmServiceRepository", name = "JbpmServiceRepositoryServlet",
urlPatterns = "/jbpmservicerepo")
public class JbpmServiceRepositoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger _logger = LoggerFactory
.getLogger(JbpmServiceRepositoryServlet.class);
private static final String displayRepoContent = "display";
private static final String installRepoContent = "install";
private IDiagramProfile profile;
// this is here just for unit testing purpose
public void setProfile(IDiagramProfile profile) {
this.profile = profile;
}
@Inject
private IDiagramProfileService _profileService = null;
@Inject
private Event<DesignerWorkitemInstalledEvent> workitemInstalledEventEvent;
@Inject
private Event<NotificationEvent> notification;
@Inject
private VFSService vfsServices;
@Inject
private POMService pomService;
@Inject
private ModuleService<? extends Module> moduleService;
@Inject
private MetadataService metadataService;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String uuid = Utils.getUUID(req);
String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
String action = req.getParameter("action");
String assetsToInstall = req.getParameter("asset");
String categoryToInstall = req.getParameter("category");
String repoURL = req.getParameter("repourl");
if (repoURL == null || repoURL.length() < 1) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
try {
URL url = new URL(repoURL);
if (!(repoURL.startsWith("file:"))) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setConnectTimeout(5 * 1000);
conn.connect();
if (conn.getResponseCode() != 200) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
}
} catch (Exception e) {
e.printStackTrace();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false||" + e.getMessage());
return;
}
if (repoURL.endsWith("/")) {
repoURL = repoURL.substring(0,
repoURL.length() - 1);
}
if (profile == null) {
profile = _profileService.findProfile(req,
profileName);
}
Repository repository = profile.getRepository();
Map<String, WorkDefinitionImpl> workitemsFromRepo = WorkItemRepository.getWorkDefinitions(repoURL);
if (action != null && action.equalsIgnoreCase(displayRepoContent)) {
if (workitemsFromRepo != null && workitemsFromRepo.size() > 0) {
Map<String, List<String>> retMap = new HashMap<String, List<String>>();
for (String key : workitemsFromRepo.keySet()) {
WorkDefinitionImpl wd = workitemsFromRepo.get(key);
List<String> keyList = new ArrayList<String>();
keyList.add(wd.getName() == null ? "" : wd.getName());
keyList.add(wd.getDisplayName() == null ? "" : wd.getDisplayName());
if (wd.getIcon() != null && wd.getIcon().trim().length() > 0) {
if (repoURL.startsWith("file:")) {
keyList.add(getFileIconEncoded(repoURL + "/" + wd.getName() + "/" + wd.getIcon()));
} else {
keyList.add(repoURL + "/" + wd.getName() + "/" + wd.getIcon());
}
} else {
_logger.warn("No icon specified. Showing default");
keyList.add(getFileIconEncoded(""));
}
keyList.add(wd.getCategory() == null ? "" : wd.getCategory());
keyList.add(wd.getExplanationText() == null ? "" : wd.getExplanationText());
keyList.add(repoURL + "/" + wd.getDocumentation());
StringBuffer bn = new StringBuffer();
if (wd.getParameterNames() != null) {
String delim = "";
for (String name : wd.getParameterNames()) {
bn.append(delim).append(name);
delim = ",";
}
}
keyList.add(bn.toString());
StringBuffer br = new StringBuffer();
if (wd.getResultNames() != null) {
String delim = "";
for (String resName : wd.getResultNames()) {
br.append(delim).append(resName);
delim = ",";
}
}
keyList.add(br.toString());
keyList.add(wd.getDefaultHandler() == null ? "" : wd.getDefaultHandler());
retMap.put(key,
keyList);
}
JSONObject jsonObject = new JSONObject();
for (Entry<String, List<String>> retMapKey : retMap.entrySet()) {
try {
if (retMapKey != null && retMapKey.getKey() != null) {
jsonObject.put(retMapKey.getKey(),
retMapKey.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write(jsonObject.toString());
} else {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
} else if (action != null && action.equalsIgnoreCase(installRepoContent)) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
if (workitemsFromRepo != null && workitemsFromRepo.size() > 0) {
for (String key : workitemsFromRepo.keySet()) {
if (key != null &&
key.equals(assetsToInstall) &&
categoryToInstall.equals(workitemsFromRepo.get(key).getCategory())) {
try {
ServiceRepoUtils.installWorkItem(workitemsFromRepo,
key,
uuid,
repository,
vfsServices,
workitemInstalledEventEvent,
notification,
pomService,
moduleService,
metadataService);
} catch (FileAlreadyExistsException e) {
_logger.warn("Workitem already installed.");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("alreadyinstalled");
return;
}
}
}
} else {
_logger.error("Invalid or empty service repository.");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
}
}
private String getFileIconEncoded(String fileIconPath) {
try {
return javax.xml.bind.DatatypeConverter.printBase64Binary(
IOUtils.toByteArray(new FileInputStream(new File(fileIconPath.substring(5))))
);
} catch (Exception e) {
try {
// return default service icon
String defaultServiceNodeIcon = getServletContext().getRealPath(ConfigurationProvider.getInstance().getDesignerContext() + "/defaults/defaultservicenodeicon.png");
return javax.xml.bind.DatatypeConverter.printBase64Binary(
IOUtils.toByteArray(new FileInputStream(new File(defaultServiceNodeIcon)))
);
} catch (Exception ee) {
_logger.error("Unable to load workitem icon: " + ee.getMessage());
return "";
}
}
}
}
|
jbpm-designer-backend/src/main/java/org/jbpm/designer/web/server/JbpmServiceRepositoryServlet.java
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.designer.web.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.guvnor.common.services.project.model.Module;
import org.guvnor.common.services.project.service.ModuleService;
import org.guvnor.common.services.project.service.POMService;
import org.guvnor.common.services.shared.metadata.MetadataService;
import org.jbpm.designer.notification.DesignerWorkitemInstalledEvent;
import org.jbpm.designer.repository.Repository;
import org.jbpm.designer.util.ConfigurationProvider;
import org.jbpm.designer.util.Utils;
import org.jbpm.designer.web.profile.IDiagramProfile;
import org.jbpm.designer.web.profile.IDiagramProfileService;
import org.jbpm.process.workitem.WorkDefinitionImpl;
import org.jbpm.process.workitem.WorkItemRepository;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.vfs.VFSService;
import org.uberfire.java.nio.file.FileAlreadyExistsException;
import org.uberfire.workbench.events.NotificationEvent;
@WebServlet(displayName = "JbpmServiceRepository", name = "JbpmServiceRepositoryServlet",
urlPatterns = "/jbpmservicerepo")
public class JbpmServiceRepositoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger _logger = LoggerFactory
.getLogger(JbpmServiceRepositoryServlet.class);
private static final String displayRepoContent = "display";
private static final String installRepoContent = "install";
private IDiagramProfile profile;
// this is here just for unit testing purpose
public void setProfile(IDiagramProfile profile) {
this.profile = profile;
}
@Inject
private IDiagramProfileService _profileService = null;
@Inject
private Event<DesignerWorkitemInstalledEvent> workitemInstalledEventEvent;
@Inject
private Event<NotificationEvent> notification;
@Inject
private VFSService vfsServices;
@Inject
private POMService pomService;
@Inject
private ModuleService<? extends Module> moduleService;
@Inject
private MetadataService metadataService;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String uuid = Utils.getUUID(req);
String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
String action = req.getParameter("action");
String assetsToInstall = req.getParameter("asset");
String categoryToInstall = req.getParameter("category");
String repoURL = req.getParameter("repourl");
if (repoURL == null || repoURL.length() < 1) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
try {
URL url = new URL(repoURL);
if (!(repoURL.startsWith("file:"))) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setConnectTimeout(5 * 1000);
conn.connect();
if (conn.getResponseCode() != 200) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
}
} catch (Exception e) {
e.printStackTrace();
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false||" + e.getMessage());
return;
}
if (repoURL.endsWith("/")) {
repoURL = repoURL.substring(0,
repoURL.length() - 1);
}
if (profile == null) {
profile = _profileService.findProfile(req,
profileName);
}
Repository repository = profile.getRepository();
Map<String, WorkDefinitionImpl> workitemsFromRepo = WorkItemRepository.getWorkDefinitions(repoURL);
if (action != null && action.equalsIgnoreCase(displayRepoContent)) {
if (workitemsFromRepo != null && workitemsFromRepo.size() > 0) {
Map<String, List<String>> retMap = new HashMap<String, List<String>>();
for (String key : workitemsFromRepo.keySet()) {
WorkDefinitionImpl wd = workitemsFromRepo.get(key);
List<String> keyList = new ArrayList<String>();
keyList.add(wd.getName() == null ? "" : wd.getName());
keyList.add(wd.getDisplayName() == null ? "" : wd.getDisplayName());
if (wd.getIcon() != null && wd.getIcon().trim().length() > 0) {
if (repoURL.startsWith("file:")) {
keyList.add(getFileIconEncoded(repoURL + "/" + wd.getName() + "/" + wd.getIcon()));
} else {
keyList.add(repoURL + "/" + wd.getName() + "/" + wd.getIcon());
}
} else {
_logger.warn("No icon specified. Showing default");
keyList.add(getFileIconEncoded(""));
}
keyList.add(wd.getCategory() == null ? "" : wd.getCategory());
keyList.add(wd.getExplanationText() == null ? "" : wd.getExplanationText());
keyList.add(repoURL + "/" + wd.getName() + "/" + wd.getDocumentation());
StringBuffer bn = new StringBuffer();
if (wd.getParameterNames() != null) {
String delim = "";
for (String name : wd.getParameterNames()) {
bn.append(delim).append(name);
delim = ",";
}
}
keyList.add(bn.toString());
StringBuffer br = new StringBuffer();
if (wd.getResultNames() != null) {
String delim = "";
for (String resName : wd.getResultNames()) {
br.append(delim).append(resName);
delim = ",";
}
}
keyList.add(br.toString());
keyList.add(wd.getDefaultHandler() == null ? "" : wd.getDefaultHandler());
retMap.put(key,
keyList);
}
JSONObject jsonObject = new JSONObject();
for (Entry<String, List<String>> retMapKey : retMap.entrySet()) {
try {
if (retMapKey != null && retMapKey.getKey() != null) {
jsonObject.put(retMapKey.getKey(),
retMapKey.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write(jsonObject.toString());
} else {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
} else if (action != null && action.equalsIgnoreCase(installRepoContent)) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
if (workitemsFromRepo != null && workitemsFromRepo.size() > 0) {
for (String key : workitemsFromRepo.keySet()) {
if (key != null &&
key.equals(assetsToInstall) &&
categoryToInstall.equals(workitemsFromRepo.get(key).getCategory())) {
try {
ServiceRepoUtils.installWorkItem(workitemsFromRepo,
key,
uuid,
repository,
vfsServices,
workitemInstalledEventEvent,
notification,
pomService,
moduleService,
metadataService);
} catch (FileAlreadyExistsException e) {
_logger.warn("Workitem already installed.");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("alreadyinstalled");
return;
}
}
}
} else {
_logger.error("Invalid or empty service repository.");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write("false");
return;
}
}
}
private String getFileIconEncoded(String fileIconPath) {
try {
return javax.xml.bind.DatatypeConverter.printBase64Binary(
IOUtils.toByteArray(new FileInputStream(new File(fileIconPath.substring(5))))
);
} catch (Exception e) {
try {
// return default service icon
String defaultServiceNodeIcon = getServletContext().getRealPath(ConfigurationProvider.getInstance().getDesignerContext() + "/defaults/defaultservicenodeicon.png");
return javax.xml.bind.DatatypeConverter.printBase64Binary(
IOUtils.toByteArray(new FileInputStream(new File(defaultServiceNodeIcon)))
);
} catch (Exception ee) {
_logger.error("Unable to load workitem icon: " + ee.getMessage());
return "";
}
}
}
}
|
fixes for service repository install (#771)
|
jbpm-designer-backend/src/main/java/org/jbpm/designer/web/server/JbpmServiceRepositoryServlet.java
|
fixes for service repository install (#771)
|
|
Java
|
apache-2.0
|
b0d627c71fc222f8e8685e341c678fe1b5a7f9ae
| 0
|
ghoullier/cometd,cometd/cometd,cometd/cometd,ghoullier/cometd,ghoullier/cometd,cometd/cometd,cometd/cometd
|
/*
* Copyright (c) 2011 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.cometd.websocket.client;
import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Message.Mutable;
import org.cometd.client.transport.HttpClientTransport;
import org.cometd.client.transport.MessageClientTransport;
import org.cometd.client.transport.TransportListener;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocket.Connection;
import org.eclipse.jetty.websocket.WebSocketClient;
import org.eclipse.jetty.websocket.WebSocketClientFactory;
public class WebSocketTransport extends HttpClientTransport implements MessageClientTransport
{
public final static String PREFIX = "ws";
public final static String NAME = "websocket";
public final static String PROTOCOL_OPTION = "protocol";
public final static String CONNECT_TIMEOUT_OPTION = "connectTimeout";
public final static String IDLE_TIMEOUT_OPTION = "idleTimeout";
public final static String MAX_MESSAGE_SIZE_OPTION = "maxMessageSize";
public final static String UNIQUE_MESSAGE_ID_GUARANTEED_OPTION = "uniqueMessageIdGuaranteed";
public static WebSocketTransport create(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory)
{
return create(options, webSocketClientFactory, null);
}
public static WebSocketTransport create(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory, ScheduledExecutorService scheduler)
{
WebSocketTransport transport = new WebSocketTransport(options, webSocketClientFactory, scheduler);
if (!webSocketClientFactory.isStarted())
{
try
{
webSocketClientFactory.start();
}
catch (Exception x)
{
throw new RuntimeException(x);
}
}
return transport;
}
private final WebSocket _websocket = new CometDWebSocket();
private final Map<String, WebSocketExchange> _metaExchanges = new ConcurrentHashMap<String, WebSocketExchange>();
private final Map<String, List<WebSocketExchange>> _exchanges = new HashMap<String, List<WebSocketExchange>>();
private final WebSocketClientFactory _webSocketClientFactory;
private volatile ScheduledExecutorService _scheduler;
private volatile boolean _shutdownScheduler;
private volatile String _protocol = "cometd";
private volatile long _maxNetworkDelay = 15000L;
private volatile long _connectTimeout = 30000L;
private volatile int _idleTimeout = 60000;
private volatile int _maxMessageSize;
private volatile boolean _uniqueMessageId = true;
private volatile boolean _connected;
private volatile boolean _disconnected;
private volatile boolean _aborted;
private volatile boolean _webSocketSupported = true;
private volatile WebSocket.Connection _connection;
private volatile TransportListener _listener;
private volatile Map<String, Object> _advice;
public WebSocketTransport(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory, ScheduledExecutorService scheduler)
{
super(NAME, options);
_webSocketClientFactory = webSocketClientFactory;
_scheduler = scheduler;
setOptionPrefix(PREFIX);
}
public void setMessageTransportListener(TransportListener listener)
{
_listener = listener;
}
public boolean accept(String version)
{
return _webSocketSupported;
}
@Override
public void init()
{
super.init();
_aborted = false;
_protocol = getOption(PROTOCOL_OPTION, _protocol);
_maxNetworkDelay = getOption(MAX_NETWORK_DELAY_OPTION, _maxNetworkDelay);
_connectTimeout = getOption(CONNECT_TIMEOUT_OPTION, _connectTimeout);
_idleTimeout = getOption(IDLE_TIMEOUT_OPTION, _idleTimeout);
_maxMessageSize = getOption(MAX_MESSAGE_SIZE_OPTION, _webSocketClientFactory.getBufferSize());
_uniqueMessageId = getOption(UNIQUE_MESSAGE_ID_GUARANTEED_OPTION, _uniqueMessageId);
if (_scheduler == null)
{
_shutdownScheduler = true;
_scheduler = Executors.newSingleThreadScheduledExecutor();
}
}
private long getMaxNetworkDelay()
{
return _maxNetworkDelay;
}
private long getConnectTimeout()
{
return _connectTimeout;
}
@Override
public void abort()
{
_aborted = true;
disconnect("Aborted");
reset();
}
@Override
public void reset()
{
super.reset();
if (_shutdownScheduler)
{
_shutdownScheduler = false;
_scheduler.shutdown();
_scheduler = null;
}
}
@Override
public void terminate()
{
super.terminate();
disconnect("Terminated");
}
protected void disconnect(String reason)
{
Connection connection = _connection;
_connection = null;
if (connection != null && connection.isOpen())
{
debug("Closing websocket connection {}", connection);
connection.close(1000, reason);
}
}
@Override
public void send(TransportListener listener, Message.Mutable... messages)
{
if (_aborted)
throw new IllegalStateException("Aborted");
try
{
Connection connection = connect(listener, messages);
if (connection == null)
return;
for (Message.Mutable message : messages)
registerMessage(message, listener);
String content = generateJSON(messages);
debug("Sending messages {}", content);
// The onSending() callback must be invoked before the actual send
// otherwise we may have a race condition where the response is so
// fast that it arrives before the onSending() is called.
listener.onSending(messages);
connection.sendMessage(content);
}
catch (Exception x)
{
complete(messages);
listener.onException(x, messages);
}
}
private Connection connect(TransportListener listener, Mutable[] messages)
{
Connection connection = _connection;
if (connection != null)
return connection;
try
{
// Mangle the URL
String url = getURL();
url = url.replaceFirst("^http", "ws");
URI uri = new URI(url);
debug("Opening websocket connection to {}", uri);
// Prepare the cookies
Map<String, String> cookies = new HashMap<String, String>();
for (Cookie cookie : getCookieProvider().getCookies())
cookies.put(cookie.getName(), cookie.getValue());
WebSocketClient client = newWebSocketClient();
client.setProtocol(_protocol);
client.getCookies().putAll(cookies);
_connection = client.open(uri, _websocket, getConnectTimeout(), TimeUnit.MILLISECONDS);
if (_aborted)
{
listener.onException(new IOException("Aborted"), messages);
}
return _connection;
}
catch (ConnectException x)
{
listener.onConnectException(x, messages);
}
catch (SocketTimeoutException x)
{
listener.onConnectException(x, messages);
}
catch (TimeoutException x)
{
listener.onConnectException(x, messages);
}
catch (URISyntaxException x)
{
_webSocketSupported = false;
listener.onProtocolError(x.getMessage(), messages);
}
catch (InterruptedException x)
{
_webSocketSupported = false;
listener.onException(x, messages);
}
catch (ProtocolException x)
{
_webSocketSupported = false;
listener.onProtocolError(x.getMessage(), messages);
}
catch (IOException x)
{
_webSocketSupported = false;
listener.onException(x, messages);
}
return _connection;
}
protected WebSocketClient newWebSocketClient()
{
WebSocketClient result = _webSocketClientFactory.newWebSocketClient();
result.setMaxTextMessageSize(_maxMessageSize);
result.setMaxIdleTime(_idleTimeout);
return result;
}
private void complete(Message.Mutable[] messages)
{
for (Message.Mutable message : messages)
deregisterMessage(message);
}
private void registerMessage(final Message.Mutable message, final TransportListener listener)
{
// Calculate max network delay
long maxNetworkDelay = getMaxNetworkDelay();
if (Channel.META_CONNECT.equals(message.getChannel()))
{
Map<String, Object> advice = message.getAdvice();
if (advice == null)
advice = _advice;
if (advice != null)
{
Object timeout = advice.get("timeout");
if (timeout instanceof Number)
maxNetworkDelay += ((Number)timeout).intValue();
else if (timeout != null)
maxNetworkDelay += Integer.parseInt(timeout.toString());
}
_connected = true;
}
// Schedule a task to expire if the maxNetworkDelay elapses
final long expiration = System.currentTimeMillis() + maxNetworkDelay;
ScheduledFuture<?> task = _scheduler.schedule(new Runnable()
{
public void run()
{
long now = System.currentTimeMillis();
long jitter = now - expiration;
if (jitter > 5000) // TODO: make the max jitter a parameter ?
debug("Expired too late {} for {}", jitter, message);
// Notify only if we won the race to deregister the message
WebSocketExchange exchange = deregisterMessage(message);
if (exchange != null)
listener.onExpire(new Message[]{message});
}
}, maxNetworkDelay, TimeUnit.MILLISECONDS);
// Register the exchange
// Message responses must have the same messageId as the requests
// Meta messages have unique messageIds, but this may not be true
// for publish messages where the application can specify its own
// messageId, so we need to take that in account
WebSocketExchange exchange = new WebSocketExchange(message, listener, task);
debug("Registering {}", exchange);
if (_uniqueMessageId || message.isMeta())
{
Object existing = _metaExchanges.put(message.getId(), exchange);
// Paranoid check
if (existing != null)
throw new IllegalStateException();
}
else
{
synchronized (this)
{
List<WebSocketExchange> exchanges = _exchanges.get(message.getId());
if (exchanges == null)
{
exchanges = new LinkedList<WebSocketExchange>();
Object existing = _exchanges.put(message.getId(), exchanges);
// Paranoid check
if (existing != null)
throw new IllegalStateException();
}
exchanges.add(exchange);
}
}
}
private WebSocketExchange deregisterMessage(Message message)
{
WebSocketExchange exchange = null;
if (_uniqueMessageId || message.isMeta())
{
exchange = _metaExchanges.remove(message.getId());
if (Channel.META_CONNECT.equals(message.getChannel()))
_connected = false;
else if (Channel.META_DISCONNECT.equals(message.getChannel()))
_disconnected = true;
}
else
{
// Check if it is a publish reply
if (isPublishReply(message))
{
synchronized (this)
{
List<WebSocketExchange> exchanges = _exchanges.get(message.getId());
if (exchanges != null)
{
for (int i = 0; i < exchanges.size(); ++i)
{
WebSocketExchange x = exchanges.get(i);
if (message.getChannel().equals(x.message.getChannel()))
{
exchanges.remove(x);
if (exchanges.isEmpty())
_exchanges.remove(message.getId());
exchange = x;
break;
}
}
}
}
}
}
debug("Deregistering {} for message {}", exchange, message);
if (exchange != null)
exchange.task.cancel(false);
return exchange;
}
private boolean isReply(Message message)
{
return message.isMeta() || isPublishReply(message);
}
private boolean isPublishReply(Message message)
{
return !message.containsKey(Message.DATA_FIELD) && !message.isMeta();
}
private void failMessages(Throwable cause)
{
List<WebSocketExchange> exchanges = new ArrayList<WebSocketExchange>(_metaExchanges.values());
for (WebSocketExchange exchange : exchanges)
{
deregisterMessage(exchange.message);
exchange.listener.onException(cause, new Message[]{exchange.message});
}
if (!_uniqueMessageId)
{
exchanges = new ArrayList<WebSocketExchange>();
synchronized (this)
{
for (List<WebSocketExchange> exchangeList : _exchanges.values())
{
exchanges.addAll(exchangeList);
for (WebSocketExchange exchange : exchangeList)
deregisterMessage(exchange.message);
}
}
for (WebSocketExchange exchange : exchanges)
exchange.listener.onException(cause, new Message[]{exchange.message});
}
}
protected void onMessages(List<Mutable> messages)
{
for (Mutable message : messages)
{
if (isReply(message))
{
// Remembering the advice must be done before we notify listeners
// otherwise we risk that listeners send a connect message that does
// not take into account the timeout to calculate the maxNetworkDelay
if (Channel.META_CONNECT.equals(message.getChannel()) && message.isSuccessful())
{
Map<String, Object> advice = message.getAdvice();
if (advice != null)
{
// Remember the advice so that we can properly calculate the max network delay
if (advice.get(Message.TIMEOUT_FIELD) != null)
_advice = advice;
}
}
WebSocketExchange exchange = deregisterMessage(message);
if (exchange != null)
{
exchange.listener.onMessages(Collections.singletonList(message));
}
else
{
// If the exchange is missing, then the message has expired, and we do not notify
debug("Could not find request for reply {}", message);
}
if (_disconnected && !_connected)
disconnect("Disconnect");
}
else
{
_listener.onMessages(Collections.singletonList(message));
}
}
}
protected class CometDWebSocket implements WebSocket.OnTextMessage
{
public void onOpen(Connection connection)
{
debug("Opened websocket connection {}", connection);
}
public void onClose(int closeCode, String message)
{
Connection connection = _connection;
_connection = null;
debug("Closed websocket connection with code {} {}: {} ", closeCode, message, connection);
failMessages(new EOFException("Connection closed " + closeCode + " " + message));
}
public void onMessage(String data)
{
try
{
List<Mutable> messages = parseMessages(data);
debug("Received messages {}", data);
onMessages(messages);
}
catch (ParseException x)
{
_listener.onException(x, new Message[0]);
}
}
}
private static class WebSocketExchange
{
private final Mutable message;
private final TransportListener listener;
private final ScheduledFuture<?> task;
public WebSocketExchange(Mutable message, TransportListener listener, ScheduledFuture<?> task)
{
this.message = message;
this.listener = listener;
this.task = task;
}
@Override
public String toString()
{
return getClass().getSimpleName() + " " + message;
}
}
}
|
cometd-java/cometd-websocket-jetty/src/main/java/org/cometd/websocket/client/WebSocketTransport.java
|
/*
* Copyright (c) 2011 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.cometd.websocket.client;
import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Message.Mutable;
import org.cometd.client.transport.HttpClientTransport;
import org.cometd.client.transport.MessageClientTransport;
import org.cometd.client.transport.TransportListener;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocket.Connection;
import org.eclipse.jetty.websocket.WebSocketClient;
import org.eclipse.jetty.websocket.WebSocketClientFactory;
public class WebSocketTransport extends HttpClientTransport implements MessageClientTransport
{
public final static String PREFIX = "ws";
public final static String NAME = "websocket";
public final static String PROTOCOL_OPTION = "protocol";
public final static String CONNECT_TIMEOUT_OPTION = "connectTimeout";
public final static String IDLE_TIMEOUT_OPTION = "idleTimeout";
public final static String MAX_MESSAGE_SIZE_OPTION = "maxMessageSize";
public final static String UNIQUE_MESSAGE_ID_GUARANTEED_OPTION = "uniqueMessageIdGuaranteed";
public static WebSocketTransport create(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory)
{
return create(options, webSocketClientFactory, null);
}
public static WebSocketTransport create(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory, ScheduledExecutorService scheduler)
{
WebSocketTransport transport = new WebSocketTransport(options, webSocketClientFactory, scheduler);
if (!webSocketClientFactory.isStarted())
{
try
{
webSocketClientFactory.start();
}
catch (Exception x)
{
throw new RuntimeException(x);
}
}
return transport;
}
private final WebSocket _websocket = new CometDWebSocket();
private final Map<String, WebSocketExchange> _metaExchanges = new ConcurrentHashMap<String, WebSocketExchange>();
private final Map<String, List<WebSocketExchange>> _exchanges = new HashMap<String, List<WebSocketExchange>>();
private final WebSocketClientFactory _webSocketClientFactory;
private volatile ScheduledExecutorService _scheduler;
private volatile boolean _shutdownScheduler;
private volatile String _protocol = "cometd";
private volatile long _maxNetworkDelay = 15000L;
private volatile long _connectTimeout = 30000L;
private volatile int _idleTimeout = 60000;
private volatile int _maxMessageSize;
private volatile boolean _uniqueMessageId = true;
private volatile boolean _connected;
private volatile boolean _disconnected;
private volatile boolean _aborted;
private volatile boolean _webSocketSupported = true;
private volatile WebSocket.Connection _connection;
private volatile TransportListener _listener;
private volatile Map<String, Object> _advice;
public WebSocketTransport(Map<String, Object> options, WebSocketClientFactory webSocketClientFactory, ScheduledExecutorService scheduler)
{
super(NAME, options);
_webSocketClientFactory = webSocketClientFactory;
_scheduler = scheduler;
setOptionPrefix(PREFIX);
}
public void setMessageTransportListener(TransportListener listener)
{
_listener = listener;
}
public boolean accept(String version)
{
return _webSocketSupported;
}
@Override
public void init()
{
super.init();
_aborted = false;
_protocol = getOption(PROTOCOL_OPTION, _protocol);
_maxNetworkDelay = getOption(MAX_NETWORK_DELAY_OPTION, _maxNetworkDelay);
_connectTimeout = getOption(CONNECT_TIMEOUT_OPTION, _connectTimeout);
_idleTimeout = getOption(IDLE_TIMEOUT_OPTION, _idleTimeout);
_maxMessageSize = getOption(MAX_MESSAGE_SIZE_OPTION, _webSocketClientFactory.getBufferSize());
_uniqueMessageId = getOption(UNIQUE_MESSAGE_ID_GUARANTEED_OPTION, _uniqueMessageId);
if (_scheduler == null)
{
_shutdownScheduler = true;
_scheduler = Executors.newSingleThreadScheduledExecutor();
}
}
private long getMaxNetworkDelay()
{
return _maxNetworkDelay;
}
private long getConnectTimeout()
{
return _connectTimeout;
}
@Override
public void abort()
{
_aborted = true;
disconnect("Aborted");
reset();
}
@Override
public void reset()
{
super.reset();
if (_shutdownScheduler)
{
_shutdownScheduler = false;
_scheduler.shutdown();
_scheduler = null;
}
}
@Override
public void terminate()
{
super.terminate();
disconnect("Terminated");
}
protected void disconnect(String reason)
{
Connection connection = _connection;
_connection = null;
if (connection != null && connection.isOpen())
{
debug("Closing websocket connection {}", connection);
connection.close(1000, reason);
}
}
@Override
public void send(TransportListener listener, Message.Mutable... messages)
{
if (_aborted)
throw new IllegalStateException("Aborted");
try
{
Connection connection = connect(listener, messages);
if (connection == null)
return;
for (Message.Mutable message : messages)
registerMessage(message, listener);
String content = generateJSON(messages);
debug("Sending messages {}", content);
// The onSending() callback must be invoked before the actual send
// otherwise we may have a race condition where the response is so
// fast that it arrives before the onSending() is called.
listener.onSending(messages);
connection.sendMessage(content);
}
catch (Exception x)
{
complete(messages);
listener.onException(x, messages);
}
}
private Connection connect(TransportListener listener, Mutable[] messages)
{
Connection connection = _connection;
if (connection != null)
return connection;
try
{
// Mangle the URL
String url = getURL();
url = url.replaceFirst("^http", "ws");
URI uri = new URI(url);
debug("Opening websocket connection to {}", uri);
// Prepare the cookies
Map<String, String> cookies = new HashMap<String, String>();
for (Cookie cookie : getCookieProvider().getCookies())
cookies.put(cookie.getName(), cookie.getValue());
WebSocketClient client = newWebSocketClient();
client.setProtocol(_protocol);
client.getCookies().putAll(cookies);
_connection = client.open(uri, _websocket, getConnectTimeout(), TimeUnit.MILLISECONDS);
if (_aborted)
{
listener.onException(new IOException("Aborted"), messages);
}
return _connection;
}
catch (ConnectException x)
{
listener.onConnectException(x, messages);
}
catch (SocketTimeoutException x)
{
listener.onConnectException(x, messages);
}
catch (TimeoutException x)
{
listener.onConnectException(x, messages);
}
catch (URISyntaxException x)
{
_webSocketSupported = false;
listener.onProtocolError(x.getMessage(), messages);
}
catch (InterruptedException x)
{
_webSocketSupported = false;
listener.onException(x, messages);
}
catch (ProtocolException x)
{
_webSocketSupported = false;
listener.onProtocolError(x.getMessage(), messages);
}
catch (IOException x)
{
_webSocketSupported = false;
listener.onException(x, messages);
}
return _connection;
}
protected WebSocketClient newWebSocketClient()
{
WebSocketClient result = _webSocketClientFactory.newWebSocketClient();
result.setMaxTextMessageSize(_maxMessageSize);
result.setMaxIdleTime(_idleTimeout);
return result;
}
private void complete(Message.Mutable[] messages)
{
for (Message.Mutable message : messages)
deregisterMessage(message);
}
private void registerMessage(final Message.Mutable message, final TransportListener listener)
{
// Calculate max network delay
long maxNetworkDelay = getMaxNetworkDelay();
if (Channel.META_CONNECT.equals(message.getChannel()))
{
Map<String, Object> advice = message.getAdvice();
if (advice == null)
advice = _advice;
if (advice != null)
{
Object timeout = advice.get("timeout");
if (timeout instanceof Number)
maxNetworkDelay += ((Number)timeout).intValue();
else if (timeout != null)
maxNetworkDelay += Integer.parseInt(timeout.toString());
}
_connected = true;
}
// Schedule a task to expire if the maxNetworkDelay elapses
final long expiration = System.currentTimeMillis() + maxNetworkDelay;
ScheduledFuture<?> task = _scheduler.schedule(new Runnable()
{
public void run()
{
long now = System.currentTimeMillis();
long jitter = now - expiration;
if (jitter > 5000) // TODO: make the max jitter a parameter ?
debug("Expired too late {} for {}", jitter, message);
// Notify only if we won the race to deregister the message
WebSocketExchange exchange = deregisterMessage(message);
if (exchange != null)
listener.onExpire(new Message[]{message});
}
}, maxNetworkDelay, TimeUnit.MILLISECONDS);
// Register the exchange
// Message responses must have the same messageId as the requests
// Meta messages have unique messageIds, but this may not be true
// for publish messages where the application can specify its own
// messageId, so we need to take that in account
WebSocketExchange exchange = new WebSocketExchange(message, listener, task);
debug("Registering {}", exchange);
if (_uniqueMessageId || message.isMeta())
{
Object existing = _metaExchanges.put(message.getId(), exchange);
// Paranoid check
if (existing != null)
throw new IllegalStateException();
}
else
{
synchronized (this)
{
List<WebSocketExchange> exchanges = _exchanges.get(message.getId());
if (exchanges == null)
{
exchanges = new LinkedList<WebSocketExchange>();
Object existing = _exchanges.put(message.getId(), exchanges);
// Paranoid check
if (existing != null)
throw new IllegalStateException();
}
exchanges.add(exchange);
}
}
}
private WebSocketExchange deregisterMessage(Message message)
{
WebSocketExchange exchange = null;
if (_uniqueMessageId || message.isMeta())
{
exchange = _metaExchanges.remove(message.getId());
if (Channel.META_CONNECT.equals(message.getChannel()))
_connected = false;
else if (Channel.META_DISCONNECT.equals(message.getChannel()))
_disconnected = true;
}
else
{
// Check if it is a publish reply
if (isPublishReply(message))
{
synchronized (this)
{
List<WebSocketExchange> exchanges = _exchanges.get(message.getId());
if (exchanges != null)
{
for (int i = 0; i < exchanges.size(); ++i)
{
WebSocketExchange x = exchanges.get(i);
if (message.getChannel().equals(x.message.getChannel()))
{
exchanges.remove(x);
if (exchanges.isEmpty())
_exchanges.remove(message.getId());
exchange = x;
break;
}
}
}
}
}
}
debug("Deregistering {} for message {}", exchange, message);
if (exchange != null)
exchange.task.cancel(false);
return exchange;
}
private boolean isReply(Message message)
{
return message.isMeta() || isPublishReply(message);
}
private boolean isPublishReply(Message message)
{
return !message.containsKey(Message.DATA_FIELD) && !message.isMeta();
}
private void failMessages(Throwable cause)
{
List<WebSocketExchange> exchanges = new ArrayList<WebSocketExchange>(_metaExchanges.values());
for (WebSocketExchange exchange : exchanges)
{
deregisterMessage(exchange.message);
exchange.listener.onException(cause, new Message[]{exchange.message});
}
if (!_uniqueMessageId)
{
exchanges = new ArrayList<WebSocketExchange>();
synchronized (this)
{
for (List<WebSocketExchange> exchangeList : _exchanges.values())
{
exchanges.addAll(exchangeList);
for (WebSocketExchange exchange : exchangeList)
deregisterMessage(exchange.message);
}
}
for (WebSocketExchange exchange : exchanges)
exchange.listener.onException(cause, new Message[]{exchange.message});
}
}
protected void onMessages(List<Mutable> messages)
{
for (Mutable message : messages)
{
if (isReply(message))
{
WebSocketExchange exchange = deregisterMessage(message);
if (exchange != null)
{
exchange.listener.onMessages(Collections.singletonList(message));
}
else
{
// If the exchange is missing, then the message has expired, and we do not notify
debug("Could not find request for reply {}", message);
}
if (Channel.META_CONNECT.equals(message.getChannel()) && message.isSuccessful())
{
Map<String, Object> advice = message.getAdvice();
if (advice != null)
{
// Remember the advice so that we can properly calculate the max network delay
if (advice.get(Message.TIMEOUT_FIELD) != null)
_advice = advice;
}
}
if (_disconnected && !_connected)
disconnect("Disconnect");
}
else
{
_listener.onMessages(Collections.singletonList(message));
}
}
}
protected class CometDWebSocket implements WebSocket.OnTextMessage
{
public void onOpen(Connection connection)
{
debug("Opened websocket connection {}", connection);
}
public void onClose(int closeCode, String message)
{
Connection connection = _connection;
_connection = null;
debug("Closed websocket connection with code {} {}: {} ", closeCode, message, connection);
failMessages(new EOFException("Connection closed " + closeCode + " " + message));
}
public void onMessage(String data)
{
try
{
List<Mutable> messages = parseMessages(data);
debug("Received messages {}", data);
onMessages(messages);
}
catch (ParseException x)
{
_listener.onException(x, new Message[0]);
}
}
}
private static class WebSocketExchange
{
private final Mutable message;
private final TransportListener listener;
private final ScheduledFuture<?> task;
public WebSocketExchange(Mutable message, TransportListener listener, ScheduledFuture<?> task)
{
this.message = message;
this.listener = listener;
this.task = task;
}
@Override
public String toString()
{
return getClass().getSimpleName() + " " + message;
}
}
}
|
Advice must be remembered before notifying listeners.
|
cometd-java/cometd-websocket-jetty/src/main/java/org/cometd/websocket/client/WebSocketTransport.java
|
Advice must be remembered before notifying listeners.
|
|
Java
|
apache-2.0
|
e70fea64fb92d9ee8e5038e31af818094b57952f
| 0
|
nicolas-raoul/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,commons-app/apps-android-commons,neslihanturan/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,nicolas-raoul/apps-android-commons,maskaravivek/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons,nicolas-raoul/apps-android-commons,commons-app/apps-android-commons,commons-app/apps-android-commons,neslihanturan/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,domdomegg/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,nicolas-raoul/apps-android-commons,maskaravivek/apps-android-commons,neslihanturan/apps-android-commons,maskaravivek/apps-android-commons,neslihanturan/apps-android-commons,psh/apps-android-commons
|
package fr.free.nrw.commons.review;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.di.CommonsDaggerSupportFragment;
public class ReviewImageFragment extends CommonsDaggerSupportFragment {
static final int CATEGORY = 2;
private static final int SPAM = 0;
private static final int COPYRIGHT = 1;
private static final int THANKS = 3;
private int position;
public ProgressBar progressBar;
@BindView(R.id.tv_review_question)
TextView textViewQuestion;
@BindView(R.id.tv_review_question_context)
TextView textViewQuestionContext;
@BindView(R.id.button_yes)
Button yesButton;
@BindView(R.id.button_no)
Button noButton;
// Constant variable used to store user's key name for onSaveInstanceState method
private final String SAVED_USER = "saved_user";
//Variable that stores the value of user
private String user;
public void update(int position) {
this.position = position;
}
private String updateCategoriesQuestion() {
Media media = getReviewActivity().getMedia();
if (media != null && media.getCategories() != null && isAdded()) {
String catString = TextUtils.join(", ", media.getCategories());
if (catString != null && !catString.equals("") && textViewQuestionContext != null) {
catString = "<b>" + catString + "</b>";
String stringToConvertHtml = String.format(getResources().getString(R.string.review_category_explanation), catString);
return Html.fromHtml(stringToConvertHtml).toString();
}
}
return getResources().getString(R.string.review_no_category);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
position = getArguments().getInt("position");
View layoutView = inflater.inflate(R.layout.fragment_review_image, container,
false);
ButterKnife.bind(this, layoutView);
String question, explanation=null, yesButtonText, noButtonText;
switch (position) {
case SPAM:
question = getString(R.string.review_spam);
explanation = getString(R.string.review_spam_explanation);
yesButtonText = getString(R.string.review_spam_yes_button_text);
noButtonText = getString(R.string.review_spam_no_button_text);
yesButton.setOnClickListener(view -> getReviewActivity()
.reviewController.reportSpam(requireActivity(), getReviewCallback()));
break;
case COPYRIGHT:
enableButtons();
question = getString(R.string.review_copyright);
explanation = getString(R.string.review_copyright_explanation);
yesButtonText = getString(R.string.review_copyright_yes_button_text);
noButtonText = getString(R.string.review_copyright_no_button_text);
yesButton.setOnClickListener(view -> getReviewActivity()
.reviewController
.reportPossibleCopyRightViolation(requireActivity(), getReviewCallback()));
break;
case CATEGORY:
enableButtons();
question = getString(R.string.review_category);
explanation = updateCategoriesQuestion();
yesButtonText = getString(R.string.review_category_yes_button_text);
noButtonText = getString(R.string.review_category_no_button_text);
yesButton.setOnClickListener(view -> {
getReviewActivity()
.reviewController
.reportWrongCategory(requireActivity(), getReviewCallback());
getReviewActivity().swipeToNext();
});
break;
case THANKS:
enableButtons();
question = getString(R.string.review_thanks);
//Get existing user name if it is already saved using savedInstanceState else get from reviewController
if (savedInstanceState == null) {
if (getReviewActivity().reviewController.firstRevision != null) {
user = getReviewActivity().reviewController.firstRevision.getUser();
}
} else {
user = savedInstanceState.getString(SAVED_USER);
}
//if the user is null because of whatsoever reason, review will not be sent anyways
if (!TextUtils.isEmpty(user)) {
explanation = getString(R.string.review_thanks_explanation, user);
}
yesButtonText = getString(R.string.review_thanks_yes_button_text);
noButtonText = getString(R.string.review_thanks_no_button_text);
yesButton.setTextColor(Color.parseColor("#228b22"));
noButton.setTextColor(Color.parseColor("#116aaa"));
yesButton.setOnClickListener(view -> {
getReviewActivity().reviewController.sendThanks(getReviewActivity());
getReviewActivity().swipeToNext();
});
break;
default:
enableButtons();
question = "How did we get here?";
explanation = "No idea.";
yesButtonText = "yes";
noButtonText = "no";
}
textViewQuestion.setText(question);
textViewQuestionContext.setText(explanation);
yesButton.setText(yesButtonText);
noButton.setText(noButtonText);
return layoutView;
}
/**
* This method will be called when configuration changes happen
*
* @param outState
*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
//Save user name when configuration changes happen
outState.putString(SAVED_USER, user);
}
private ReviewController.ReviewCallback getReviewCallback() {
return new ReviewController
.ReviewCallback() {
@Override
public void onSuccess() {
getReviewActivity().runRandomizer();
}
@Override
public void onFailure() {
//do nothing
}
};
}
/**
* This function is called when an image has
* been loaded to enable the review buttons.
*/
public void enableButtons() {
yesButton.setEnabled(true);
yesButton.setAlpha(1);
noButton.setEnabled(true);
noButton.setAlpha(1);
}
/**
* This function is called when an image is being loaded
* to disable the review buttons
*/
public void disableButtons() {
yesButton.setEnabled(false);
yesButton.setAlpha(0.5f);
noButton.setEnabled(false);
noButton.setAlpha(0.5f);
}
@OnClick(R.id.button_no)
void onNoButtonClicked() {
getReviewActivity().swipeToNext();
}
private ReviewActivity getReviewActivity() {
return (ReviewActivity) requireActivity();
}
}
|
app/src/main/java/fr/free/nrw/commons/review/ReviewImageFragment.java
|
package fr.free.nrw.commons.review;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.di.CommonsDaggerSupportFragment;
public class ReviewImageFragment extends CommonsDaggerSupportFragment {
static final int CATEGORY = 2;
private static final int SPAM = 0;
private static final int COPYRIGHT = 1;
private static final int THANKS = 3;
private int position;
public ProgressBar progressBar;
@BindView(R.id.tv_review_question)
TextView textViewQuestion;
@BindView(R.id.tv_review_question_context)
TextView textViewQuestionContext;
@BindView(R.id.button_yes)
Button yesButton;
@BindView(R.id.button_no)
Button noButton;
// Constant variable used to store user's key name for onSaveInstanceState method
private final String SAVED_USER = "saved_user";
//Variable that stores the value of user
private String user;
public void update(int position) {
this.position = position;
}
private String updateCategoriesQuestion() {
Media media = getReviewActivity().getMedia();
if (media != null && media.getCategories() != null && isAdded()) {
String catString = TextUtils.join(", ", media.getCategories());
if (catString != null && !catString.equals("") && textViewQuestionContext != null) {
catString = "<b>" + catString + "</b>";
String stringToConvertHtml = String.format(getResources().getString(R.string.review_category_explanation), catString);
return Html.fromHtml(stringToConvertHtml).toString();
}
}
return getResources().getString(R.string.review_no_category);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
position = getArguments().getInt("position");
View layoutView = inflater.inflate(R.layout.fragment_review_image, container,
false);
ButterKnife.bind(this, layoutView);
String question, explanation=null, yesButtonText, noButtonText;
switch (position) {
case SPAM:
question = getString(R.string.review_spam);
explanation = getString(R.string.review_spam_explanation);
yesButtonText = getString(R.string.review_spam_yes_button_text);
noButtonText = getString(R.string.review_spam_no_button_text);
yesButton.setOnClickListener(view -> getReviewActivity()
.reviewController.reportSpam(requireActivity(), getReviewCallback()));
break;
case COPYRIGHT:
enableButtons();
question = getString(R.string.review_copyright);
explanation = getString(R.string.review_copyright_explanation);
yesButtonText = getString(R.string.review_copyright_yes_button_text);
noButtonText = getString(R.string.review_copyright_no_button_text);
yesButton.setOnClickListener(view -> getReviewActivity()
.reviewController
.reportPossibleCopyRightViolation(requireActivity(), getReviewCallback()));
break;
case CATEGORY:
enableButtons();
question = getString(R.string.review_category);
explanation = updateCategoriesQuestion();
yesButtonText = getString(R.string.review_category_yes_button_text);
noButtonText = getString(R.string.review_category_no_button_text);
yesButton.setOnClickListener(view -> {
getReviewActivity()
.reviewController
.reportWrongCategory(requireActivity(), getReviewCallback());
getReviewActivity().swipeToNext();
});
break;
case THANKS:
enableButtons();
question = getString(R.string.review_thanks);
//Get existing user name if it is already saved using savedInstanceState else get from reviewController
if (savedInstanceState == null) {
if (getReviewActivity().reviewController != null) {
user = getReviewActivity().reviewController.firstRevision.getUser();
}
} else {
user = savedInstanceState.getString(SAVED_USER);
}
//if the user is null because of whatsoever reason, review will not be sent anyways
if (!TextUtils.isEmpty(user)) {
explanation = getString(R.string.review_thanks_explanation, user);
}
yesButtonText = getString(R.string.review_thanks_yes_button_text);
noButtonText = getString(R.string.review_thanks_no_button_text);
yesButton.setTextColor(Color.parseColor("#228b22"));
noButton.setTextColor(Color.parseColor("#116aaa"));
yesButton.setOnClickListener(view -> {
getReviewActivity().reviewController.sendThanks(getReviewActivity());
getReviewActivity().swipeToNext();
});
break;
default:
enableButtons();
question = "How did we get here?";
explanation = "No idea.";
yesButtonText = "yes";
noButtonText = "no";
}
textViewQuestion.setText(question);
textViewQuestionContext.setText(explanation);
yesButton.setText(yesButtonText);
noButton.setText(noButtonText);
return layoutView;
}
/**
* This method will be called when configuration changes happen
*
* @param outState
*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
//Save user name when configuration changes happen
outState.putString(SAVED_USER, user);
}
private ReviewController.ReviewCallback getReviewCallback() {
return new ReviewController
.ReviewCallback() {
@Override
public void onSuccess() {
getReviewActivity().runRandomizer();
}
@Override
public void onFailure() {
//do nothing
}
};
}
/**
* This function is called when an image has
* been loaded to enable the review buttons.
*/
public void enableButtons() {
yesButton.setEnabled(true);
yesButton.setAlpha(1);
noButton.setEnabled(true);
noButton.setAlpha(1);
}
/**
* This function is called when an image is being loaded
* to disable the review buttons
*/
public void disableButtons() {
yesButton.setEnabled(false);
yesButton.setAlpha(0.5f);
noButton.setEnabled(false);
noButton.setAlpha(0.5f);
}
@OnClick(R.id.button_no)
void onNoButtonClicked() {
getReviewActivity().swipeToNext();
}
private ReviewActivity getReviewActivity() {
return (ReviewActivity) requireActivity();
}
}
|
fixed bug: App crashes on viewing review in Review Fragment #4132 (#4146)
* fixed bug:app crashes on viewing review in Review Fragment #4135
|
app/src/main/java/fr/free/nrw/commons/review/ReviewImageFragment.java
|
fixed bug: App crashes on viewing review in Review Fragment #4132 (#4146)
|
|
Java
|
apache-2.0
|
0c822588d7b69ba01cc008374ffd92b8b3c6f049
| 0
|
atlasapi/atlas-deer,atlasapi/atlas-deer
|
package org.atlasapi.application.auth;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigInteger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.atlasapi.application.users.User;
import org.atlasapi.entity.Id;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.metabroadcast.common.ids.NumberToShortStringCodec;
import com.metabroadcast.common.ids.SubstitutionTableNumberCodec;
@RunWith( MockitoJUnitRunner.class )
public class OAuthInterceptorTest {
private final NumberToShortStringCodec idCodec = SubstitutionTableNumberCodec.lowerCaseOnly();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final HttpServletResponse response = mock(HttpServletResponse.class);
private final ServletOutputStream stream = mock(ServletOutputStream.class);
private final UserFetcher userFetcher = mock(UserFetcher.class);
private final User user = User.builder()
.withId(Id.valueOf(new BigInteger("5000")))
.withProfileComplete(false)
.build();
/**
* Test that access is denied to a url under protection if no
* user present
* @throws Exception
*/
@Test
public void testProtectsUrlNoUser() throws Exception {
when(request.getRequestURI()).thenReturn("/myprotectedUrl.json");
when(response.getOutputStream()).thenReturn(stream);
when(userFetcher.userFor(request)).thenReturn(Optional.<User>absent());
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of(""))
.build();
assertFalse(interceptor.preHandle(request, response, null));
}
/**
* Test that a url requiring a completed user profile is not
* accessible to a user with an incomplete profile
* @throws Exception
*/
@Test
public void testProtectsUrlNeedingFullProfile() throws Exception {
when(request.getRequestURI()).thenReturn("/myprotectedUrl.json");
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
when(response.getOutputStream()).thenReturn(stream);
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of(""))
.build();
assertFalse(interceptor.preHandle(request, response, null));
}
/**
* Test that a url granted an exemption from needing a full profile
* is accesible by a user with an incomplete profile
* @throws Exception
*/
@Test
public void testNeedingFullProfileExemption() throws Exception {
when(request.getRequestURI()).thenReturn("/something/bcdf.json");
when(response.getOutputStream()).thenReturn(stream);
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of("/something/:uid"))
.build();
assertTrue(interceptor.preHandle(request, response, null));
}
/**
* Check that the OAuthInterceptor won't block urls
* that it is not meant to protect
*/
@Test
public void testNotProtectingOtherUrl() throws Exception {
when(request.getRequestURI()).thenReturn("/other.json");
when(response.getOutputStream()).thenReturn(stream);
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of("/something/:uid"))
.build();
assertTrue(interceptor.preHandle(request, response, null));
}
}
|
atlas-api/src/test/java/org/atlasapi/application/auth/OAuthInterceptorTest.java
|
package org.atlasapi.application.auth;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigInteger;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.atlasapi.application.users.User;
import org.atlasapi.entity.Id;
import org.junit.Test;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.metabroadcast.common.ids.NumberToShortStringCodec;
public class OAuthInterceptorTest {
/**
* Test that access is denied to a url under protection if no
* user present
* @throws Exception
*/
@Test
public void testProtectsUrlNoUser() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("/myprotectedUrl.json");
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream stream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(stream);
UserFetcher userFetcher = mock(UserFetcher.class);
NumberToShortStringCodec idCodec = mock(NumberToShortStringCodec.class);
when(userFetcher.userFor(request)).thenReturn(Optional.<User>absent());
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of(""))
.build();
assertFalse(interceptor.preHandle(request, response, null));
}
/**
* Test that a url requiring a completed user profile is not
* accessible to a user with an incomplete profile
* @throws Exception
*/
@Test
public void testProtectsUrlNeedingFullProfile() throws Exception {
User user = mock(User.class);
when(user.getId()).thenReturn(Id.valueOf(new BigInteger("5000")));
when(user.isProfileComplete()).thenReturn(false);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("/myprotectedUrl.json");
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream stream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(stream);
UserFetcher userFetcher = mock(UserFetcher.class);
NumberToShortStringCodec idCodec = mock(NumberToShortStringCodec.class);
when(idCodec.encode(new BigInteger("5000"))).thenReturn("bcdf");
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of(""))
.build();
assertFalse(interceptor.preHandle(request, response, null));
}
/**
* Test that a url granted an exemption from needing a full profile
* is accesible by a user with an incomplete profile
* @throws Exception
*/
@Test
public void testNeedingFullProfileExemption() throws Exception {
User user = mock(User.class);
when(user.getId()).thenReturn(Id.valueOf(new BigInteger("5000")));
when(user.isProfileComplete()).thenReturn(false);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("/something/bcdf.json");
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream stream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(stream);
UserFetcher userFetcher = mock(UserFetcher.class);
NumberToShortStringCodec idCodec = mock(NumberToShortStringCodec.class);
when(idCodec.encode(new BigInteger("5000"))).thenReturn("bcdf");
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of("/something/:uid"))
.build();
assertTrue(interceptor.preHandle(request, response, null));
}
/**
* Check that the OAuthInterceptor won't block urls
* that it is not meant to protect
*/
@Test
public void testNotProtectingOtherUrl() throws Exception {
User user = mock(User.class);
when(user.getId()).thenReturn(Id.valueOf(new BigInteger("5000")));
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn("/other.json");
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream stream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(stream);
UserFetcher userFetcher = mock(UserFetcher.class);
NumberToShortStringCodec idCodec = mock(NumberToShortStringCodec.class);
when(idCodec.encode(new BigInteger("5000"))).thenReturn("bcdf");
when(userFetcher.userFor(request)).thenReturn(Optional.<User>of(user));
OAuthInterceptor interceptor = OAuthInterceptor
.builder()
.withUserFetcher(userFetcher)
.withIdCodec(idCodec)
.withUrlsToProtect(ImmutableSet.of(
"/myprotectedUrl"))
.withUrlsNotNeedingCompleteProfile(ImmutableSet.of("/something/:uid"))
.build();
assertTrue(interceptor.preHandle(request, response, null));
}
}
|
Remove much duplicated code in test
|
atlas-api/src/test/java/org/atlasapi/application/auth/OAuthInterceptorTest.java
|
Remove much duplicated code in test
|
|
Java
|
apache-2.0
|
25c95f28f7ab0eccf20435c562f1a316671c6738
| 0
|
jinglining/flink,kl0u/flink,jinglining/flink,zentol/flink,hequn8128/flink,shaoxuan-wang/flink,fhueske/flink,StephanEwen/incubator-flink,yew1eb/flink,mbode/flink,kl0u/flink,zimmermatt/flink,tony810430/flink,tony810430/flink,fhueske/flink,kl0u/flink,zjureel/flink,greghogan/flink,greghogan/flink,kaibozhou/flink,ueshin/apache-flink,zentol/flink,wwjiang007/flink,godfreyhe/flink,apache/flink,lincoln-lil/flink,tony810430/flink,jinglining/flink,gyfora/flink,hequn8128/flink,bowenli86/flink,fhueske/flink,greghogan/flink,tzulitai/flink,aljoscha/flink,apache/flink,shaoxuan-wang/flink,kl0u/flink,twalthr/flink,GJL/flink,aljoscha/flink,rmetzger/flink,zjureel/flink,rmetzger/flink,fhueske/flink,StephanEwen/incubator-flink,twalthr/flink,clarkyzl/flink,xccui/flink,tony810430/flink,gyfora/flink,rmetzger/flink,kaibozhou/flink,twalthr/flink,zjureel/flink,ueshin/apache-flink,shaoxuan-wang/flink,ueshin/apache-flink,zhangminglei/flink,wwjiang007/flink,mylog00/flink,xccui/flink,lincoln-lil/flink,gyfora/flink,StephanEwen/incubator-flink,tillrohrmann/flink,shaoxuan-wang/flink,gyfora/flink,mylog00/flink,zhangminglei/flink,aljoscha/flink,sunjincheng121/flink,rmetzger/flink,clarkyzl/flink,zimmermatt/flink,tillrohrmann/flink,kaibozhou/flink,fhueske/flink,godfreyhe/flink,tony810430/flink,mbode/flink,clarkyzl/flink,xccui/flink,zimmermatt/flink,sunjincheng121/flink,bowenli86/flink,wwjiang007/flink,bowenli86/flink,kaibozhou/flink,aljoscha/flink,apache/flink,lincoln-lil/flink,jinglining/flink,darionyaphet/flink,godfreyhe/flink,wwjiang007/flink,apache/flink,godfreyhe/flink,mylog00/flink,fhueske/flink,StephanEwen/incubator-flink,kaibozhou/flink,zhangminglei/flink,tillrohrmann/flink,sunjincheng121/flink,clarkyzl/flink,zjureel/flink,ueshin/apache-flink,darionyaphet/flink,shaoxuan-wang/flink,GJL/flink,tzulitai/flink,StephanEwen/incubator-flink,sunjincheng121/flink,bowenli86/flink,hequn8128/flink,aljoscha/flink,GJL/flink,yew1eb/flink,zentol/flink,hequn8128/flink,gyfora/flink,bowenli86/flink,zjureel/flink,tzulitai/flink,apache/flink,tillrohrmann/flink,clarkyzl/flink,zhangminglei/flink,mylog00/flink,zimmermatt/flink,apache/flink,greghogan/flink,sunjincheng121/flink,gyfora/flink,lincoln-lil/flink,zhangminglei/flink,hequn8128/flink,mbode/flink,godfreyhe/flink,aljoscha/flink,yew1eb/flink,zjureel/flink,sunjincheng121/flink,wwjiang007/flink,mylog00/flink,tillrohrmann/flink,zentol/flink,yew1eb/flink,rmetzger/flink,zentol/flink,jinglining/flink,GJL/flink,greghogan/flink,kaibozhou/flink,lincoln-lil/flink,tillrohrmann/flink,rmetzger/flink,tzulitai/flink,darionyaphet/flink,xccui/flink,tony810430/flink,zentol/flink,ueshin/apache-flink,xccui/flink,rmetzger/flink,zjureel/flink,twalthr/flink,apache/flink,mbode/flink,mbode/flink,GJL/flink,godfreyhe/flink,wwjiang007/flink,darionyaphet/flink,darionyaphet/flink,tzulitai/flink,jinglining/flink,twalthr/flink,greghogan/flink,GJL/flink,wwjiang007/flink,yew1eb/flink,shaoxuan-wang/flink,godfreyhe/flink,xccui/flink,tillrohrmann/flink,kl0u/flink,zimmermatt/flink,xccui/flink,bowenli86/flink,lincoln-lil/flink,hequn8128/flink,gyfora/flink,kl0u/flink,twalthr/flink,lincoln-lil/flink,tony810430/flink,StephanEwen/incubator-flink,zentol/flink,tzulitai/flink,twalthr/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.resourcemanager.slotmanager;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.clusterframework.types.TaskManagerSlot;
import org.apache.flink.runtime.concurrent.Executors;
import org.apache.flink.runtime.concurrent.ScheduledExecutor;
import org.apache.flink.runtime.instance.InstanceID;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.resourcemanager.SlotRequest;
import org.apache.flink.runtime.resourcemanager.exceptions.ResourceManagerException;
import org.apache.flink.runtime.resourcemanager.registration.TaskExecutorConnection;
import org.apache.flink.runtime.taskexecutor.SlotReport;
import org.apache.flink.runtime.taskexecutor.SlotStatus;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.runtime.taskexecutor.exceptions.SlotAllocationException;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.util.TestLogger;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SlotManagerTest extends TestLogger {
/**
* Tests that we can register task manager and their slots at the slot manager.
*/
@Test
public void testTaskManagerRegistration() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue("The number registered slots does not equal the expected number.",2 == slotManager.getNumberRegisteredSlots());
assertNotNull(slotManager.getSlot(slotId1));
assertNotNull(slotManager.getSlot(slotId2));
}
}
/**
* Tests that un-registration of task managers will free and remove all registered slots.
*/
@Test
public void testTaskManagerUnregistration() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(new CompletableFuture<>());
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final AllocationID allocationId1 = new AllocationID();
final AllocationID allocationId2 = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile, jobId, allocationId1);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
allocationId2,
resourceProfile,
"foobar");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue("The number registered slots does not equal the expected number.",2 == slotManager.getNumberRegisteredSlots());
TaskManagerSlot slot1 = slotManager.getSlot(slotId1);
TaskManagerSlot slot2 = slotManager.getSlot(slotId2);
assertTrue(slot1.getState() == TaskManagerSlot.State.ALLOCATED);
assertTrue(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slotManager.registerSlotRequest(slotRequest));
assertFalse(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slot2.getState() == TaskManagerSlot.State.PENDING);
PendingSlotRequest pendingSlotRequest = slotManager.getSlotRequest(allocationId2);
assertTrue("The pending slot request should have been assigned to slot 2", pendingSlotRequest.isAssigned());
slotManager.unregisterTaskManager(taskManagerConnection.getInstanceID());
assertTrue(0 == slotManager.getNumberRegisteredSlots());
assertFalse(pendingSlotRequest.isAssigned());
}
}
/**
* Tests that a slot request with no free slots will trigger the resource allocation
*/
@Test
public void testSlotRequestWithoutFreeSlots() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
new AllocationID(),
resourceProfile,
"localhost");
ResourceActions resourceManagerActions = mock(ResourceActions.class);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerSlotRequest(slotRequest);
verify(resourceManagerActions).allocateResource(eq(resourceProfile));
}
}
/**
* Tests that the slot request fails if we cannot allocate more resources.
*/
@Test
public void testSlotRequestWithResourceAllocationFailure() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
new AllocationID(),
resourceProfile,
"localhost");
ResourceActions resourceManagerActions = mock(ResourceActions.class);
doThrow(new ResourceManagerException("Test exception")).when(resourceManagerActions).allocateResource(any(ResourceProfile.class));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerSlotRequest(slotRequest);
fail("The slot request should have failed with a ResourceManagerException.");
} catch (ResourceManagerException e) {
// expected exception
}
}
/**
* Tests that a slot request which can be fulfilled will trigger a slot allocation.
*/
@Test
public void testSlotRequestWithFreeSlot() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final String targetAddress = "localhost";
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
jobId,
allocationId,
resourceProfile,
targetAddress);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
eq(slotId),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
assertTrue("The slot request should be accepted", slotManager.registerSlotRequest(slotRequest));
verify(taskExecutorGateway).requestSlot(eq(slotId), eq(jobId), eq(allocationId), eq(targetAddress), eq(resourceManagerId), any(Time.class));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
}
/**
* Checks that un-registering a pending slot request will cancel it, removing it from all
* assigned task manager slots and then remove it from the slot manager.
*/
@Test
public void testUnregisterPendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final AllocationID allocationId = new AllocationID();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(new CompletableFuture<>());
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
final SlotRequest slotRequest = new SlotRequest(new JobID(), allocationId, resourceProfile, "foobar");
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
TaskManagerSlot slot = slotManager.getSlot(slotId);
slotManager.registerSlotRequest(slotRequest);
assertNotNull(slotManager.getSlotRequest(allocationId));
assertTrue(slot.getState() == TaskManagerSlot.State.PENDING);
slotManager.unregisterSlotRequest(allocationId);
assertNull(slotManager.getSlotRequest(allocationId));
slot = slotManager.getSlot(slotId);
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
}
}
/**
* Tests that pending slot requests are tried to be fulfilled upon new slot registrations.
*/
@Test
public void testFulfillingPendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final String targetAddress = "localhost";
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
jobId,
allocationId,
resourceProfile,
targetAddress);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
eq(slotId),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
assertTrue("The slot request should be accepted", slotManager.registerSlotRequest(slotRequest));
verify(resourceManagerActions, times(1)).allocateResource(eq(resourceProfile));
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
verify(taskExecutorGateway).requestSlot(eq(slotId), eq(jobId), eq(allocationId), eq(targetAddress), eq(resourceManagerId), any(Time.class));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
}
/**
* Tests that freeing a slot will correctly reset the slot and mark it as a free slot
*/
@Test
public void testFreeSlot() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile, jobId, allocationId);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
// this should be ignored since the allocation id does not match
slotManager.freeSlot(slotId, new AllocationID());
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
slotManager.freeSlot(slotId, allocationId);
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
assertNull(slot.getAllocationId());
}
}
/**
* Tests that a second pending slot request is detected as a duplicate if the allocation ids are
* the same.
*/
@Test
public void testDuplicatePendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
assertTrue(slotManager.registerSlotRequest(slotRequest1));
assertFalse(slotManager.registerSlotRequest(slotRequest2));
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, times(1)).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that if we have received a slot report with some allocated slots, then we don't accept
* slot requests with allocated allocation ids.
*/
@Test
public void testDuplicatePendingSlotRequestAfterSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile, jobId, allocationId);
final SlotReport slotReport = new SlotReport(slotStatus);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertFalse(slotManager.registerSlotRequest(slotRequest));
}
}
/**
* Tests that duplicate slot requests (requests with an already registered allocation id) are
* also detected after a pending slot request has been fulfilled but not yet freed.
*/
@Test
public void testDuplicatePendingSlotRequestAfterSuccessfulAllocation() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile1);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue(slotManager.registerSlotRequest(slotRequest1));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
assertFalse(slotManager.registerSlotRequest(slotRequest2));
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, never()).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that an already registered allocation id can be reused after the initial slot request
* has been freed.
*/
@Test
public void testAcceptingDuplicateSlotRequestAfterAllocationRelease() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final SlotStatus slotStatus = new SlotStatus(slotId, new ResourceProfile(2.0, 2));
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue(slotManager.registerSlotRequest(slotRequest1));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
slotManager.freeSlot(slotId, allocationId);
// check that the slot has been freed
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
assertNull(slot.getAllocationId());
assertTrue(slotManager.registerSlotRequest(slotRequest2));
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, never()).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that the slot manager ignores slot reports of unknown origin (not registered
* task managers).
*/
@Test
public void testReceivingUnknownSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final InstanceID unknownInstanceID = new InstanceID();
final SlotID unknownSlotId = new SlotID(ResourceID.generate(), 0);
final ResourceProfile unknownResourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus unknownSlotStatus = new SlotStatus(unknownSlotId, unknownResourceProfile);
final SlotReport unknownSlotReport = new SlotReport(unknownSlotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// check that we don't have any slots registered
assertTrue(0 == slotManager.getNumberRegisteredSlots());
// this should not update anything since the instance id is not known to the slot manager
assertFalse(slotManager.reportSlotStatus(unknownInstanceID, unknownSlotReport));
assertTrue(0 == slotManager.getNumberRegisteredSlots());
}
}
/**
* Tests that slots are updated with respect to the latest incoming slot report. This means that
* slots for which a report was received are updated accordingly.
*/
@Test
public void testUpdateSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotStatus newSlotStatus2 = new SlotStatus(slotId2, resourceProfile, jobId, allocationId);
final SlotReport slotReport1 = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final SlotReport slotReport2 = new SlotReport(Arrays.asList(newSlotStatus2, slotStatus1));
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// check that we don't have any slots registered
assertTrue(0 == slotManager.getNumberRegisteredSlots());
slotManager.registerTaskManager(taskManagerConnection, slotReport1);
TaskManagerSlot slot1 = slotManager.getSlot(slotId1);
TaskManagerSlot slot2 = slotManager.getSlot(slotId2);
assertTrue(2 == slotManager.getNumberRegisteredSlots());
assertTrue(slot1.getState() == TaskManagerSlot.State.FREE);
assertTrue(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slotManager.reportSlotStatus(taskManagerConnection.getInstanceID(), slotReport2));
assertTrue(2 == slotManager.getNumberRegisteredSlots());
assertNotNull(slotManager.getSlot(slotId1));
assertNotNull(slotManager.getSlot(slotId2));
// slotId2 should have been allocated for allocationId
assertEquals(allocationId, slotManager.getSlot(slotId2).getAllocationId());
}
}
/**
* Tests that idle task managers time out after the configured timeout. A timed out task manager
* will be removed from the slot manager and the resource manager will be notified about the
* timeout.
*/
@Test
public void testTaskManagerTimeout() throws Exception {
final long tmTimeout = 500L;
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
Time.milliseconds(tmTimeout))) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
mainThreadExecutor.execute(new Runnable() {
@Override
public void run() {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
}
});
verify(resourceManagerActions, timeout(100L * tmTimeout).times(1))
.releaseResource(eq(taskManagerConnection.getInstanceID()));
}
}
/**
* Tests that slot requests time out after the specified request timeout. If a slot request
* times out, then the request is cancelled, removed from the slot manager and the resource
* manager is notified about the failed allocation.
*/
@Test
public void testSlotRequestTimeout() throws Exception {
final long allocationTimeout = 50L;
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
Time.milliseconds(allocationTimeout),
TestingUtils.infiniteTime())) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
final AtomicReference<Exception> atomicException = new AtomicReference<>(null);
mainThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
assertTrue(slotManager.registerSlotRequest(slotRequest));
} catch (Exception e) {
atomicException.compareAndSet(null, e);
}
}
});
verify(resourceManagerActions, timeout(100L * allocationTimeout).times(1)).notifyAllocationFailure(
eq(jobId),
eq(allocationId),
any(TimeoutException.class));
if (atomicException.get() != null) {
throw atomicException.get();
}
}
}
/**
* Tests that a slot request is retried if it times out on the task manager side
*/
@Test
@SuppressWarnings("unchecked")
public void testTaskManagerSlotRequestTimeoutHandling() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final CompletableFuture<Acknowledge> slotRequestFuture1 = new CompletableFuture<>();
final CompletableFuture<Acknowledge> slotRequestFuture2 = new CompletableFuture<>();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
eq(allocationId),
anyString(),
any(ResourceManagerId.class),
any(Time.class))).thenReturn(slotRequestFuture1, slotRequestFuture2);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
slotManager.registerSlotRequest(slotRequest);
ArgumentCaptor<SlotID> slotIdCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, times(1)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
TaskManagerSlot failedSlot = slotManager.getSlot(slotIdCaptor.getValue());
// let the first attempt fail --> this should trigger a second attempt
slotRequestFuture1.completeExceptionally(new SlotAllocationException("Test exception."));
verify(taskExecutorGateway, times(2)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
// the second attempt succeeds
slotRequestFuture2.complete(Acknowledge.get());
TaskManagerSlot slot = slotManager.getSlot(slotIdCaptor.getValue());
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
if (!failedSlot.getSlotId().equals(slot.getSlotId())) {
assertTrue(failedSlot.getState() == TaskManagerSlot.State.FREE);
}
}
}
/**
* Tests that pending slot requests are rejected if a slot report with a different allocation
* is received.
*/
@Test
@SuppressWarnings("unchecked")
public void testSlotReportWhileActiveSlotRequest() throws Exception {
final long verifyTimeout = 10000L;
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final CompletableFuture<Acknowledge> slotRequestFuture1 = new CompletableFuture<>();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
eq(allocationId),
anyString(),
any(ResourceManagerId.class),
any(Time.class))).thenReturn(slotRequestFuture1, CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (final SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime())) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
CompletableFuture<Void> registrationFuture = CompletableFuture.supplyAsync(
() -> {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
return null;
},
mainThreadExecutor)
.thenAccept(
(Object value) -> {
try {
slotManager.registerSlotRequest(slotRequest);
} catch (SlotManagerException e) {
throw new RuntimeException("Could not register slots.", e);
}
});
// check that no exception has been thrown
registrationFuture.get();
ArgumentCaptor<SlotID> slotIdCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, times(1)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
final SlotID requestedSlotId = slotIdCaptor.getValue();
final SlotID freeSlotId = requestedSlotId.equals(slotId1) ? slotId2 : slotId1;
CompletableFuture<Boolean> freeSlotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(freeSlotId).getState() == TaskManagerSlot.State.FREE,
mainThreadExecutor);
assertTrue(freeSlotFuture.get());
final SlotStatus newSlotStatus1 = new SlotStatus(slotIdCaptor.getValue(), resourceProfile, new JobID(), new AllocationID());
final SlotStatus newSlotStatus2 = new SlotStatus(freeSlotId, resourceProfile);
final SlotReport newSlotReport = new SlotReport(Arrays.asList(newSlotStatus1, newSlotStatus2));
CompletableFuture<Boolean> reportSlotStatusFuture = CompletableFuture.supplyAsync(
// this should update the slot with the pending slot request triggering the reassignment of it
() -> slotManager.reportSlotStatus(taskManagerConnection.getInstanceID(), newSlotReport),
mainThreadExecutor);
assertTrue(reportSlotStatusFuture.get());
verify(taskExecutorGateway, timeout(verifyTimeout).times(2)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
final SlotID requestedSlotId2 = slotIdCaptor.getValue();
assertEquals(slotId2, requestedSlotId2);
CompletableFuture<TaskManagerSlot> requestedSlotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(requestedSlotId2),
mainThreadExecutor);
TaskManagerSlot slot = requestedSlotFuture.get();
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
}
}
/**
* Tests that formerly used task managers can again timeout after all of their slots have
* been freed.
*/
@Test
public void testTimeoutForUnusedTaskManager() throws Exception {
final long taskManagerTimeout = 50L;
final long verifyTimeout = taskManagerTimeout * 10L;
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ScheduledExecutor scheduledExecutor = TestingUtils.defaultScheduledExecutor();
final ResourceID resourceId = ResourceID.generate();
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport initialSlotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (final SlotManager slotManager = new SlotManager(
scheduledExecutor,
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
Time.of(taskManagerTimeout, TimeUnit.MILLISECONDS))) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
CompletableFuture.supplyAsync(
() -> {
try {
return slotManager.registerSlotRequest(slotRequest);
} catch (SlotManagerException e) {
throw new CompletionException(e);
}
},
mainThreadExecutor)
.thenAccept((Object value) -> slotManager.registerTaskManager(taskManagerConnection, initialSlotReport));
ArgumentCaptor<SlotID> slotIdArgumentCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, timeout(verifyTimeout)).requestSlot(
slotIdArgumentCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
CompletableFuture<Boolean> idleFuture = CompletableFuture.supplyAsync(
() -> slotManager.isTaskManagerIdle(taskManagerConnection.getInstanceID()),
mainThreadExecutor);
// check that the TaskManaer is not idle
assertFalse(idleFuture.get());
final SlotID slotId = slotIdArgumentCaptor.getValue();
CompletableFuture<TaskManagerSlot> slotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(slotId),
mainThreadExecutor);
TaskManagerSlot slot = slotFuture.get();
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
CompletableFuture<Boolean> idleFuture2 = CompletableFuture.runAsync(
() -> slotManager.freeSlot(slotId, allocationId),
mainThreadExecutor)
.thenApply((Object value) -> slotManager.isTaskManagerIdle(taskManagerConnection.getInstanceID()));
assertTrue(idleFuture2.get());
verify(resourceManagerActions, timeout(verifyTimeout).times(1)).releaseResource(eq(taskManagerConnection.getInstanceID()));
}
}
/**
* Tests that a task manager timeout does not remove the slots from the SlotManager.
* A timeout should only trigger the {@link ResourceActions#releaseResource(InstanceID)}
* callback. The receiver of the callback can then decide what to do with the TaskManager.
*
* FLINK-7793
*/
@Test
public void testTaskManagerTimeoutDoesNotRemoveSlots() throws Exception {
final Time taskManagerTimeout = Time.milliseconds(10L);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceActions = mock(ResourceActions.class);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(
new SlotID(ResourceID.generate(), 0),
new ResourceProfile(1.0, 1));
final SlotReport initialSlotReport = new SlotReport(slotStatus);
try (final SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
taskManagerTimeout)) {
slotManager.start(resourceManagerId, Executors.directExecutor(), resourceActions);
slotManager.registerTaskManager(taskExecutorConnection, initialSlotReport);
assertEquals(1, slotManager.getNumberRegisteredSlots());
// wait for the timeout call to happen
verify(resourceActions, timeout(taskManagerTimeout.toMilliseconds() * 20L).atLeast(1)).releaseResource(eq(taskExecutorConnection.getInstanceID()));
assertEquals(1, slotManager.getNumberRegisteredSlots());
slotManager.unregisterTaskManager(taskExecutorConnection.getInstanceID());
assertEquals(0, slotManager.getNumberRegisteredSlots());
}
}
private SlotManager createSlotManager(ResourceManagerId resourceManagerId, ResourceActions resourceManagerActions) {
SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime());
slotManager.start(resourceManagerId, Executors.directExecutor(), resourceManagerActions);
return slotManager;
}
}
|
flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManagerTest.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.resourcemanager.slotmanager;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.clusterframework.types.TaskManagerSlot;
import org.apache.flink.runtime.concurrent.Executors;
import org.apache.flink.runtime.concurrent.ScheduledExecutor;
import org.apache.flink.runtime.instance.InstanceID;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.resourcemanager.SlotRequest;
import org.apache.flink.runtime.resourcemanager.exceptions.ResourceManagerException;
import org.apache.flink.runtime.resourcemanager.registration.TaskExecutorConnection;
import org.apache.flink.runtime.taskexecutor.SlotReport;
import org.apache.flink.runtime.taskexecutor.SlotStatus;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.runtime.taskexecutor.exceptions.SlotAllocationException;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.util.TestLogger;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SlotManagerTest extends TestLogger {
/**
* Tests that we can register task manager and their slots at the slot manager.
*/
@Test
public void testTaskManagerRegistration() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue("The number registered slots does not equal the expected number.",2 == slotManager.getNumberRegisteredSlots());
assertNotNull(slotManager.getSlot(slotId1));
assertNotNull(slotManager.getSlot(slotId2));
}
}
/**
* Tests that un-registration of task managers will free and remove all registered slots.
*/
@Test
public void testTaskManagerUnregistration() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(new CompletableFuture<>());
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final AllocationID allocationId1 = new AllocationID();
final AllocationID allocationId2 = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile, jobId, allocationId1);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
allocationId2,
resourceProfile,
"foobar");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue("The number registered slots does not equal the expected number.",2 == slotManager.getNumberRegisteredSlots());
TaskManagerSlot slot1 = slotManager.getSlot(slotId1);
TaskManagerSlot slot2 = slotManager.getSlot(slotId2);
assertTrue(slot1.getState() == TaskManagerSlot.State.ALLOCATED);
assertTrue(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slotManager.registerSlotRequest(slotRequest));
assertFalse(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slot2.getState() == TaskManagerSlot.State.PENDING);
PendingSlotRequest pendingSlotRequest = slotManager.getSlotRequest(allocationId2);
assertTrue("The pending slot request should have been assigned to slot 2", pendingSlotRequest.isAssigned());
slotManager.unregisterTaskManager(taskManagerConnection.getInstanceID());
assertTrue(0 == slotManager.getNumberRegisteredSlots());
assertFalse(pendingSlotRequest.isAssigned());
}
}
/**
* Tests that a slot request with no free slots will trigger the resource allocation
*/
@Test
public void testSlotRequestWithoutFreeSlots() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
new AllocationID(),
resourceProfile,
"localhost");
ResourceActions resourceManagerActions = mock(ResourceActions.class);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerSlotRequest(slotRequest);
verify(resourceManagerActions).allocateResource(eq(resourceProfile));
}
}
/**
* Tests that the slot request fails if we cannot allocate more resources.
*/
@Test
public void testSlotRequestWithResourceAllocationFailure() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
new JobID(),
new AllocationID(),
resourceProfile,
"localhost");
ResourceActions resourceManagerActions = mock(ResourceActions.class);
doThrow(new ResourceManagerException("Test exception")).when(resourceManagerActions).allocateResource(any(ResourceProfile.class));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerSlotRequest(slotRequest);
fail("The slot request should have failed with a ResourceManagerException.");
} catch (ResourceManagerException e) {
// expected exception
}
}
/**
* Tests that a slot request which can be fulfilled will trigger a slot allocation.
*/
@Test
public void testSlotRequestWithFreeSlot() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final String targetAddress = "localhost";
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
jobId,
allocationId,
resourceProfile,
targetAddress);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
eq(slotId),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
assertTrue("The slot request should be accepted", slotManager.registerSlotRequest(slotRequest));
verify(taskExecutorGateway).requestSlot(eq(slotId), eq(jobId), eq(allocationId), eq(targetAddress), eq(resourceManagerId), any(Time.class));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
}
/**
* Checks that un-registering a pending slot request will cancel it, removing it from all
* assigned task manager slots and then remove it from the slot manager.
*/
@Test
public void testUnregisterPendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final AllocationID allocationId = new AllocationID();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(new CompletableFuture<>());
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
final SlotRequest slotRequest = new SlotRequest(new JobID(), allocationId, resourceProfile, "foobar");
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
TaskManagerSlot slot = slotManager.getSlot(slotId);
slotManager.registerSlotRequest(slotRequest);
assertNotNull(slotManager.getSlotRequest(allocationId));
assertTrue(slot.getState() == TaskManagerSlot.State.PENDING);
slotManager.unregisterSlotRequest(allocationId);
assertNull(slotManager.getSlotRequest(allocationId));
slot = slotManager.getSlot(slotId);
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
}
}
/**
* Tests that pending slot requests are tried to be fulfilled upon new slot registrations.
*/
@Test
public void testFulfillingPendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final String targetAddress = "localhost";
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(
jobId,
allocationId,
resourceProfile,
targetAddress);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
eq(slotId),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
assertTrue("The slot request should be accepted", slotManager.registerSlotRequest(slotRequest));
verify(resourceManagerActions, times(1)).allocateResource(eq(resourceProfile));
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
verify(taskExecutorGateway).requestSlot(eq(slotId), eq(jobId), eq(allocationId), eq(targetAddress), eq(resourceManagerId), any(Time.class));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
}
/**
* Tests that freeing a slot will correctly reset the slot and mark it as a free slot
*/
@Test
public void testFreeSlot() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceID resourceID = ResourceID.generate();
final JobID jobId = new JobID();
final SlotID slotId = new SlotID(resourceID, 0);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
ResourceActions resourceManagerActions = mock(ResourceActions.class);
// accept an incoming slot request
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile, jobId, allocationId);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(
taskExecutorConnection,
slotReport);
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
// this should be ignored since the allocation id does not match
slotManager.freeSlot(slotId, new AllocationID());
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
slotManager.freeSlot(slotId, allocationId);
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
assertNull(slot.getAllocationId());
}
}
/**
* Tests that a second pending slot request is detected as a duplicate if the allocation ids are
* the same.
*/
@Test
public void testDuplicatePendingSlotRequest() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
assertTrue(slotManager.registerSlotRequest(slotRequest1));
assertFalse(slotManager.registerSlotRequest(slotRequest2));
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, times(1)).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that if we have received a slot report with some allocated slots, then we don't accept
* slot requests with allocated allocation ids.
*/
@Test
public void testDuplicatePendingSlotRequestAfterSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile, jobId, allocationId);
final SlotReport slotReport = new SlotReport(slotStatus);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertFalse(slotManager.registerSlotRequest(slotRequest));
}
}
/**
* Tests that duplicate slot requests (requests with an already registered allocation id) are
* also detected after a pending slot request has been fulfilled but not yet freed.
*/
@Test
public void testDuplicatePendingSlotRequestAfterSuccessfulAllocation() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile1);
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue(slotManager.registerSlotRequest(slotRequest1));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
assertFalse(slotManager.registerSlotRequest(slotRequest2));
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, never()).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that an already registered allocation id can be reused after the initial slot request
* has been freed.
*/
@Test
public void testAcceptingDuplicateSlotRequestAfterAllocationRelease() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2);
final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1);
final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar");
final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
any(AllocationID.class),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final SlotStatus slotStatus = new SlotStatus(slotId, new ResourceProfile(2.0, 2));
final SlotReport slotReport = new SlotReport(slotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
assertTrue(slotManager.registerSlotRequest(slotRequest1));
TaskManagerSlot slot = slotManager.getSlot(slotId);
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
slotManager.freeSlot(slotId, allocationId);
// check that the slot has been freed
assertTrue(slot.getState() == TaskManagerSlot.State.FREE);
assertNull(slot.getAllocationId());
assertTrue(slotManager.registerSlotRequest(slotRequest2));
assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId());
}
// check that we have only called the resource allocation only for the first slot request,
// since the second request is a duplicate
verify(resourceManagerActions, never()).allocateResource(any(ResourceProfile.class));
}
/**
* Tests that the slot manager ignores slot reports of unknown origin (not registered
* task managers).
*/
@Test
public void testReceivingUnknownSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final InstanceID unknownInstanceID = new InstanceID();
final SlotID unknownSlotId = new SlotID(ResourceID.generate(), 0);
final ResourceProfile unknownResourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus unknownSlotStatus = new SlotStatus(unknownSlotId, unknownResourceProfile);
final SlotReport unknownSlotReport = new SlotReport(unknownSlotStatus);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// check that we don't have any slots registered
assertTrue(0 == slotManager.getNumberRegisteredSlots());
// this should not update anything since the instance id is not known to the slot manager
assertFalse(slotManager.reportSlotStatus(unknownInstanceID, unknownSlotReport));
assertTrue(0 == slotManager.getNumberRegisteredSlots());
}
}
/**
* Tests that slots are updated with respect to the latest incoming slot report. This means that
* slots for which a report was received are updated accordingly.
*/
@Test
public void testUpdateSlotReport() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotStatus newSlotStatus2 = new SlotStatus(slotId2, resourceProfile, jobId, allocationId);
final SlotReport slotReport1 = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final SlotReport slotReport2 = new SlotReport(Arrays.asList(newSlotStatus2, slotStatus1));
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
// check that we don't have any slots registered
assertTrue(0 == slotManager.getNumberRegisteredSlots());
slotManager.registerTaskManager(taskManagerConnection, slotReport1);
TaskManagerSlot slot1 = slotManager.getSlot(slotId1);
TaskManagerSlot slot2 = slotManager.getSlot(slotId2);
assertTrue(2 == slotManager.getNumberRegisteredSlots());
assertTrue(slot1.getState() == TaskManagerSlot.State.FREE);
assertTrue(slot2.getState() == TaskManagerSlot.State.FREE);
assertTrue(slotManager.reportSlotStatus(taskManagerConnection.getInstanceID(), slotReport2));
assertTrue(2 == slotManager.getNumberRegisteredSlots());
assertNotNull(slotManager.getSlot(slotId1));
assertNotNull(slotManager.getSlot(slotId2));
// slotId2 should have been allocated for allocationId
assertEquals(allocationId, slotManager.getSlot(slotId2).getAllocationId());
}
}
/**
* Tests that idle task managers time out after the configured timeout. A timed out task manager
* will be removed from the slot manager and the resource manager will be notified about the
* timeout.
*/
@Test
public void testTaskManagerTimeout() throws Exception {
final long tmTimeout = 500L;
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId = new SlotID(ResourceID.generate(), 0);
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile);
final SlotReport slotReport = new SlotReport(slotStatus);
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
Time.milliseconds(tmTimeout))) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
mainThreadExecutor.execute(new Runnable() {
@Override
public void run() {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
}
});
verify(resourceManagerActions, timeout(100L * tmTimeout).times(1))
.releaseResource(eq(taskManagerConnection.getInstanceID()));
}
}
/**
* Tests that slot requests time out after the specified request timeout. If a slot request
* times out, then the request is cancelled, removed from the slot manager and the resource
* manager is notified about the failed allocation.
*/
@Test
public void testSlotRequestTimeout() throws Exception {
final long allocationTimeout = 50L;
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
Time.milliseconds(allocationTimeout),
TestingUtils.infiniteTime())) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
final AtomicReference<Exception> atomicException = new AtomicReference<>(null);
mainThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
assertTrue(slotManager.registerSlotRequest(slotRequest));
} catch (Exception e) {
atomicException.compareAndSet(null, e);
}
}
});
verify(resourceManagerActions, timeout(100L * allocationTimeout).times(1)).notifyAllocationFailure(
eq(jobId),
eq(allocationId),
any(TimeoutException.class));
if (atomicException.get() != null) {
throw atomicException.get();
}
}
}
/**
* Tests that a slot request is retried if it times out on the task manager side
*/
@Test
@SuppressWarnings("unchecked")
public void testTaskManagerSlotRequestTimeoutHandling() throws Exception {
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final CompletableFuture<Acknowledge> slotRequestFuture1 = new CompletableFuture<>();
final CompletableFuture<Acknowledge> slotRequestFuture2 = new CompletableFuture<>();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
eq(allocationId),
anyString(),
any(ResourceManagerId.class),
any(Time.class))).thenReturn(slotRequestFuture1, slotRequestFuture2);
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
slotManager.registerSlotRequest(slotRequest);
ArgumentCaptor<SlotID> slotIdCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, times(1)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
TaskManagerSlot failedSlot = slotManager.getSlot(slotIdCaptor.getValue());
// let the first attempt fail --> this should trigger a second attempt
slotRequestFuture1.completeExceptionally(new SlotAllocationException("Test exception."));
verify(taskExecutorGateway, times(2)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
// the second attempt succeeds
slotRequestFuture2.complete(Acknowledge.get());
TaskManagerSlot slot = slotManager.getSlot(slotIdCaptor.getValue());
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
if (!failedSlot.getSlotId().equals(slot.getSlotId())) {
assertTrue(failedSlot.getState() == TaskManagerSlot.State.FREE);
}
}
}
/**
* Tests that pending slot requests are rejected if a slot report with a different allocation
* is received.
*/
@Test
@SuppressWarnings("unchecked")
public void testSlotReportWhileActiveSlotRequest() throws Exception {
final long verifyTimeout = 10000L;
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final CompletableFuture<Acknowledge> slotRequestFuture1 = new CompletableFuture<>();
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
any(JobID.class),
eq(allocationId),
anyString(),
any(ResourceManagerId.class),
any(Time.class))).thenReturn(slotRequestFuture1, CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final ResourceID resourceId = ResourceID.generate();
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport slotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (final SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime())) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
CompletableFuture<Void> registrationFuture = CompletableFuture.supplyAsync(
() -> {
slotManager.registerTaskManager(taskManagerConnection, slotReport);
return null;
},
mainThreadExecutor)
.thenAccept(
(Object value) -> {
try {
slotManager.registerSlotRequest(slotRequest);
} catch (SlotManagerException e) {
throw new RuntimeException("Could not register slots.", e);
}
});
// check that no exception has been thrown
registrationFuture.get();
ArgumentCaptor<SlotID> slotIdCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, times(1)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
final SlotID requestedSlotId = slotIdCaptor.getValue();
final SlotID freeSlotId = requestedSlotId.equals(slotId1) ? slotId2 : slotId1;
CompletableFuture<Boolean> freeSlotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(freeSlotId).getState() == TaskManagerSlot.State.FREE,
mainThreadExecutor);
assertTrue(freeSlotFuture.get());
final SlotStatus newSlotStatus1 = new SlotStatus(slotIdCaptor.getValue(), resourceProfile, new JobID(), new AllocationID());
final SlotStatus newSlotStatus2 = new SlotStatus(freeSlotId, resourceProfile);
final SlotReport newSlotReport = new SlotReport(Arrays.asList(newSlotStatus1, newSlotStatus2));
CompletableFuture<Boolean> reportSlotStatusFuture = CompletableFuture.supplyAsync(
// this should update the slot with the pending slot request triggering the reassignment of it
() -> slotManager.reportSlotStatus(taskManagerConnection.getInstanceID(), newSlotReport),
mainThreadExecutor);
assertTrue(reportSlotStatusFuture.get());
verify(taskExecutorGateway, timeout(verifyTimeout).times(2)).requestSlot(
slotIdCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
final SlotID requestedSlotId2 = slotIdCaptor.getValue();
assertEquals(slotId2, requestedSlotId2);
CompletableFuture<TaskManagerSlot> requestedSlotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(requestedSlotId2),
mainThreadExecutor);
TaskManagerSlot slot = requestedSlotFuture.get();
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
}
}
/**
* Tests that formerly used task managers can again timeout after all of their slots have
* been freed.
*/
@Test
public void testTimeoutForUnusedTaskManager() throws Exception {
final long taskManagerTimeout = 50L;
final long verifyTimeout = taskManagerTimeout * 10L;
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceManagerActions = mock(ResourceActions.class);
final ScheduledExecutor scheduledExecutor = TestingUtils.defaultScheduledExecutor();
final ResourceID resourceId = ResourceID.generate();
final JobID jobId = new JobID();
final AllocationID allocationId = new AllocationID();
final ResourceProfile resourceProfile = new ResourceProfile(1.0, 1);
final SlotRequest slotRequest = new SlotRequest(jobId, allocationId, resourceProfile, "foobar");
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
when(taskExecutorGateway.requestSlot(
any(SlotID.class),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class))).thenReturn(CompletableFuture.completedFuture(Acknowledge.get()));
final TaskExecutorConnection taskManagerConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotID slotId1 = new SlotID(resourceId, 0);
final SlotID slotId2 = new SlotID(resourceId, 1);
final SlotStatus slotStatus1 = new SlotStatus(slotId1, resourceProfile);
final SlotStatus slotStatus2 = new SlotStatus(slotId2, resourceProfile);
final SlotReport initialSlotReport = new SlotReport(Arrays.asList(slotStatus1, slotStatus2));
final Executor mainThreadExecutor = TestingUtils.defaultExecutor();
try (final SlotManager slotManager = new SlotManager(
scheduledExecutor,
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
Time.of(taskManagerTimeout, TimeUnit.MILLISECONDS))) {
slotManager.start(resourceManagerId, mainThreadExecutor, resourceManagerActions);
CompletableFuture.supplyAsync(
() -> {
try {
return slotManager.registerSlotRequest(slotRequest);
} catch (SlotManagerException e) {
throw new CompletionException(e);
}
},
mainThreadExecutor)
.thenAccept((Object value) -> slotManager.registerTaskManager(taskManagerConnection, initialSlotReport));
ArgumentCaptor<SlotID> slotIdArgumentCaptor = ArgumentCaptor.forClass(SlotID.class);
verify(taskExecutorGateway, timeout(verifyTimeout)).requestSlot(
slotIdArgumentCaptor.capture(),
eq(jobId),
eq(allocationId),
anyString(),
eq(resourceManagerId),
any(Time.class));
CompletableFuture<Boolean> idleFuture = CompletableFuture.supplyAsync(
() -> slotManager.isTaskManagerIdle(taskManagerConnection.getInstanceID()),
mainThreadExecutor);
// check that the TaskManaer is not idle
assertFalse(idleFuture.get());
final SlotID slotId = slotIdArgumentCaptor.getValue();
CompletableFuture<TaskManagerSlot> slotFuture = CompletableFuture.supplyAsync(
() -> slotManager.getSlot(slotId),
mainThreadExecutor);
TaskManagerSlot slot = slotFuture.get();
assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED);
assertEquals(allocationId, slot.getAllocationId());
CompletableFuture<Boolean> idleFuture2 = CompletableFuture.runAsync(
() -> slotManager.freeSlot(slotId, allocationId),
mainThreadExecutor)
.thenApply((Object value) -> slotManager.isTaskManagerIdle(taskManagerConnection.getInstanceID()));
assertTrue(idleFuture2.get());
verify(resourceManagerActions, timeout(verifyTimeout).times(1)).releaseResource(eq(taskManagerConnection.getInstanceID()));
}
}
/**
* Tests that a task manager timeout does not remove the slots from the SlotManager.
* A timeout should only trigger the {@link ResourceActions#releaseResource(InstanceID)}
* callback. The receiver of the callback can then decide what to do with the TaskManager.
*
* FLINK-7793
*/
@Test
public void testTaskManagerTimeoutDoesNotRemoveSlots() throws Exception {
final Time taskManagerTimeout = Time.milliseconds(10L);
final ResourceManagerId resourceManagerId = ResourceManagerId.generate();
final ResourceActions resourceActions = mock(ResourceActions.class);
final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class);
final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(taskExecutorGateway);
final SlotStatus slotStatus = new SlotStatus(
new SlotID(ResourceID.generate(), 0),
new ResourceProfile(1.0, 1));
final SlotReport initialSlotReport = new SlotReport(slotStatus);
try (final SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
taskManagerTimeout)) {
slotManager.start(resourceManagerId, Executors.directExecutor(), resourceActions);
slotManager.registerTaskManager(taskExecutorConnection, initialSlotReport);
assertEquals(1, slotManager.getNumberRegisteredSlots());
// wait for the timeout call to happen
verify(resourceActions, timeout(taskManagerTimeout.toMilliseconds() * 3L).atLeast(1)).releaseResource(eq(taskExecutorConnection.getInstanceID()));
assertEquals(1, slotManager.getNumberRegisteredSlots());
slotManager.unregisterTaskManager(taskExecutorConnection.getInstanceID());
assertEquals(0, slotManager.getNumberRegisteredSlots());
}
}
private SlotManager createSlotManager(ResourceManagerId resourceManagerId, ResourceActions resourceManagerActions) {
SlotManager slotManager = new SlotManager(
TestingUtils.defaultScheduledExecutor(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime(),
TestingUtils.infiniteTime());
slotManager.start(resourceManagerId, Executors.directExecutor(), resourceManagerActions);
return slotManager;
}
}
|
[FLINK-7899] Harden SlotManagerTest#testTaskManagerTimeoutDoesNotRemoveSlots by increasing timeout
|
flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManagerTest.java
|
[FLINK-7899] Harden SlotManagerTest#testTaskManagerTimeoutDoesNotRemoveSlots by increasing timeout
|
|
Java
|
apache-2.0
|
6407862b9abea34fdeb2e8f62333821f829d8d0d
| 0
|
spoofax-shell-2017/spoofax-shell
|
package org.metaborg.spoofax.shell.commands;
import java.util.Objects;
import javax.annotation.Nullable;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.action.ITransformAction;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.project.IProject;
import org.metaborg.spoofax.shell.client.IResult;
import org.metaborg.spoofax.shell.functions.FailableFunction;
import org.metaborg.spoofax.shell.functions.IFunctionFactory;
import org.metaborg.spoofax.shell.output.AnalyzeResult;
import org.metaborg.spoofax.shell.output.EvaluateResult;
import org.metaborg.spoofax.shell.output.InputResult;
import org.metaborg.spoofax.shell.output.ParseResult;
import org.metaborg.spoofax.shell.output.TransformResult;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
/**
* Builds commands by composing {@link FailableFunction}s. This builder provides several functions
* that are set out of the box, namely:
*
* <ol>
* <li>{@link #input()},</li>
* <li>{@link #parse()},</li>
* <li>{@link #analyze()},</li>
* <li>{@link #transformParsed(ITransformAction)} and {@link #transformAnalyzed(ITransformAction)},
* </li>
* <li>{@link #evalParsed()} and {@link #evalAnalyzed()}</li>
* </ol>
*
* It also allows composing ones own {@link FailableFunction}s in a builder like manner. Use
* {@link #function(FailableFunction)} for setting the initial function, which always starts from an
* array of {@link String}s and can return any {@link IResult}. Then one can use
* {@link #compose(FailableFunction)} repeatedly to compose from that function (see also
* {@link FailableFunction#kleisliCompose(FailableFunction)}.
*
* Lastly, the description of the command to be built can be set with {@link #description(String)}.
* The command itself can be built using the {@link #build()} method.
*
* @param <R>
* the return type of the created command
*/
public class CommandBuilder<R extends IResult> {
private final IFunctionFactory functionFactory;
private final ILanguageImpl lang;
private final IProject project;
private final String description;
private final @Nullable FailableFunction<String[], R, IResult> function;
private CommandBuilder(IFunctionFactory functionFactory, IProject project, ILanguageImpl lang,
String description, FailableFunction<String[], R, IResult> function) {
this.functionFactory = functionFactory;
this.project = project;
this.lang = lang;
this.description = description;
this.function = function;
}
/**
* Constructs a new {@link CommandBuilder} from the given parameters.
*
* @param functionFactory
* the {@link IFunctionFactory}
* @param project
* the {@link IProject} associated with all created commands
* @param lang
* the {@link ILanguageImpl} associated with all created commands
*/
@AssistedInject
public CommandBuilder(IFunctionFactory functionFactory, @Assisted IProject project,
@Assisted ILanguageImpl lang) {
this(functionFactory, project, lang, "", null);
}
/**
* Constructs a new {@link CommandBuilder} from a parent.
*
* @param parent
* the parent {@link CommandBuilder}
* @param description
* the description of the created command
* @param function
* the function the created command will execute
*/
private CommandBuilder(CommandBuilder<?> parent, String description,
FailableFunction<String[], R, IResult> function) {
this(parent.functionFactory, parent.project, parent.lang, description, function);
}
private FailableFunction<String, InputResult, IResult> inputFunction() {
return functionFactory.createInputFunction(project, lang);
}
private FailableFunction<String, ParseResult, IResult> parseFunction() {
return inputFunction().kleisliCompose(functionFactory.createParseFunction(project, lang));
}
private FailableFunction<String, AnalyzeResult, IResult> analyzeFunction() {
return parseFunction().kleisliCompose(functionFactory.createAnalyzeFunction(project, lang));
}
private FailableFunction<String, TransformResult, IResult>
pTransformFunction(ITransformAction action) {
return parseFunction()
.kleisliCompose(functionFactory.createPTransformFunction(project, lang, action));
}
private FailableFunction<String, TransformResult, IResult>
aTransformFunction(ITransformAction action) {
return analyzeFunction()
.kleisliCompose(functionFactory.createATransformFunction(project, lang, action));
}
private FailableFunction<String, EvaluateResult, IResult> pEvaluateFunction() {
return parseFunction().kleisliCompose(functionFactory.createPEvalFunction(project, lang));
}
private FailableFunction<String, EvaluateResult, IResult> aEvaluateFunction() {
return analyzeFunction().kleisliCompose(functionFactory.createAEvalFunction(project, lang));
}
/**
* Returns a function that creates an {@link InputResult} from a String.
*
* @return the builder
*/
public CommandBuilder<InputResult> input() {
return function(inputFunction());
}
/**
* Returns a function that creates a {@link ParseResult} from a String.
*
* @return the builder
*/
public CommandBuilder<ParseResult> parse() {
return function(parseFunction());
}
/**
* Returns a function that creates a {@link AnalyzeResult} from a String.
*
* @return the builder
*/
public CommandBuilder<AnalyzeResult> analyze() {
return function(analyzeFunction());
}
/**
* Returns a function that creates a parsed {@link TransformResult} from a String.
*
* @param action
* the associated {@link ITransformAction}
* @return the builder
*/
public CommandBuilder<TransformResult> transformParsed(ITransformAction action) {
return function(pTransformFunction(action));
}
/**
* Returns a function that creates an analyzed {@link TransformResult} from a String.
*
* @param action
* the associated {@link ITransformAction}
* @return the builder
*/
public CommandBuilder<TransformResult> transformAnalyzed(ITransformAction action) {
return function(aTransformFunction(action));
}
/**
* Returns a function that creates a parsed {@link EvaluateResult} from a String.
*
* @return the builder
*/
public CommandBuilder<EvaluateResult> evalParsed() {
return function(pEvaluateFunction());
}
/**
* Returns a function that creates an analyzed {@link EvaluateResult} from a String.
*
* @return the builder
*/
public CommandBuilder<EvaluateResult> evalAnalyzed() {
return function(aEvaluateFunction());
}
/**
* Set the function for a new builder with the current parameters. Discards the current function
* of this builder.
*
* @param func
* An initial {@link FailableFunction} accepting a String array and returning some
* {@link IResult}.
* @return A {@link CommandBuilder} with given function as current function.
* @param <OtherR>
* The return type of the given function.
*/
public <OtherR extends IResult> CommandBuilder<OtherR>
varFunction(FailableFunction<String[], OtherR, IResult> func) {
return new CommandBuilder<>(this, description, func);
}
/**
* Variant of {@link #varFunction(FailableFunction)} accepting a single string.
*
* @param func
* An initial {@link FailableFunction} accepting a String and returning some
* {@link IResult}.
* @return A {@link CommandBuilder} with given function as current function.
* @param <OtherR>
* The return type of the given function.
*/
public <OtherR extends IResult> CommandBuilder<OtherR>
function(FailableFunction<String, OtherR, IResult> func) {
return varFunction((String... args) -> func.apply(args[0]));
}
/**
* Compose a given {@link FailableFunction} with the current function.
*
* @param func
* A {@link FailableFunction} accepting the return type of the current function, and
* returning a new return type.
* @return A {@link CommandBuilder} with the composed {@link FailableFunction}.
* @param <NewR>
* The return type of the given function.
*/
public <NewR extends IResult> CommandBuilder<NewR>
compose(FailableFunction<R, NewR, IResult> func) {
Objects.requireNonNull(function,
"The current function cannot be null"
+ " before composing. Set a function with "
+ "one of the builder methods.");
return new CommandBuilder<>(this, description, this.function.kleisliCompose(func));
}
/**
* Sets the description of the created command.
*
* @param description
* the description of the command
* @return the builder
*/
public CommandBuilder<R> description(String description) {
return new CommandBuilder<>(this, description, function);
}
/**
* Returns an {@link IReplCommand} given a function.
*
* @return an {@link IReplCommand}
*/
public IReplCommand build() {
return new IReplCommand() {
@Override
public IResult execute(String... args) throws MetaborgException {
return function.apply(args);
}
@Override
public String description() {
return description;
}
};
}
}
|
org.metaborg.spoofax.shell.core/src/main/java/org/metaborg/spoofax/shell/commands/CommandBuilder.java
|
package org.metaborg.spoofax.shell.commands;
import java.util.Objects;
import javax.annotation.Nullable;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.action.ITransformAction;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.project.IProject;
import org.metaborg.spoofax.shell.client.IResult;
import org.metaborg.spoofax.shell.functions.FailableFunction;
import org.metaborg.spoofax.shell.functions.IFunctionFactory;
import org.metaborg.spoofax.shell.output.AnalyzeResult;
import org.metaborg.spoofax.shell.output.EvaluateResult;
import org.metaborg.spoofax.shell.output.InputResult;
import org.metaborg.spoofax.shell.output.ParseResult;
import org.metaborg.spoofax.shell.output.TransformResult;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
/**
* Builds commands by composing several smaller functional interfaces.
*
* @param <R>
* the return type of the created command
*/
public class CommandBuilder<R extends IResult> {
private final IFunctionFactory functionFactory;
private final ILanguageImpl lang;
private final IProject project;
private final String description;
private final @Nullable FailableFunction<String[], R, IResult> function;
private CommandBuilder(IFunctionFactory functionFactory, IProject project, ILanguageImpl lang,
String description, FailableFunction<String[], R, IResult> function) {
this.functionFactory = functionFactory;
this.project = project;
this.lang = lang;
this.description = description;
this.function = function;
}
/**
* Constructs a new {@link CommandBuilder} from the given parameters.
*
* @param functionFactory
* the {@link IFunctionFactory}
* @param project
* the {@link IProject} associated with all created commands
* @param lang
* the {@link ILanguageImpl} associated with all created commands
*/
@AssistedInject
public CommandBuilder(IFunctionFactory functionFactory, @Assisted IProject project,
@Assisted ILanguageImpl lang) {
this(functionFactory, project, lang, "", null);
}
/**
* Constructs a new {@link CommandBuilder} from a parent.
*
* @param parent
* the parent {@link CommandBuilder}
* @param description
* the description of the created command
* @param function
* the function the created command will execute
*/
private CommandBuilder(CommandBuilder<?> parent, String description,
FailableFunction<String[], R, IResult> function) {
this(parent.functionFactory, parent.project, parent.lang, description, function);
}
private FailableFunction<String, InputResult, IResult> inputFunction() {
return functionFactory.createInputFunction(project, lang);
}
private FailableFunction<String, ParseResult, IResult> parseFunction() {
return inputFunction().kleisliCompose(functionFactory.createParseFunction(project, lang));
}
private FailableFunction<String, AnalyzeResult, IResult> analyzeFunction() {
return parseFunction().kleisliCompose(functionFactory.createAnalyzeFunction(project, lang));
}
private FailableFunction<String, TransformResult, IResult>
pTransformFunction(ITransformAction action) {
return parseFunction()
.kleisliCompose(functionFactory.createPTransformFunction(project, lang, action));
}
private FailableFunction<String, TransformResult, IResult>
aTransformFunction(ITransformAction action) {
return analyzeFunction()
.kleisliCompose(functionFactory.createATransformFunction(project, lang, action));
}
private FailableFunction<String, EvaluateResult, IResult> pEvaluateFunction() {
return parseFunction().kleisliCompose(functionFactory.createPEvalFunction(project, lang));
}
private FailableFunction<String, EvaluateResult, IResult> aEvaluateFunction() {
return analyzeFunction().kleisliCompose(functionFactory.createAEvalFunction(project, lang));
}
/**
* Returns a function that creates an {@link InputResult} from a String.
*
* @return the builder
*/
public CommandBuilder<InputResult> input() {
return function(inputFunction());
}
/**
* Returns a function that creates a {@link ParseResult} from a String.
*
* @return the builder
*/
public CommandBuilder<ParseResult> parse() {
return function(parseFunction());
}
/**
* Returns a function that creates a {@link AnalyzeResult} from a String.
*
* @return the builder
*/
public CommandBuilder<AnalyzeResult> analyze() {
return function(analyzeFunction());
}
/**
* Returns a function that creates a parsed {@link TransformResult} from a String.
*
* @param action
* the associated {@link ITransformAction}
* @return the builder
*/
public CommandBuilder<TransformResult> transformParsed(ITransformAction action) {
return function(pTransformFunction(action));
}
/**
* Returns a function that creates an analyzed {@link TransformResult} from a String.
*
* @param action
* the associated {@link ITransformAction}
* @return the builder
*/
public CommandBuilder<TransformResult> transformAnalyzed(ITransformAction action) {
return function(aTransformFunction(action));
}
/**
* Returns a function that creates a parsed {@link EvaluateResult} from a String.
*
* @return the builder
*/
public CommandBuilder<EvaluateResult> evalParsed() {
return function(pEvaluateFunction());
}
/**
* Returns a function that creates an analyzed {@link EvaluateResult} from a String.
*
* @return the builder
*/
public CommandBuilder<EvaluateResult> evalAnalyzed() {
return function(aEvaluateFunction());
}
/**
* Set the function for a new builder with the current parameters. Discards the current function
* of this builder.
*
* @param func
* An initial {@link FailableFunction} accepting a String array and returning some
* {@link IResult}.
* @return A {@link CommandBuilder} with given function as current function.
* @param <OtherR>
* The return type of the given function.
*/
public <OtherR extends IResult> CommandBuilder<OtherR>
varFunction(FailableFunction<String[], OtherR, IResult> func) {
return new CommandBuilder<>(this, description, func);
}
/**
* Variant of {@link #varFunction(FailableFunction)} accepting a single string.
*
* @param func
* An initial {@link FailableFunction} accepting a String and returning some
* {@link IResult}.
* @return A {@link CommandBuilder} with given function as current function.
* @param <OtherR>
* The return type of the given function.
*/
public <OtherR extends IResult> CommandBuilder<OtherR>
function(FailableFunction<String, OtherR, IResult> func) {
return varFunction((String... args) -> func.apply(args[0]));
}
/**
* Compose a given {@link FailableFunction} with the current function.
*
* @param func
* A {@link FailableFunction} accepting the return type of the current function, and
* returning a new return type.
* @return A {@link CommandBuilder} with the composed {@link FailableFunction}.
* @param <NewR>
* The return type of the given function.
*/
public <NewR extends IResult> CommandBuilder<NewR>
compose(FailableFunction<R, NewR, IResult> func) {
Objects.requireNonNull(function,
"The current function cannot be null"
+ " before composing. Set a function with "
+ "one of the builder methods.");
return new CommandBuilder<>(this, description, this.function.kleisliCompose(func));
}
/**
* Sets the description of the created command.
*
* @param description
* the description of the command
* @return the builder
*/
public CommandBuilder<R> description(String description) {
return new CommandBuilder<>(this, description, function);
}
/**
* Returns an {@link IReplCommand} given a function.
*
* @return an {@link IReplCommand}
*/
public IReplCommand build() {
return new IReplCommand() {
@Override
public IResult execute(String... args) throws MetaborgException {
return function.apply(args);
}
@Override
public String description() {
return description;
}
};
}
}
|
Add javadoc class comment to CommandBuilder
|
org.metaborg.spoofax.shell.core/src/main/java/org/metaborg/spoofax/shell/commands/CommandBuilder.java
|
Add javadoc class comment to CommandBuilder
|
|
Java
|
apache-2.0
|
da35df17e0ba6e5f07395c9f296fa75c3cf981a5
| 0
|
PRIDE-Cluster/cluster-web-service,PRIDE-Cluster/cluster-web-service,PRIDE-Cluster/cluster-web-service
|
package uk.ac.ebi.pride.cluster.ws.modules.cluster.util;
/**
* @author Jose A. Dianes <jdianes@ebi.ac.uk>
*/
public class SpeciesCount {
private String speciesName;
private long count;
public SpeciesCount(String speciesName, long count) {
this.speciesName = speciesName;
this.count = count;
}
public String getSpeciesName() {
return speciesName;
}
public void setSpeciesName(String speciesName) {
this.speciesName = speciesName;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public void addSpeciesCount(long n) {
this.count += n;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SpeciesCount)) return false;
SpeciesCount that = (SpeciesCount) o;
if (count != that.count) return false;
if (speciesName != null ? !speciesName.equals(that.speciesName) : that.speciesName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = speciesName != null ? speciesName.hashCode() : 0;
result = 31 * result + (int) (count ^ (count >>> 32));
return result;
}
@Override
public String toString() {
return "SpeciesCount{" +
"speciesName='" + speciesName + '\'' +
", count=" + count +
'}';
}
}
|
src/main/java/uk/ac/ebi/pride/cluster/ws/modules/cluster/util/SpeciesCount.java
|
package uk.ac.ebi.pride.cluster.ws.modules.cluster.util;
/**
* @author Jose A. Dianes <jdianes@ebi.ac.uk>
*/
public class SpeciesCount {
private String speciesName;
private long speciesCount;
public SpeciesCount(String speciesName, long speciesCount) {
this.speciesName = speciesName;
this.speciesCount = speciesCount;
}
public String getSpeciesName() {
return speciesName;
}
public void setSpeciesName(String speciesName) {
this.speciesName = speciesName;
}
public long getSpeciesCount() {
return speciesCount;
}
public void setSpeciesCount(long speciesCount) {
this.speciesCount = speciesCount;
}
public void addSpeciesCount(long n) {
this.speciesCount += n;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SpeciesCount)) return false;
SpeciesCount that = (SpeciesCount) o;
if (speciesCount != that.speciesCount) return false;
if (speciesName != null ? !speciesName.equals(that.speciesName) : that.speciesName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = speciesName != null ? speciesName.hashCode() : 0;
result = 31 * result + (int) (speciesCount ^ (speciesCount >>> 32));
return result;
}
@Override
public String toString() {
return "SpeciesCount{" +
"speciesName='" + speciesName + '\'' +
", speciesCount=" + speciesCount +
'}';
}
}
|
change both the species and the modification chats to have limited amount of items, and group the others into "Others" category
|
src/main/java/uk/ac/ebi/pride/cluster/ws/modules/cluster/util/SpeciesCount.java
|
change both the species and the modification chats to have limited amount of items, and group the others into "Others" category
|
|
Java
|
apache-2.0
|
2da0a6e2dfd9a0f0932d3b3547a5190ce1ce416e
| 0
|
ic3fox/jawr,ic3fox/jawr,ic3fox/jawr,ic3fox/jawr
|
package test.net.jawr.web.resource.bundle.generator.js.coffee;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.when;
import net.jawr.web.JawrConstant;
import net.jawr.web.config.JawrConfig;
import net.jawr.web.resource.bundle.IOUtils;
import net.jawr.web.resource.bundle.JoinableResourceBundle;
import net.jawr.web.resource.bundle.generator.GeneratorContext;
import net.jawr.web.resource.bundle.generator.GeneratorRegistry;
import net.jawr.web.resource.bundle.generator.js.coffee.CoffeeScriptGenerator;
import net.jawr.web.resource.bundle.handler.ResourceBundlesHandler;
import net.jawr.web.resource.bundle.iterator.BundlePath;
import net.jawr.web.resource.bundle.iterator.ConditionalCommentCallbackHandler;
import net.jawr.web.resource.bundle.iterator.ResourceBundlePathsIterator;
import net.jawr.web.resource.handler.reader.ResourceReaderHandler;
import test.net.jawr.web.FileUtils;
import test.net.jawr.web.servlet.mock.MockServletContext;
import test.net.jawr.web.util.js.rhino.JSEngineUtils;
@RunWith(Parameterized.class)
public class CoffeeScriptGeneratorTestCase {
private static Logger LOGGER = LoggerFactory.getLogger(CoffeeScriptGeneratorTestCase.class);
private static String WORK_DIR = "workDirCoffee";
@Parameter
public String jsEngineName;
@Parameters
public static List<Object[]> jsEnginesToTestWith() {
return Arrays.asList(new Object[][] { { JawrConstant.DEFAULT_JS_ENGINE }, { "nashorn" } });
}
private JawrConfig config;
private GeneratorContext ctx;
private CoffeeScriptGenerator generator;
@Mock
private ResourceBundlesHandler resourceBundlesHandler;
@Mock
private ResourceBundlePathsIterator pathIterator;
@Mock
private JoinableResourceBundle bundle;
@Mock
private ResourceReaderHandler rsReaderHandler;
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
initMocks(this);
final String bundlePath = "/temp.coffee";
config = new JawrConfig("js", new Properties());
ServletContext servletContext = new MockServletContext();
when(pathIterator.next()).thenReturn(new BundlePath(null, bundlePath));
when(pathIterator.nextPath()).thenReturn(new BundlePath(null, bundlePath));
when(pathIterator.hasNext()).thenReturn(true, false, false);
when(resourceBundlesHandler.getBundlePaths(Matchers.anyString(),
Matchers.any(ConditionalCommentCallbackHandler.class), Matchers.anyMapOf(String.class, String.class)))
.thenReturn(pathIterator);
when(resourceBundlesHandler.resolveBundleForPath(bundlePath)).thenReturn(bundle);
servletContext.setAttribute(JawrConstant.JS_CONTEXT_ATTRIBUTE, resourceBundlesHandler);
// getMockBundlesHandler(config, paths));
config.setContext(servletContext);
config.setServletMapping("/js");
config.setCharsetName("UTF-8");
GeneratorRegistry generatorRegistry = addGeneratorRegistryToConfig(config, JawrConstant.JS_TYPE);
generator = new CoffeeScriptGenerator();
FileUtils.clearDirectory(FileUtils.getClasspathRootDir() + File.separator + WORK_DIR);
FileUtils.createDir(WORK_DIR);
generator.setWorkingDirectory(FileUtils.getClasspathRootDir() + "/" + WORK_DIR);
ctx = new GeneratorContext(bundle, config, bundlePath);
ctx.setResourceReaderHandler(rsReaderHandler);
generatorRegistry.setResourceReaderHandler(ctx.getResourceReaderHandler());
// Make sure that the version of temp.coffee is the right one
FileUtils.copyFile("generator/js/coffeescript/temp.coffee.backup", "generator/js/coffeescript/temp.coffee");
when(rsReaderHandler.getFilePath(Matchers.anyString()))
.thenReturn(FileUtils.getClassPathFileAbsolutePath("generator/js/coffeescript/temp.coffee"));
Mockito.doAnswer(new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
File f = new File((String) args[0]);
Long result = f.lastModified();
return result;
}
}).when(rsReaderHandler).getLastModified(Matchers.anyString());
Mockito.doAnswer(new Answer<Reader>() {
@Override
public Reader answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Reader rd = null;
try {
final String content = FileUtils.readClassPathFile("generator/js/coffeescript" + args[1]);
rd = new StringReader(content);
} catch (IOException ex) {
// Do nothing
}
return rd;
}
}).when(rsReaderHandler).getResource(Matchers.any(JoinableResourceBundle.class), Matchers.anyString(),
Matchers.anyBoolean(), (List<Class<?>>) Matchers.any());
generator.setResourceReaderHandler(rsReaderHandler);
generator.setConfig(config);
generator.afterPropertiesSet();
}
@After
public void tearDown() throws Exception {
// Make sure that the version of temp.coffee is the right one
FileUtils.copyFile("generator/js/coffeescript/temp.coffee.backup", "generator/js/coffeescript/temp.coffee");
}
/**
* Checks if the JS engine is available
*
* @return true if JS engine is available
*/
private boolean isJsEngineAvailable() {
return JSEngineUtils.isJsEngineAvailable(jsEngineName, LOGGER);
}
@Test
public void testBundleGenerator() throws Exception {
if (isJsEngineAvailable()) {
Reader rd = generator.createResource(ctx);
String content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve from cache in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve in debug mode (should be read from cache)
ctx.setProcessingBundle(false);
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve in debug mode (should be read from cache)
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
FileUtils.copyFile("generator/js/coffeescript/temp2.coffee", "generator/js/coffeescript/temp.coffee");
when(rsReaderHandler.getLastModified("generator/js/coffeescript/temp.coffee"))
.thenReturn(Calendar.getInstance().getTimeInMillis() + 3);
ctx.setProcessingBundle(true);
// Retrieve updated version in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version from cache in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version in debug mode from cache
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version in debug mode from cache
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
}
}
private GeneratorRegistry addGeneratorRegistryToConfig(JawrConfig config, String type) {
GeneratorRegistry generatorRegistry = new GeneratorRegistry(type);
generatorRegistry.setConfig(config);
config.setGeneratorRegistry(generatorRegistry);
return generatorRegistry;
}
}
|
jawr-core/src/test/java/test/net/jawr/web/resource/bundle/generator/js/coffee/CoffeeScriptGeneratorTestCase.java
|
package test.net.jawr.web.resource.bundle.generator.js.coffee;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.when;
import net.jawr.web.JawrConstant;
import net.jawr.web.config.JawrConfig;
import net.jawr.web.resource.bundle.IOUtils;
import net.jawr.web.resource.bundle.JoinableResourceBundle;
import net.jawr.web.resource.bundle.generator.GeneratorContext;
import net.jawr.web.resource.bundle.generator.GeneratorRegistry;
import net.jawr.web.resource.bundle.generator.js.coffee.CoffeeScriptGenerator;
import net.jawr.web.resource.bundle.handler.ResourceBundlesHandler;
import net.jawr.web.resource.bundle.iterator.BundlePath;
import net.jawr.web.resource.bundle.iterator.ConditionalCommentCallbackHandler;
import net.jawr.web.resource.bundle.iterator.ResourceBundlePathsIterator;
import net.jawr.web.resource.handler.reader.ResourceReaderHandler;
import test.net.jawr.web.FileUtils;
import test.net.jawr.web.servlet.mock.MockServletContext;
import test.net.jawr.web.util.js.rhino.JSEngineUtils;
@RunWith(Parameterized.class)
public class CoffeeScriptGeneratorTestCase {
private static Logger LOGGER = LoggerFactory.getLogger(CoffeeScriptGeneratorTestCase.class);
private static String WORK_DIR = "workDirCoffee";
@Parameter
public String jsEngineName;
@Parameters
public static List<Object[]> jsEnginesToTestWith() {
return Arrays.asList(new Object[][] { { JawrConstant.DEFAULT_JS_ENGINE }, { "nashorn" } });
}
private JawrConfig config;
private GeneratorContext ctx;
private CoffeeScriptGenerator generator;
@Mock
private ResourceBundlesHandler resourceBundlesHandler;
@Mock
private ResourceBundlePathsIterator pathIterator;
@Mock
private JoinableResourceBundle bundle;
@Mock
private ResourceReaderHandler rsReaderHandler;
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
initMocks(this);
final String bundlePath = "/temp.coffee";
config = new JawrConfig("js", new Properties());
ServletContext servletContext = new MockServletContext();
when(pathIterator.next()).thenReturn(new BundlePath(null, bundlePath));
when(pathIterator.nextPath()).thenReturn(new BundlePath(null, bundlePath));
when(pathIterator.hasNext()).thenReturn(true, false, false);
when(resourceBundlesHandler.getBundlePaths(Matchers.anyString(),
Matchers.any(ConditionalCommentCallbackHandler.class), Matchers.anyMapOf(String.class, String.class)))
.thenReturn(pathIterator);
when(resourceBundlesHandler.resolveBundleForPath(bundlePath)).thenReturn(bundle);
servletContext.setAttribute(JawrConstant.JS_CONTEXT_ATTRIBUTE, resourceBundlesHandler);
// getMockBundlesHandler(config, paths));
config.setContext(servletContext);
config.setServletMapping("/js");
config.setCharsetName("UTF-8");
GeneratorRegistry generatorRegistry = addGeneratorRegistryToConfig(config, JawrConstant.JS_TYPE);
generator = new CoffeeScriptGenerator();
FileUtils.clearDirectory(FileUtils.getClasspathRootDir() + File.separator + WORK_DIR);
FileUtils.createDir(WORK_DIR);
generator.setWorkingDirectory(FileUtils.getClasspathRootDir() + "/" + WORK_DIR);
ctx = new GeneratorContext(bundle, config, bundlePath);
ctx.setResourceReaderHandler(rsReaderHandler);
generatorRegistry.setResourceReaderHandler(ctx.getResourceReaderHandler());
// Make sure that the version of temp.coffee is the right one
FileUtils.copyFile("generator/js/coffeescript/temp.coffee.backup", "generator/js/coffeescript/temp.coffee");
when(rsReaderHandler.getFilePath(Matchers.anyString())).thenReturn(FileUtils.getClassPathFileAbsolutePath("generator/js/coffeescript/temp.coffee"));
Mockito.doAnswer(new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
File f = new File((String) args[0]);
Long result = f.lastModified();
return result;
}
}).when(rsReaderHandler).getLastModified(Matchers.anyString());
Mockito.doAnswer(new Answer<Reader>() {
@Override
public Reader answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Reader rd = null;
try {
final String content = FileUtils.readClassPathFile("generator/js/coffeescript" + args[1]);
rd = new StringReader(content);
} catch (IOException ex) {
// Do nothing
}
return rd;
}
}).when(rsReaderHandler).getResource(Matchers.any(JoinableResourceBundle.class), Matchers.anyString(),
Matchers.anyBoolean(), (List<Class<?>>) Matchers.any());
generator.setResourceReaderHandler(rsReaderHandler);
generator.setConfig(config);
generator.afterPropertiesSet();
}
@After
public void tearDown() throws Exception {
// Make sure that the version of temp.coffee is the right one
FileUtils.copyFile("generator/js/coffeescript/temp.coffee.backup", "generator/js/coffeescript/temp.coffee");
}
/**
* Checks if the JS engine is available
*
* @return true if JS engine is available
*/
private boolean isJsEngineAvailable() {
return JSEngineUtils.isJsEngineAvailable(jsEngineName, LOGGER);
}
@SuppressWarnings("unchecked")
@Test
public void testBundleGenerator() throws Exception {
if (isJsEngineAvailable()) {
Reader rd = generator.createResource(ctx);
String content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve from cache in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve in debug mode (should be read from cache)
ctx.setProcessingBundle(false);
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
// Retrieve in debug mode (should be read from cache)
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected.js"), content);
FileUtils.copyFile("generator/js/coffeescript/temp2.coffee", "generator/js/coffeescript/temp.coffee");
Mockito.doAnswer(new Answer<Reader>() {
@Override
public Reader answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Reader rd = null;
try {
final String content = FileUtils.readClassPathFile("generator/js/coffeescript" + args[1]);
rd = new StringReader(content);
} catch (IOException ex) {
// Do nothing
}
return rd;
}
}).when(rsReaderHandler).getResource(Matchers.any(JoinableResourceBundle.class), Matchers.anyString(),
Matchers.anyBoolean(), (List<Class<?>>) Matchers.any());
ctx.setProcessingBundle(true);
// Retrieve updated version in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version from cache in production mode
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version in debug mode from cache
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
// Retrieve updated version in debug mode from cache
rd = generator.createResource(ctx);
content = IOUtils.toString(rd);
Assert.assertEquals(FileUtils.readClassPathFile("generator/js/coffeescript/expected_updated.js"), content);
}
}
private GeneratorRegistry addGeneratorRegistryToConfig(JawrConfig config, String type) {
GeneratorRegistry generatorRegistry = new GeneratorRegistry(type);
generatorRegistry.setConfig(config);
config.setGeneratorRegistry(generatorRegistry);
return generatorRegistry;
}
}
|
Fix issue in Coffeescript generator unit test
|
jawr-core/src/test/java/test/net/jawr/web/resource/bundle/generator/js/coffee/CoffeeScriptGeneratorTestCase.java
|
Fix issue in Coffeescript generator unit test
|
|
Java
|
apache-2.0
|
ec945317ea7eeab851a6034a952db9f45afe4a20
| 0
|
astrapi69/wicket,AlienQueen/wicket,mosoft521/wicket,mafulafunk/wicket,topicusonderwijs/wicket,freiheit-com/wicket,bitstorm/wicket,topicusonderwijs/wicket,dashorst/wicket,bitstorm/wicket,selckin/wicket,freiheit-com/wicket,selckin/wicket,selckin/wicket,apache/wicket,dashorst/wicket,klopfdreh/wicket,mosoft521/wicket,Servoy/wicket,martin-g/wicket-osgi,mosoft521/wicket,bitstorm/wicket,apache/wicket,apache/wicket,zwsong/wicket,zwsong/wicket,dashorst/wicket,selckin/wicket,bitstorm/wicket,AlienQueen/wicket,mafulafunk/wicket,Servoy/wicket,aldaris/wicket,aldaris/wicket,Servoy/wicket,klopfdreh/wicket,AlienQueen/wicket,astrapi69/wicket,AlienQueen/wicket,selckin/wicket,astrapi69/wicket,AlienQueen/wicket,martin-g/wicket-osgi,apache/wicket,Servoy/wicket,zwsong/wicket,astrapi69/wicket,dashorst/wicket,aldaris/wicket,aldaris/wicket,freiheit-com/wicket,mosoft521/wicket,Servoy/wicket,dashorst/wicket,zwsong/wicket,bitstorm/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,klopfdreh/wicket,topicusonderwijs/wicket,aldaris/wicket,freiheit-com/wicket,apache/wicket,freiheit-com/wicket,klopfdreh/wicket,mosoft521/wicket,mafulafunk/wicket,topicusonderwijs/wicket,klopfdreh/wicket
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.html.tree;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import org.apache.wicket.Component;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.resources.JavascriptResourceReference;
import org.apache.wicket.model.IDetachable;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.AppendingStringBuffer;
import sun.reflect.generics.tree.Tree;
/**
* This class encapsulates the logic for displaying and (partial) updating the tree. Actual
* presentation is out of scope of this class. User should derive they own tree (if needed) from
* {@link DefaultAbstractTree} or {@link Tree} (recommended).
*
* @author Matej Knopp
*/
public abstract class AbstractTree extends Panel implements ITreeStateListener, TreeModelListener
{
/**
* Interface for visiting individual tree items.
*/
private static interface IItemCallback
{
/**
* Visits the tree item.
*
* @param item
* the item to visit
*/
void visitItem(TreeItem item);
}
/**
* This class represents one row in rendered tree (TreeNode). Only TreeNodes that are visible
* (all their parent are expanded) have TreeItem created for them.
*/
private final class TreeItem extends WebMarkupContainer
{
/**
* whether this tree item should also render it's children to response. this is set if we
* need the whole subtree rendered as one component in ajax response, so that we can replace
* it in one step (replacing individual rows is very slow in javascript, therefore we
* replace the whole subtree)
*/
private final static int FLAG_RENDER_CHILDREN = FLAG_RESERVED8;
private static final long serialVersionUID = 1L;
/**
* tree item children - we need this to traverse items in correct order when rendering
*/
private List children = null;
/** tree item level - how deep is this item in tree */
private final int level;
/**
* Construct.
*
* @param id
* The component id
* @param node
* tree node
* @param level
* current level
*/
public TreeItem(String id, final TreeNode node, int level)
{
super(id, new Model((Serializable)node));
nodeToItemMap.put(node, this);
this.level = level;
setOutputMarkupId(true);
// if this isn't a root item in rootless mode
if (level != -1)
{
populateTreeItem(this, level);
}
}
/**
* @return The children
*/
public List getChildren()
{
return children;
}
/**
* @return The current level
*/
public int getLevel()
{
return level;
}
/**
* @see org.apache.wicket.Component#getMarkupId()
*/
public String getMarkupId()
{
// this is overriden to produce id that begins with id of tree
// if the tree has set (shorter) id in markup, we can use it to
// shorten the id of individual TreeItems
return AbstractTree.this.getMarkupId() + "_" + getId();
}
/**
* @return parent item
*/
public TreeItem getParentItem()
{
return (TreeItem)nodeToItemMap.get(((TreeNode)getModelObject()).getParent());
}
/**
* Sets the children.
*
* @param children
* The children
*/
public void setChildren(List children)
{
this.children = children;
}
/**
* Whether to render children.
*
* @return whether to render children
*/
protected final boolean isRenderChildren()
{
return getFlag(FLAG_RENDER_CHILDREN);
}
/**
* @see org.apache.wicket.MarkupContainer#onRender(org.apache.wicket.markup.MarkupStream)
*/
protected void onRender(final MarkupStream markupStream)
{
// is this root and tree is in rootless mode?
if (this == rootItem && isRootLess() == true)
{
// yes, write empty div with id
// this is necesary for createElement js to work correctly
getResponse().write(
"<div style=\"display:none\" id=\"" + getMarkupId() + "\"></div>");
markupStream.skipComponent();
}
else
{
// remember current index
final int index = markupStream.getCurrentIndex();
// render the item
super.onRender(markupStream);
// should we also render children (ajax response)
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
// rewind markupStream
markupStream.setCurrentIndex(index);
// render child
item.onRender(markupStream);
}
});
//
}
}
}
public void renderHead(final HtmlHeaderContainer container)
{
super.renderHead(container);
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
// write header contributions from the children of item
item.visitChildren(new Component.IVisitor()
{
public Object component(Component component)
{
if (component.isVisible())
{
component.renderHead(container);
return CONTINUE_TRAVERSAL;
}
else
{
return CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
}
}
});
}
});
}
}
protected final void setRenderChildren(boolean value)
{
setFlag(FLAG_RENDER_CHILDREN, value);
}
protected void onAttach()
{
super.onAttach();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.attach();
}
});
}
}
protected void onDetach()
{
super.onDetach();
Object object = getModelObject();
if (object instanceof IDetachable)
{
((IDetachable)object).detach();
}
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.detach();
}
});
}
// children are rendered, clear the flag
setRenderChildren(false);
}
protected void onBeforeRender()
{
onBeforeRenderInternal();
super.onBeforeRender();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.prepareForRender();
}
});
}
}
protected void onAfterRender()
{
super.onAfterRender();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.afterRender();
}
});
}
}
}
/**
* Components that holds tree items. This is similiar to ListView, but it renders tree items in
* the right order.
*/
private class TreeItemContainer extends WebMarkupContainer
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param id
* The component id
*/
public TreeItemContainer(String id)
{
super(id);
}
/**
* @see org.apache.wicket.MarkupContainer#remove(org.apache.wicket.Component)
*/
public void remove(Component component)
{
// when a treeItem is removed, remove reference to it from
// nodeToItemMAp
if (component instanceof TreeItem)
{
nodeToItemMap.remove(((TreeItem)component).getModelObject());
}
super.remove(component);
}
/**
* renders the tree items, making sure that items are rendered in the order they should be
*
* @param markupStream
*/
protected void onRender(final MarkupStream markupStream)
{
// Save position in markup stream
final int markupStart = markupStream.getCurrentIndex();
// have we rendered at least one item?
final class Rendered
{
boolean rendered = false;
}
;
final Rendered rendered = new Rendered();
// is there a root item? (non-empty tree)
if (rootItem != null)
{
IItemCallback callback = new IItemCallback()
{
public void visitItem(TreeItem item)
{
// rewind markup stream
markupStream.setCurrentIndex(markupStart);
// render component
item.render(markupStream);
rendered.rendered = true;
}
};
// visit item and it's children
visitItemAndChildren(rootItem, callback);
}
if (rendered.rendered == false)
{
// tree is empty, just move the markupStream
markupStream.skipComponent();
}
}
}
/**
* Returns an iterator that iterates trough the enumeration.
*
* @param enumeration
* The enumeration to iterate through
* @return The iterator
*/
private static final Iterator toIterator(final Enumeration enumeration)
{
return new Iterator()
{
private final Enumeration e = enumeration;
public boolean hasNext()
{
return e.hasMoreElements();
}
public Object next()
{
return e.nextElement();
}
public void remove()
{
throw new UnsupportedOperationException("Remove is not supported on enumeration.");
}
};
}
private boolean attached = false;
/** comma separated list of ids of elements to be deleted. */
private final AppendingStringBuffer deleteIds = new AppendingStringBuffer();
/**
* whether the whole tree is dirty (so the whole tree needs to be refreshed).
*/
private boolean dirtyAll = false;
/**
* list of dirty items. if children property of these items is null, the chilren will be
* rebuild.
*/
private final List dirtyItems = new ArrayList();
/**
* list of dirty items which need the DOM structure to be created for them (added items)
*/
private final List dirtyItemsCreateDOM = new ArrayList();
/** counter for generating unique ids of every tree item. */
private int idCounter = 0;
/** Component whose children are tree items. */
private TreeItemContainer itemContainer;
/**
* map that maps TreeNode to TreeItem. TreeItems only exists for TreeNodes, that are visibled
* (their parents are not collapsed).
*/
private final Map nodeToItemMap = new HashMap();
/**
* we need to track previous model. if the model changes, we unregister the tree from listeners
* of old model and register the tree as litener of new model.
*/
private TreeModel previousModel = null;
/** root item of the tree. */
private TreeItem rootItem = null;
/** whether the tree root is shown. */
private boolean rootLess = false;
/** stores reference to tree state. */
private ITreeState state;
/**
* Tree constructor
*
* @param id
* The component id
*/
public AbstractTree(String id)
{
super(id);
init();
}
/**
* Tree constructor
*
* @param id
* The component id
* @param model
* The tree model
*/
public AbstractTree(String id, IModel model)
{
super(id, model);
init();
}
/** called when all nodes are collapsed. */
public final void allNodesCollapsed()
{
invalidateAll();
}
/** called when all nodes are expaned. */
public final void allNodesExpanded()
{
invalidateAll();
}
/**
* Returns the TreeState of this tree.
*
* @return Tree state instance
*/
public ITreeState getTreeState()
{
if (state == null)
{
state = newTreeState();
// add this object as listener of the state
state.addTreeStateListener(this);
// FIXME: Where should we remove the listener?
}
return state;
}
/**
* This method is called before the onAttach is called. Code here gets executed before the items
* have been populated.
*/
protected void onBeforeAttach()
{
}
// This is necessary because MarkupContainer.onBeforeRender involves calling
// beforeRender on children, which results in stack overflow when called from TreeItem
private void onBeforeRenderInternal()
{
if (attached == false)
{
onBeforeAttach();
checkModel();
// Do we have to rebuld the whole tree?
if (dirtyAll && rootItem != null)
{
clearAllItem();
}
else
{
// rebuild chilren of dirty nodes that need it
rebuildDirty();
}
// is root item created? (root item is null if the items have not
// been created yet, or the whole tree was dirty and clearAllITem
// has been called
if (rootItem == null)
{
TreeNode rootNode = (TreeNode)((TreeModel)getModelObject()).getRoot();
if (rootNode != null)
{
if (isRootLess())
{
rootItem = newTreeItem(rootNode, -1);
}
else
{
rootItem = newTreeItem(rootNode, 0);
}
itemContainer.add(rootItem);
buildItemChildren(rootItem);
}
}
attached = true;
}
}
/**
* Called at the beginning of the request (not ajax request, unless we are rendering the entire
* component)
*/
public void onBeforeRender()
{
onBeforeRenderInternal();
super.onBeforeRender();
}
/**
* @see org.apache.wicket.MarkupContainer#onDetach()
*/
public void onDetach()
{
attached = false;
super.onDetach();
}
/**
* Call to refresh the whole tree. This should only be called when the roodNode has been
* replaced or the entiry tree model changed.
*/
public final void invalidateAll()
{
updated();
dirtyAll = true;
}
/**
* @return whether the tree root is shown
*/
public final boolean isRootLess()
{
return rootLess;
};
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeCollapsed(javax.swing.tree.TreeNode)
*/
public final void nodeCollapsed(TreeNode node)
{
if (isNodeVisible(node) == true)
{
invalidateNodeWithChildren(node);
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeExpanded(javax.swing.tree.TreeNode)
*/
public final void nodeExpanded(TreeNode node)
{
if (isNodeVisible(node) == true)
{
invalidateNodeWithChildren(node);
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeSelected(javax.swing.tree.TreeNode)
*/
public final void nodeSelected(TreeNode node)
{
if (isNodeVisible(node))
{
invalidateNode(node, isForceRebuildOnSelectionChange());
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeUnselected(javax.swing.tree.TreeNode)
*/
public final void nodeUnselected(TreeNode node)
{
if (isNodeVisible(node))
{
invalidateNode(node, isForceRebuildOnSelectionChange());
}
}
/**
* Determines whether the TreeNode needs to be rebuilt if it is selected or deselected
*
* @return true if the node should be rebuilt after (de)selection, false otherwise
*/
protected boolean isForceRebuildOnSelectionChange()
{
return true;
}
/**
* Sets whether the root of the tree should be visible.
*
* @param rootLess
* whether the root should be visible
*/
public void setRootLess(boolean rootLess)
{
if (this.rootLess != rootLess)
{
this.rootLess = rootLess;
invalidateAll();
// if the tree is in rootless mode, make sure the root node is
// expanded
if (rootLess == true && getModelObject() != null)
{
getTreeState().expandNode((TreeNode)((TreeModel)getModelObject()).getRoot());
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesChanged(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesChanged(TreeModelEvent e)
{
// has root node changed?
if (e.getChildren() == null)
{
if (rootItem != null)
{
invalidateNode((TreeNode)rootItem.getModelObject(), true);
}
}
else
{
// go through all changed nodes
Object[] children = e.getChildren();
if (children != null)
{
for (int i = 0; i < children.length; i++)
{
TreeNode node = (TreeNode)children[i];
if (isNodeVisible(node))
{
// if the nodes is visible invalidate it
invalidateNode(node, true);
}
}
}
}
};
/**
* Marks the last but one visible child node of the given item as dirty, if give child is the
* last item of parent.
*
* We need this to refresh the previous visible item in case the inserted / deleteditem was
* last. The reason is that the line shape of previous item chages from L to |- .
*
* @param parent
* @param child
*/
private void markTheLastButOneChildDirty(TreeItem parent, TreeItem child)
{
if (parent.getChildren().indexOf(child) == parent.getChildren().size() - 1)
{
// go through the childrend backwards, start at the last but one
// item
for (int i = parent.getChildren().size() - 2; i >= 0; --i)
{
TreeItem item = (TreeItem)parent.getChildren().get(i);
// invalidate the node and it's children, so that they are
// redrawn
invalidateNodeWithChildren((TreeNode)item.getModelObject());
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesInserted(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesInserted(TreeModelEvent e)
{
// get the parent node of inserted nodes
TreeNode parent = (TreeNode)e.getTreePath().getLastPathComponent();
if (isNodeVisible(parent) && isNodeExpanded(parent))
{
TreeItem parentItem = (TreeItem)nodeToItemMap.get(parent);
for (int i = 0; i < e.getChildren().length; ++i)
{
TreeNode node = (TreeNode)e.getChildren()[i];
int index = e.getChildIndices()[i];
TreeItem item = newTreeItem(node, parentItem.getLevel() + 1);
itemContainer.add(item);
parentItem.getChildren().add(index, item);
markTheLastButOneChildDirty(parentItem, item);
dirtyItems.add(item);
dirtyItemsCreateDOM.add(item);
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesRemoved(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesRemoved(TreeModelEvent e)
{
// get the parent node of inserted nodes
TreeNode parent = (TreeNode)e.getTreePath().getLastPathComponent();
TreeItem parentItem = (TreeItem)nodeToItemMap.get(parent);
if (isNodeVisible(parent) && isNodeExpanded(parent))
{
for (int i = 0; i < e.getChildren().length; ++i)
{
TreeNode node = (TreeNode)e.getChildren()[i];
TreeItem item = (TreeItem)nodeToItemMap.get(node);
if (item != null)
{
markTheLastButOneChildDirty(parentItem, item);
parentItem.getChildren().remove(item);
// go though item children and remove every one of them
visitItemChildren(item, new IItemCallback()
{
public void visitItem(TreeItem item)
{
removeItem(item);
// unselect the node
getTreeState().selectNode((TreeNode)item.getModelObject(), false);
}
});
removeItem(item);
}
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeStructureChanged(javax.swing.event.TreeModelEvent)
*/
public final void treeStructureChanged(TreeModelEvent e)
{
// get the parent node of changed nodes
TreeNode node = (TreeNode)e.getTreePath().getLastPathComponent();
// has the tree root changed?
if (e.getTreePath().getPathCount() == 1 && node.equals(rootItem.getModelObject()))
{
invalidateAll();
}
else
{
invalidateNodeWithChildren(node);
}
}
/**
* Updates the changed portions of the tree using given AjaxRequestTarget. Call this method if
* you modified the tree model during an ajax request target and you want to partially update
* the component on page. Make sure that the tree model has fired the proper listener functions.
* <p>
* <b>You can only call this method once in a request.</b>
*
* @param target
* Ajax request target used to send the update to the page
*/
public final void updateTree(final AjaxRequestTarget target)
{
if (target == null)
{
return;
}
// check whether the model hasn't changed
checkModel();
// is the whole tree dirty
if (dirtyAll)
{
// render entire tree component
target.addComponent(this);
}
else
{
// remove DOM elements that need to be removed
if (deleteIds.length() != 0)
{
String js = getElementsDeleteJavascript();
// add the javascript to target
target.prependJavascript(js);
}
// We have to repeat this as long as there are any dirty items to be
// created.
// The reason why we can't do this in one pass is that some of the
// items
// may need to be inserted after items that has not been inserted
// yet, so we have
// to detect those and wait until the items they depend on are
// inserted.
while (dirtyItemsCreateDOM.isEmpty() == false)
{
for (Iterator i = dirtyItemsCreateDOM.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
TreeItem parent = item.getParentItem();
int index = parent.getChildren().indexOf(item);
TreeItem previous;
// we need item before this (in dom structure)
if (index == 0)
{
previous = parent;
}
else
{
previous = (TreeItem)parent.getChildren().get(index - 1);
// get the last item of previous item subtree
while (previous.getChildren() != null && previous.getChildren().size() > 0)
{
previous = (TreeItem)previous.getChildren().get(
previous.getChildren().size() - 1);
}
}
// check if the previous item isn't waiting to be inserted
if (dirtyItemsCreateDOM.contains(previous) == false)
{
// it's already in dom, so we can use it as point of
// insertion
target.prependJavascript("Wicket.Tree.createElement(\"" +
item.getMarkupId() + "\"," + "\"" + previous.getMarkupId() + "\")");
// remove the item so we don't process it again
i.remove();
}
else
{
// we don't do anything here, inserting this item will
// have to wait
// until the previous item gets inserted
}
}
}
// iterate through dirty items
for (Iterator i = dirtyItems.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
// does the item need to rebuild children?
if (item.getChildren() == null)
{
// rebuld the children
buildItemChildren(item);
// set flag on item so that it renders itself together with
// it's children
item.setRenderChildren(true);
}
// add the component to target
target.addComponent(item);
}
// clear dirty flags
updated();
}
}
/**
* Returns whether the given node is expanded.
*
* @param node
* The node to inspect
* @return true if the node is expanded, false otherwise
*/
protected final boolean isNodeExpanded(TreeNode node)
{
// In root less mode the root node is always expanded
if (isRootLess() && rootItem != null && rootItem.getModelObject().equals(node))
{
return true;
}
return getTreeState().isNodeExpanded(node);
}
/**
* Creates the TreeState, which is an object where the current state of tree (which nodes are
* expanded / collapsed, selected, ...) is stored.
*
* @return Tree state instance
*/
protected ITreeState newTreeState()
{
return new DefaultTreeState();
}
/**
* Called after the rendering of tree is complete. Here we clear the dirty flags.
*/
protected void onAfterRender()
{
super.onAfterRender();
// rendering is complete, clear all dirty flags and items
updated();
}
/**
* This method is called after creating every TreeItem. This is the place for adding components
* on item (junction links, labels, icons...)
*
* @param item
* newly created tree item. The node can be obtained as item.getModelObject()
*
* @param level
* how deep the component is in tree hierarchy (0 for root item)
*/
protected abstract void populateTreeItem(WebMarkupContainer item, int level);
/**
* Builds the children for given TreeItem. It recursively traverses children of it's TreeNode
* and creates TreeItem for every visible TreeNode.
*
* @param item
* The parent tree item
*/
private final void buildItemChildren(TreeItem item)
{
List items;
// if the node is expanded
if (isNodeExpanded((TreeNode)item.getModelObject()))
{
// build the items for children of the items' treenode.
items = buildTreeItems(nodeChildren((TreeNode)item.getModelObject()),
item.getLevel() + 1);
}
else
{
// it's not expanded, just set children to an empty list
items = Collections.EMPTY_LIST;
}
item.setChildren(items);
}
/**
* Builds (recursively) TreeItems for the given Iterator of TreeNodes.
*
* @param nodes
* The nodes to build tree items for
* @param level
* The current level
* @return List with new tree items
*/
private final List buildTreeItems(Iterator nodes, int level)
{
List result = new ArrayList();
// for each node
while (nodes.hasNext())
{
TreeNode node = (TreeNode)nodes.next();
// create tree item
TreeItem item = newTreeItem(node, level);
itemContainer.add(item);
// builds it children (recursively)
buildItemChildren(item);
// add item to result
result.add(item);
}
return result;
}
/**
* Checks whether the model has been chaned, and if so unregister and register listeners.
*/
private final void checkModel()
{
// find out whether the model object (the TreeModel) has been changed
TreeModel model = (TreeModel)getModelObject();
if (model != previousModel)
{
if (previousModel != null)
{
previousModel.removeTreeModelListener(this);
}
previousModel = model;
if (model != null)
{
model.addTreeModelListener(this);
}
// model has been changed, redraw whole tree
invalidateAll();
}
}
/**
* Removes all TreeItem components.
*/
private final void clearAllItem()
{
visitItemAndChildren(rootItem, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.remove();
}
});
rootItem = null;
}
/**
* Returns the javascript used to delete removed elements.
*
* @return The javascript
*/
private String getElementsDeleteJavascript()
{
// build the javascript call
final AppendingStringBuffer buffer = new AppendingStringBuffer(100);
buffer.append("Wicket.Tree.removeNodes(\"");
// first parameter is the markup id of tree (will be used as prefix to
// build ids of child items
buffer.append(getMarkupId() + "_\",[");
// append the ids of elements to be deleted
buffer.append(deleteIds);
// does the buffer end if ','?
if (buffer.endsWith(","))
{
// it does, trim it
buffer.setLength(buffer.length() - 1);
}
buffer.append("]);");
return buffer.toString();
}
//
// State and Model callbacks
//
/**
* returns the short version of item id (just the number part).
*
* @param item
* The tree item
* @return The id
*/
private String getShortItemId(TreeItem item)
{
// show much of component id can we skip? (to minimize the length of
// javascript being sent)
final int skip = getMarkupId().length() + 1; // the length of id of
// tree and '_'.
return item.getMarkupId().substring(skip);
}
private final static ResourceReference JAVASCRIPT = new JavascriptResourceReference(
AbstractTree.class, "res/tree.js");
/**
* Initialize the component.
*/
private final void init()
{
setVersioned(false);
// we need id when we are replacing the whole tree
setOutputMarkupId(true);
// create container for tree items
itemContainer = new TreeItemContainer("i");
add(itemContainer);
add(HeaderContributor.forJavaScript(JAVASCRIPT));
}
/**
* Invalidates single node (without children). On the next render, this node will be updated.
* Node will not be rebuilt, unless forceRebuild is true.
*
* @param node
* The node to invalidate
* @param forceRebuild
*/
private final void invalidateNode(TreeNode node, boolean forceRebuild)
{
if (dirtyAll == false)
{
// get item for this node
TreeItem item = (TreeItem)nodeToItemMap.get(node);
if (item != null)
{
boolean createDOM = false;
if (forceRebuild)
{
// recreate the item
int level = item.getLevel();
List children = item.getChildren();
String id = item.getId();
// store the parent of old item
TreeItem parent = item.getParentItem();
// if the old item has a parent, store it's index
int index = parent != null ? parent.getChildren().indexOf(item) : -1;
createDOM = dirtyItemsCreateDOM.contains(item);
dirtyItems.remove(item);
dirtyItemsCreateDOM.remove(item);
item.remove();
item = newTreeItem(node, level, id);
itemContainer.add(item);
item.setChildren(children);
// was the item an root item?
if (parent == null)
{
rootItem = item;
}
else
{
parent.getChildren().set(index, item);
}
}
dirtyItems.add(item);
if (createDOM)
{
dirtyItemsCreateDOM.add(item);
}
}
}
}
/**
* Invalidates node and it's children. On the next render, the node and children will be
* updated. Node children will be rebuilt.
*
* @param node
* The node to invalidate
*/
private final void invalidateNodeWithChildren(TreeNode node)
{
if (dirtyAll == false)
{
// get item for this node
TreeItem item = (TreeItem)nodeToItemMap.get(node);
// is the item visible?
if (item != null)
{
// go though item children and remove every one of them
visitItemChildren(item, new IItemCallback()
{
public void visitItem(TreeItem item)
{
removeItem(item);
}
});
// set children to null so that they get rebuild
item.setChildren(null);
// add item to dirty items
dirtyItems.add(item);
}
}
}
/**
* Returns whether the given node is visibled, e.g. all it's parents are expanded.
*
* @param node
* The node to inspect
* @return true if the node is visible, false otherwise
*/
private final boolean isNodeVisible(TreeNode node)
{
while (node.getParent() != null)
{
if (isNodeExpanded(node.getParent()) == false)
{
return false;
}
node = node.getParent();
}
return true;
}
/**
* Creates a tree item for given node.
*
* @param node
* The tree node
* @param level
* The level
* @return The new tree item
*/
private final TreeItem newTreeItem(TreeNode node, int level)
{
return new TreeItem("" + idCounter++, node, level);
}
/**
* Creates a tree item for given node with specified id.
*
* @param node
* The tree node
* @param level
* The level
* @param id
* the component id
* @return The new tree item
*/
private final TreeItem newTreeItem(TreeNode node, int level, String id)
{
return new TreeItem(id, node, level);
}
/**
* Return the representation of node children as Iterator interface.
*
* @param node
* The tree node
* @return iterable presentation of node children
*/
private final Iterator nodeChildren(TreeNode node)
{
return toIterator(node.children());
}
/**
* Rebuilds children of every item in dirtyItems that needs it. This method is called for
* non-partial update.
*/
private final void rebuildDirty()
{
// go through dirty items
for (Iterator i = dirtyItems.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
// item chilren need to be rebuilt
if (item.getChildren() == null)
{
buildItemChildren(item);
}
}
}
/**
* Removes the item, appends it's id to deleteIds. This is called when a items parent is being
* deleted or rebuilt.
*
* @param item
* The item to remove
*/
private void removeItem(TreeItem item)
{
// even if the item is dirty it's no longer necessary to update id
dirtyItems.remove(item);
// if the item was about to be created
if (dirtyItemsCreateDOM.contains(item))
{
// we needed to create DOM element, we no longer do
dirtyItemsCreateDOM.remove(item);
}
else
{
// add items id (it's short version) to ids of DOM elements that
// will be
// removed
deleteIds.append(getShortItemId(item));
deleteIds.append(",");
}
// remove the id
// note that this doesn't update item's parent's children list
item.remove();
}
/**
* Calls after the tree has been rendered. Clears all dirty flags.
*/
private final void updated()
{
dirtyAll = false;
dirtyItems.clear();
dirtyItemsCreateDOM.clear();
deleteIds.clear(); // FIXME: Recreate it to save some space?
}
/**
* Call the callback#visitItem method for the given item and all it's chilren.
*
* @param item
* The tree item
* @param callback
* item call back
*/
private final void visitItemAndChildren(TreeItem item, IItemCallback callback)
{
callback.visitItem(item);
visitItemChildren(item, callback);
}
/**
* Call the callback#visitItem method for every child of given item.
*
* @param item
* The tree item
* @param callback
* The callback
*/
private final void visitItemChildren(TreeItem item, IItemCallback callback)
{
if (item.getChildren() != null)
{
for (Iterator i = item.getChildren().iterator(); i.hasNext();)
{
TreeItem child = (TreeItem)i.next();
visitItemAndChildren(child, callback);
}
}
}
/**
* Returns the component associated with given node, or null, if node is not visible. This is
* useful in situations when you want to touch the node element in html.
*
* @param node
* Tree node
* @return Component associated with given node, or null if node is not visible.
*/
public Component getNodeComponent(TreeNode node)
{
return (Component)nodeToItemMap.get(node);
}
}
|
jdk-1.4/wicket/src/main/java/org/apache/wicket/markup/html/tree/AbstractTree.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.html.tree;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import org.apache.wicket.Component;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.resources.JavascriptResourceReference;
import org.apache.wicket.model.IDetachable;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.AppendingStringBuffer;
/**
* This class encapsulates the logic for displaying and (partial) updating the
* tree. Actual presentation is out of scope of this class. User should derive
* they own tree (if needed) from {@link DefaultAbstractTree} or {@link Tree}
* (recommended).
*
* @author Matej Knopp
*/
public abstract class AbstractTree extends Panel implements ITreeStateListener, TreeModelListener
{
/**
* Interface for visiting individual tree items.
*/
private static interface IItemCallback
{
/**
* Visits the tree item.
*
* @param item
* the item to visit
*/
void visitItem(TreeItem item);
}
/**
* This class represents one row in rendered tree (TreeNode). Only TreeNodes
* that are visible (all their parent are expanded) have TreeItem created
* for them.
*/
private final class TreeItem extends WebMarkupContainer
{
/**
* whether this tree item should also render it's children to response.
* this is set if we need the whole subtree rendered as one component in
* ajax response, so that we can replace it in one step (replacing
* individual rows is very slow in javascript, therefore we replace the
* whole subtree)
*/
private final static int FLAG_RENDER_CHILDREN = FLAG_RESERVED8;
private static final long serialVersionUID = 1L;
/**
* tree item children - we need this to traverse items in correct order
* when rendering
*/
private List children = null;
/** tree item level - how deep is this item in tree */
private final int level;
/**
* Construct.
*
* @param id
* The component id
* @param node
* tree node
* @param level
* current level
*/
public TreeItem(String id, final TreeNode node, int level)
{
super(id, new Model((Serializable)node));
nodeToItemMap.put(node, this);
this.level = level;
setOutputMarkupId(true);
// if this isn't a root item in rootless mode
if (level != -1)
{
populateTreeItem(this, level);
}
}
/**
* @return The children
*/
public List getChildren()
{
return children;
}
/**
* @return The current level
*/
public int getLevel()
{
return level;
}
/**
* @see org.apache.wicket.Component#getMarkupId()
*/
public String getMarkupId()
{
// this is overriden to produce id that begins with id of tree
// if the tree has set (shorter) id in markup, we can use it to
// shorten the id of individual TreeItems
return AbstractTree.this.getMarkupId() + "_" + getId();
}
/**
* @return parent item
*/
public TreeItem getParentItem()
{
return (TreeItem)nodeToItemMap.get(((TreeNode)getModelObject()).getParent());
}
/**
* Sets the children.
*
* @param children
* The children
*/
public void setChildren(List children)
{
this.children = children;
}
/**
* Whether to render children.
*
* @return whether to render children
*/
protected final boolean isRenderChildren()
{
return getFlag(FLAG_RENDER_CHILDREN);
}
/**
* @see org.apache.wicket.MarkupContainer#onRender(org.apache.wicket.markup.MarkupStream)
*/
protected void onRender(final MarkupStream markupStream)
{
// is this root and tree is in rootless mode?
if (this == rootItem && isRootLess() == true)
{
// yes, write empty div with id
// this is necesary for createElement js to work correctly
getResponse().write(
"<div style=\"display:none\" id=\"" + getMarkupId() + "\"></div>");
markupStream.skipComponent();
}
else
{
// remember current index
final int index = markupStream.getCurrentIndex();
// render the item
super.onRender(markupStream);
// should we also render children (ajax response)
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
// rewind markupStream
markupStream.setCurrentIndex(index);
// render child
item.onRender(markupStream);
}
});
//
}
}
}
public void renderHead(final HtmlHeaderContainer container)
{
super.renderHead(container);
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
// write header contributions from the children of item
item.visitChildren(new Component.IVisitor()
{
public Object component(Component component)
{
if (component.isVisible())
{
component.renderHead(container);
return CONTINUE_TRAVERSAL;
}
else
{
return CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
}
}
});
}
});
}
}
protected final void setRenderChildren(boolean value)
{
setFlag(FLAG_RENDER_CHILDREN, value);
}
protected void onAttach()
{
super.onAttach();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.attach();
}
});
}
}
protected void onDetach()
{
super.onDetach();
Object object = getModelObject();
if (object instanceof IDetachable)
{
((IDetachable)object).detach();
}
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.detach();
}
});
}
//children are rendered, clear the flag
setRenderChildren(false);
}
protected void onBeforeRender()
{
AbstractTree.this.onBeforeRenderInternal();
super.onBeforeRender();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.beforeRender();
}
});
}
}
protected void onAfterRender()
{
super.onAfterRender();
if (isRenderChildren())
{
// visit every child
visitItemChildren(this, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.afterRender();
}
});
}
}
}
/**
* Components that holds tree items. This is similiar to ListView, but it
* renders tree items in the right order.
*/
private class TreeItemContainer extends WebMarkupContainer
{
private static final long serialVersionUID = 1L;
/**
* Construct.
*
* @param id
* The component id
*/
public TreeItemContainer(String id)
{
super(id);
}
/**
* @see org.apache.wicket.MarkupContainer#remove(org.apache.wicket.Component)
*/
public void remove(Component component)
{
// when a treeItem is removed, remove reference to it from
// nodeToItemMAp
if (component instanceof TreeItem)
{
nodeToItemMap.remove(((TreeItem)component).getModelObject());
}
super.remove(component);
}
/**
* renders the tree items, making sure that items are rendered in the
* order they should be
*
* @param markupStream
*/
protected void onRender(final MarkupStream markupStream)
{
// Save position in markup stream
final int markupStart = markupStream.getCurrentIndex();
// have we rendered at least one item?
final class Rendered
{
boolean rendered = false;
}
;
final Rendered rendered = new Rendered();
// is there a root item? (non-empty tree)
if (rootItem != null)
{
IItemCallback callback = new IItemCallback()
{
public void visitItem(TreeItem item)
{
// rewind markup stream
markupStream.setCurrentIndex(markupStart);
// render component
item.render(markupStream);
rendered.rendered = true;
}
};
// visit item and it's children
visitItemAndChildren(rootItem, callback);
}
if (rendered.rendered == false)
{
// tree is empty, just move the markupStream
markupStream.skipComponent();
}
}
}
/**
* Returns an iterator that iterates trough the enumeration.
*
* @param enumeration
* The enumeration to iterate through
* @return The iterator
*/
private static final Iterator toIterator(final Enumeration enumeration)
{
return new Iterator()
{
private final Enumeration e = enumeration;
public boolean hasNext()
{
return e.hasMoreElements();
}
public Object next()
{
return e.nextElement();
}
public void remove()
{
throw new UnsupportedOperationException("Remove is not supported on enumeration.");
}
};
}
private boolean attached = false;
/** comma separated list of ids of elements to be deleted. */
private final AppendingStringBuffer deleteIds = new AppendingStringBuffer();
/**
* whether the whole tree is dirty (so the whole tree needs to be
* refreshed).
*/
private boolean dirtyAll = false;
/**
* list of dirty items. if children property of these items is null, the
* chilren will be rebuild.
*/
private final List dirtyItems = new ArrayList();
/**
* list of dirty items which need the DOM structure to be created for them
* (added items)
*/
private final List dirtyItemsCreateDOM = new ArrayList();
/** counter for generating unique ids of every tree item. */
private int idCounter = 0;
/** Component whose children are tree items. */
private TreeItemContainer itemContainer;
/**
* map that maps TreeNode to TreeItem. TreeItems only exists for TreeNodes,
* that are visibled (their parents are not collapsed).
*/
private final Map nodeToItemMap = new HashMap();
/**
* we need to track previous model. if the model changes, we unregister the
* tree from listeners of old model and register the tree as litener of new
* model.
*/
private TreeModel previousModel = null;
/** root item of the tree. */
private TreeItem rootItem = null;
/** whether the tree root is shown. */
private boolean rootLess = false;
/** stores reference to tree state. */
private ITreeState state;
/**
* Tree constructor
*
* @param id
* The component id
*/
public AbstractTree(String id)
{
super(id);
init();
}
/**
* Tree constructor
*
* @param id
* The component id
* @param model
* The tree model
*/
public AbstractTree(String id, IModel model)
{
super(id, model);
init();
}
/** called when all nodes are collapsed. */
public final void allNodesCollapsed()
{
invalidateAll();
}
/** called when all nodes are expaned. */
public final void allNodesExpanded()
{
invalidateAll();
}
/**
* Returns the TreeState of this tree.
*
* @return Tree state instance
*/
public ITreeState getTreeState()
{
if (state == null)
{
state = newTreeState();
// add this object as listener of the state
state.addTreeStateListener(this);
// FIXME: Where should we remove the listener?
}
return state;
}
/**
* This method is called before the onAttach is called. Code here gets
* executed before the items have been populated.
*/
protected void onBeforeAttach()
{
}
// This is necessary because MarkupContainer.onBeforeRender involves calling
// beforeRender on children, which results in stack overflow when called from TreeItem
private void onBeforeRenderInternal()
{
if (attached == false)
{
onBeforeAttach();
checkModel();
// Do we have to rebuld the whole tree?
if (dirtyAll && rootItem != null)
{
clearAllItem();
}
else
{
// rebuild chilren of dirty nodes that need it
rebuildDirty();
}
// is root item created? (root item is null if the items have not
// been created yet, or the whole tree was dirty and clearAllITem
// has been called
if (rootItem == null)
{
TreeNode rootNode = (TreeNode)((TreeModel)getModelObject()).getRoot();
if (rootNode != null)
{
if (isRootLess())
{
rootItem = newTreeItem(rootNode, -1);
}
else
{
rootItem = newTreeItem(rootNode, 0);
}
itemContainer.add(rootItem);
buildItemChildren(rootItem);
}
}
attached = true;
}
}
/**
* Called at the beginning of the request (not ajax request, unless we are
* rendering the entire component)
*/
public void onBeforeRender()
{
onBeforeRenderInternal();
super.onBeforeRender();
}
/**
* @see org.apache.wicket.MarkupContainer#onDetach()
*/
public void onDetach()
{
attached = false;
super.onDetach();
}
/**
* Call to refresh the whole tree. This should only be called when the
* roodNode has been replaced or the entiry tree model changed.
*/
public final void invalidateAll()
{
updated();
this.dirtyAll = true;
}
/**
* @return whether the tree root is shown
*/
public final boolean isRootLess()
{
return rootLess;
};
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeCollapsed(javax.swing.tree.TreeNode)
*/
public final void nodeCollapsed(TreeNode node)
{
if (isNodeVisible(node) == true)
{
invalidateNodeWithChildren(node);
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeExpanded(javax.swing.tree.TreeNode)
*/
public final void nodeExpanded(TreeNode node)
{
if (isNodeVisible(node) == true)
{
invalidateNodeWithChildren(node);
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeSelected(javax.swing.tree.TreeNode)
*/
public final void nodeSelected(TreeNode node)
{
if (isNodeVisible(node))
{
invalidateNode(node, isForceRebuildOnSelectionChange());
}
}
/**
* @see org.apache.wicket.markup.html.tree.ITreeStateListener#nodeUnselected(javax.swing.tree.TreeNode)
*/
public final void nodeUnselected(TreeNode node)
{
if (isNodeVisible(node))
{
invalidateNode(node, isForceRebuildOnSelectionChange());
}
}
/**
* Determines whether the TreeNode needs to be rebuilt if it is selected
* or deselected
* @return true if the node should be rebuilt after (de)selection, false otherwise
*/
protected boolean isForceRebuildOnSelectionChange()
{
return true;
}
/**
* Sets whether the root of the tree should be visible.
*
* @param rootLess
* whether the root should be visible
*/
public void setRootLess(boolean rootLess)
{
if (this.rootLess != rootLess)
{
this.rootLess = rootLess;
invalidateAll();
// if the tree is in rootless mode, make sure the root node is
// expanded
if (rootLess == true && getModelObject() != null)
{
getTreeState().expandNode((TreeNode)((TreeModel)getModelObject()).getRoot());
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesChanged(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesChanged(TreeModelEvent e)
{
// has root node changed?
if (e.getChildren() == null)
{
if (rootItem != null)
{
invalidateNode((TreeNode)rootItem.getModelObject(), true);
}
}
else
{
// go through all changed nodes
Object[] children = e.getChildren();
if (children != null)
{
for (int i = 0; i < children.length; i++)
{
TreeNode node = (TreeNode)children[i];
if (isNodeVisible(node))
{
// if the nodes is visible invalidate it
invalidateNode(node, true);
}
}
}
}
};
/**
* Marks the last but one visible child node of the given item as dirty, if
* give child is the last item of parent.
*
* We need this to refresh the previous visible item in case the inserted /
* deleteditem was last. The reason is that the line shape of previous item
* chages from L to |- .
*
* @param parent
* @param child
*/
private void markTheLastButOneChildDirty(TreeItem parent, TreeItem child)
{
if (parent.getChildren().indexOf(child) == parent.getChildren().size() - 1)
{
// go through the childrend backwards, start at the last but one
// item
for (int i = parent.getChildren().size() - 2; i >= 0; --i)
{
TreeItem item = (TreeItem)parent.getChildren().get(i);
// invalidate the node and it's children, so that they are
// redrawn
invalidateNodeWithChildren((TreeNode)item.getModelObject());
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesInserted(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesInserted(TreeModelEvent e)
{
// get the parent node of inserted nodes
TreeNode parent = (TreeNode)e.getTreePath().getLastPathComponent();
if (isNodeVisible(parent) && isNodeExpanded(parent))
{
TreeItem parentItem = (TreeItem)nodeToItemMap.get(parent);
for (int i = 0; i < e.getChildren().length; ++i)
{
TreeNode node = (TreeNode)e.getChildren()[i];
int index = e.getChildIndices()[i];
TreeItem item = newTreeItem(node, parentItem.getLevel() + 1);
itemContainer.add(item);
parentItem.getChildren().add(index, item);
markTheLastButOneChildDirty(parentItem, item);
dirtyItems.add(item);
dirtyItemsCreateDOM.add(item);
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeNodesRemoved(javax.swing.event.TreeModelEvent)
*/
public final void treeNodesRemoved(TreeModelEvent e)
{
// get the parent node of inserted nodes
TreeNode parent = (TreeNode)e.getTreePath().getLastPathComponent();
TreeItem parentItem = (TreeItem)nodeToItemMap.get(parent);
if (isNodeVisible(parent) && isNodeExpanded(parent))
{
for (int i = 0; i < e.getChildren().length; ++i)
{
TreeNode node = (TreeNode)e.getChildren()[i];
TreeItem item = (TreeItem)nodeToItemMap.get(node);
if (item != null)
{
markTheLastButOneChildDirty(parentItem, item);
parentItem.getChildren().remove(item);
// go though item children and remove every one of them
visitItemChildren(item, new IItemCallback()
{
public void visitItem(TreeItem item)
{
removeItem(item);
// unselect the node
getTreeState().selectNode((TreeNode)item.getModelObject(), false);
}
});
removeItem(item);
}
}
}
}
/**
* @see javax.swing.event.TreeModelListener#treeStructureChanged(javax.swing.event.TreeModelEvent)
*/
public final void treeStructureChanged(TreeModelEvent e)
{
// get the parent node of changed nodes
TreeNode node = (TreeNode)e.getTreePath().getLastPathComponent();
// has the tree root changed?
if (e.getTreePath().getPathCount() == 1 && node.equals(rootItem.getModelObject()))
{
invalidateAll();
}
else
{
invalidateNodeWithChildren(node);
}
}
/**
* Updates the changed portions of the tree using given AjaxRequestTarget.
* Call this method if you modified the tree model during an ajax request
* target and you want to partially update the component on page. Make sure
* that the tree model has fired the proper listener functions.
* <p>
* <b>You can only call this method once in a request.</b>
*
* @param target
* Ajax request target used to send the update to the page
*/
public final void updateTree(final AjaxRequestTarget target)
{
if (target == null)
{
return;
}
// check whether the model hasn't changed
checkModel();
// is the whole tree dirty
if (dirtyAll)
{
// render entire tree component
target.addComponent(this);
}
else
{
// remove DOM elements that need to be removed
if (deleteIds.length() != 0)
{
String js = getElementsDeleteJavascript();
// add the javascript to target
target.prependJavascript(js);
}
// We have to repeat this as long as there are any dirty items to be
// created.
// The reason why we can't do this in one pass is that some of the
// items
// may need to be inserted after items that has not been inserted
// yet, so we have
// to detect those and wait until the items they depend on are
// inserted.
while (dirtyItemsCreateDOM.isEmpty() == false)
{
for (Iterator i = dirtyItemsCreateDOM.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
TreeItem parent = item.getParentItem();
int index = parent.getChildren().indexOf(item);
TreeItem previous;
// we need item before this (in dom structure)
if (index == 0)
{
previous = parent;
}
else
{
previous = (TreeItem)parent.getChildren().get(index - 1);
// get the last item of previous item subtree
while (previous.getChildren() != null && previous.getChildren().size() > 0)
{
previous = (TreeItem)previous.getChildren().get(
previous.getChildren().size() - 1);
}
}
// check if the previous item isn't waiting to be inserted
if (dirtyItemsCreateDOM.contains(previous) == false)
{
// it's already in dom, so we can use it as point of
// insertion
target.prependJavascript("Wicket.Tree.createElement(\""
+ item.getMarkupId() + "\"," + "\"" + previous.getMarkupId()
+ "\")");
// remove the item so we don't process it again
i.remove();
}
else
{
// we don't do anything here, inserting this item will
// have to wait
// until the previous item gets inserted
}
}
}
// iterate through dirty items
for (Iterator i = dirtyItems.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
// does the item need to rebuild children?
if (item.getChildren() == null)
{
// rebuld the children
buildItemChildren(item);
// set flag on item so that it renders itself together with
// it's children
item.setRenderChildren(true);
}
// add the component to target
target.addComponent(item);
}
// clear dirty flags
updated();
}
}
/**
* Returns whether the given node is expanded.
*
* @param node
* The node to inspect
* @return true if the node is expanded, false otherwise
*/
protected final boolean isNodeExpanded(TreeNode node)
{
// In root less mode the root node is always expanded
if (isRootLess() && rootItem != null && rootItem.getModelObject().equals(node))
{
return true;
}
return getTreeState().isNodeExpanded(node);
}
/**
* Creates the TreeState, which is an object where the current state of tree
* (which nodes are expanded / collapsed, selected, ...) is stored.
*
* @return Tree state instance
*/
protected ITreeState newTreeState()
{
return new DefaultTreeState();
}
/**
* Called after the rendering of tree is complete. Here we clear the dirty
* flags.
*/
protected void onAfterRender()
{
super.onAfterRender();
// rendering is complete, clear all dirty flags and items
updated();
}
/**
* This method is called after creating every TreeItem. This is the place
* for adding components on item (junction links, labels, icons...)
*
* @param item
* newly created tree item. The node can be obtained as
* item.getModelObject()
*
* @param level
* how deep the component is in tree hierarchy (0 for root item)
*/
protected abstract void populateTreeItem(WebMarkupContainer item, int level);
/**
* Builds the children for given TreeItem. It recursively traverses children
* of it's TreeNode and creates TreeItem for every visible TreeNode.
*
* @param item
* The parent tree item
*/
private final void buildItemChildren(TreeItem item)
{
List items;
// if the node is expanded
if (isNodeExpanded((TreeNode)item.getModelObject()))
{
// build the items for children of the items' treenode.
items = buildTreeItems(nodeChildren((TreeNode)item.getModelObject()),
item.getLevel() + 1);
}
else
{
// it's not expanded, just set children to an empty list
items = Collections.EMPTY_LIST;
}
item.setChildren(items);
}
/**
* Builds (recursively) TreeItems for the given Iterator of TreeNodes.
*
* @param nodes
* The nodes to build tree items for
* @param level
* The current level
* @return List with new tree items
*/
private final List buildTreeItems(Iterator nodes, int level)
{
List result = new ArrayList();
// for each node
while (nodes.hasNext())
{
TreeNode node = (TreeNode)nodes.next();
// create tree item
TreeItem item = newTreeItem(node, level);
itemContainer.add(item);
// builds it children (recursively)
buildItemChildren(item);
// add item to result
result.add(item);
}
return result;
}
/**
* Checks whether the model has been chaned, and if so unregister and
* register listeners.
*/
private final void checkModel()
{
// find out whether the model object (the TreeModel) has been changed
TreeModel model = (TreeModel)getModelObject();
if (model != previousModel)
{
if (previousModel != null)
{
previousModel.removeTreeModelListener(this);
}
previousModel = model;
if (model != null)
{
model.addTreeModelListener(this);
}
// model has been changed, redraw whole tree
invalidateAll();
}
}
/**
* Removes all TreeItem components.
*/
private final void clearAllItem()
{
visitItemAndChildren(rootItem, new IItemCallback()
{
public void visitItem(TreeItem item)
{
item.remove();
}
});
rootItem = null;
}
/**
* Returns the javascript used to delete removed elements.
*
* @return The javascript
*/
private String getElementsDeleteJavascript()
{
// build the javascript call
final AppendingStringBuffer buffer = new AppendingStringBuffer(100);
buffer.append("Wicket.Tree.removeNodes(\"");
// first parameter is the markup id of tree (will be used as prefix to
// build ids of child items
buffer.append(getMarkupId() + "_\",[");
// append the ids of elements to be deleted
buffer.append(deleteIds);
// does the buffer end if ','?
if (buffer.endsWith(","))
{
// it does, trim it
buffer.setLength(buffer.length() - 1);
}
buffer.append("]);");
return buffer.toString();
}
//
// State and Model callbacks
//
/**
* returns the short version of item id (just the number part).
*
* @param item
* The tree item
* @return The id
*/
private String getShortItemId(TreeItem item)
{
// show much of component id can we skip? (to minimize the length of
// javascript being sent)
final int skip = getMarkupId().length() + 1; // the length of id of
// tree and '_'.
return item.getMarkupId().substring(skip);
}
private final static ResourceReference JAVASCRIPT = new JavascriptResourceReference(
AbstractTree.class, "res/tree.js");
/**
* Initialize the component.
*/
private final void init()
{
setVersioned(false);
// we need id when we are replacing the whole tree
setOutputMarkupId(true);
// create container for tree items
itemContainer = new TreeItemContainer("i");
add(itemContainer);
add(HeaderContributor.forJavaScript(JAVASCRIPT));
}
/**
* Invalidates single node (without children). On the next render, this node
* will be updated. Node will not be rebuilt, unless forceRebuild is true.
*
* @param node
* The node to invalidate
* @param forceRebuild
*/
private final void invalidateNode(TreeNode node, boolean forceRebuild)
{
if (dirtyAll == false)
{
// get item for this node
TreeItem item = (TreeItem)nodeToItemMap.get(node);
if (item != null)
{
boolean createDOM = false;
if (forceRebuild)
{
// recreate the item
int level = item.getLevel();
List children = item.getChildren();
String id = item.getId();
// store the parent of old item
TreeItem parent = item.getParentItem();
// if the old item has a parent, store it's index
int index = parent != null ? parent.getChildren().indexOf(item) : -1;
createDOM = dirtyItemsCreateDOM.contains(item);
dirtyItems.remove(item);
dirtyItemsCreateDOM.remove(item);
item.remove();
item = newTreeItem(node, level, id);
itemContainer.add(item);
item.setChildren(children);
// was the item an root item?
if (parent == null)
{
rootItem = item;
}
else
{
parent.getChildren().set(index, item);
}
}
dirtyItems.add(item);
if (createDOM)
{
dirtyItemsCreateDOM.add(item);
}
}
}
}
/**
* Invalidates node and it's children. On the next render, the node and
* children will be updated. Node children will be rebuilt.
*
* @param node
* The node to invalidate
*/
private final void invalidateNodeWithChildren(TreeNode node)
{
if (dirtyAll == false)
{
// get item for this node
TreeItem item = (TreeItem)nodeToItemMap.get(node);
// is the item visible?
if (item != null)
{
// go though item children and remove every one of them
visitItemChildren(item, new IItemCallback()
{
public void visitItem(TreeItem item)
{
removeItem(item);
}
});
// set children to null so that they get rebuild
item.setChildren(null);
// add item to dirty items
dirtyItems.add(item);
}
}
}
/**
* Returns whether the given node is visibled, e.g. all it's parents are
* expanded.
*
* @param node
* The node to inspect
* @return true if the node is visible, false otherwise
*/
private final boolean isNodeVisible(TreeNode node)
{
while (node.getParent() != null)
{
if (isNodeExpanded(node.getParent()) == false)
{
return false;
}
node = node.getParent();
}
return true;
}
/**
* Creates a tree item for given node.
*
* @param node
* The tree node
* @param level
* The level
* @return The new tree item
*/
private final TreeItem newTreeItem(TreeNode node, int level)
{
return new TreeItem("" + idCounter++, node, level);
}
/**
* Creates a tree item for given node with specified id.
*
* @param node
* The tree node
* @param level
* The level
* @param id
* the component id
* @return The new tree item
*/
private final TreeItem newTreeItem(TreeNode node, int level, String id)
{
return new TreeItem(id, node, level);
}
/**
* Return the representation of node children as Iterator interface.
*
* @param node
* The tree node
* @return iterable presentation of node children
*/
private final Iterator nodeChildren(TreeNode node)
{
return toIterator(node.children());
}
/**
* Rebuilds children of every item in dirtyItems that needs it. This method
* is called for non-partial update.
*/
private final void rebuildDirty()
{
// go through dirty items
for (Iterator i = dirtyItems.iterator(); i.hasNext();)
{
TreeItem item = (TreeItem)i.next();
// item chilren need to be rebuilt
if (item.getChildren() == null)
{
buildItemChildren(item);
}
}
}
/**
* Removes the item, appends it's id to deleteIds. This is called when a
* items parent is being deleted or rebuilt.
*
* @param item
* The item to remove
*/
private void removeItem(TreeItem item)
{
// even if the item is dirty it's no longer necessary to update id
dirtyItems.remove(item);
// if the item was about to be created
if (dirtyItemsCreateDOM.contains(item))
{
// we needed to create DOM element, we no longer do
dirtyItemsCreateDOM.remove(item);
}
else
{
// add items id (it's short version) to ids of DOM elements that
// will be
// removed
deleteIds.append(getShortItemId(item));
deleteIds.append(",");
}
// remove the id
// note that this doesn't update item's parent's children list
item.remove();
}
/**
* Calls after the tree has been rendered. Clears all dirty flags.
*/
private final void updated()
{
this.dirtyAll = false;
this.dirtyItems.clear();
this.dirtyItemsCreateDOM.clear();
deleteIds.clear(); // FIXME: Recreate it to save some space?
}
/**
* Call the callback#visitItem method for the given item and all it's
* chilren.
*
* @param item
* The tree item
* @param callback
* item call back
*/
private final void visitItemAndChildren(TreeItem item, IItemCallback callback)
{
callback.visitItem(item);
visitItemChildren(item, callback);
}
/**
* Call the callback#visitItem method for every child of given item.
*
* @param item
* The tree item
* @param callback
* The callback
*/
private final void visitItemChildren(TreeItem item, IItemCallback callback)
{
if (item.getChildren() != null)
{
for (Iterator i = item.getChildren().iterator(); i.hasNext();)
{
TreeItem child = (TreeItem)i.next();
visitItemAndChildren(child, callback);
}
}
}
/**
* Returns the component associated with given node, or null, if node is not
* visible. This is useful in situations when you want to touch the node
* element in html.
*
* @param node
* Tree node
* @return Component associated with given node, or null if node is not
* visible.
*/
public Component getNodeComponent(TreeNode node)
{
return (Component)nodeToItemMap.get(node);
}
}
|
WICKET-878
git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@570086 13f79535-47bb-0310-9956-ffa450edef68
|
jdk-1.4/wicket/src/main/java/org/apache/wicket/markup/html/tree/AbstractTree.java
|
WICKET-878
|
|
Java
|
apache-2.0
|
63ca256f41cf09d3e79adce50d268eb9e1667cdb
| 0
|
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
|
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.ruby;
import java.util.*;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import ed.js.engine.Scope;
/**
* Scopes need to be wrapped differently because we want their key sets
* to include the keys of all parent scopes.
*/
public class RubyScopeWrapper extends RubyJSObjectWrapper {
RubyScopeWrapper(Scope s, Ruby runtime, Scope obj) {
super(s, runtime, obj);
}
RubyScopeWrapper(Scope s, Ruby runtime, Scope obj, RubyClass klass) {
super(s, runtime, obj, klass);
}
protected Collection<? extends Object> jsKeySet() {
Set<String> keys = new HashSet<String>();
Scope s = (Scope)_jsobj;
while (s != null) {
keys.addAll(s.keySet());
s = s.getParent();
}
return keys;
}
}
|
src/main/ed/lang/ruby/RubyScopeWrapper.java
|
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.ruby;
import java.util.*;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import ed.js.engine.Scope;
/**
* Scopes need to be wrapped differently because their key sets are a set
* consiting of of the key set of itself and all its parent scopes.
*/
public class RubyScopeWrapper extends RubyJSObjectWrapper {
RubyScopeWrapper(Scope s, Ruby runtime, Scope obj) {
super(s, runtime, obj);
}
RubyScopeWrapper(Scope s, Ruby runtime, Scope obj, RubyClass klass) {
super(s, runtime, obj, klass);
}
protected Collection<? extends Object> jsKeySet() {
Set<String> keys = new HashSet<String>();
Scope s = (Scope)_jsobj;
while (s != null) {
keys.addAll(s.keySet());
s = s.getParent();
}
return keys;
}
}
|
comment fix
|
src/main/ed/lang/ruby/RubyScopeWrapper.java
|
comment fix
|
|
Java
|
apache-2.0
|
686ba0974caeba333003964aa4e2b72f8a364257
| 0
|
Bedework/bw-util,nblair/bw-util
|
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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 edu.rpi.cmt.jmx;
import edu.rpi.cmt.config.ConfigBase;
import edu.rpi.cmt.config.ConfigException;
import edu.rpi.cmt.config.ConfigurationFileStore;
import edu.rpi.cmt.config.ConfigurationStore;
import org.apache.log4j.Logger;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/** A configuration has a name and a location. The location can be specified in
* a number of ways: <ul>
* <li>An absolute path to the directory containing the config</li>
* <li>An http url(soon)</li>
* <li>A system property name</li>
* </ul>
*
* <p>Each may be augmented by providing a path suffix - used to add additional
* path elements to the base path.
*
* @author douglm
* @param <T>
*
*/
public abstract class ConfBase<T extends ConfigBase> implements ConfBaseMBean {
private transient Logger log;
protected boolean debug;
protected T cfg;
private String configName;
private String configuri;
private String configPname;
private String pathSuffix;
private static Set<ObjectName> registeredMBeans = new CopyOnWriteArraySet<ObjectName>();
private static ManagementContext managementContext;
private String serviceName;
private ConfigurationStore store;
/** At least setServiceName MUST be called
*
*/
protected ConfBase() {
debug = getLogger().isDebugEnabled();
}
protected ConfBase(final String serviceName) {
this.serviceName = serviceName;
debug = getLogger().isDebugEnabled();
}
/**
* @param val IDENTICAL to that defined for service.
*/
public void setServiceName(final String val) {
serviceName = val;
}
/**
* @return name IDENTICAL to that defined for service.
*/
public String getServiceName() {
return serviceName;
}
/** Specify the absolute path to the configuration directory.
*
* @param val
*/
public void setConfigUri(final String val) {
configuri = val;
store = null;
}
/**
* @return String path to configs
*/
public String getConfigUri() {
return configuri;
}
/** Specify a system property giving the absolute path to the configuration directory.
*
* @param val
*/
public void setConfigPname(final String val) {
configPname = val;
store = null;
}
/**
* @return String name of system property
*/
public String getConfigPname() {
return configPname;
}
/** Specify a suffix to the path to the configuration directory.
*
* @param val
*/
public void setPathSuffix(final String val) {
pathSuffix = val;
store = null;
}
/**
* @return String path suffix to configs
*/
public String getPathSuffix() {
return pathSuffix;
}
/** Set a ConfigurationStore
*
* @param val
*/
public void setStore(final ConfigurationStore val) {
store = val;
}
/** Get a ConfigurationStore based on the uri or property value.
*
* @return store
* @throws ConfigException
*/
public ConfigurationStore getStore() throws ConfigException {
if (store != null) {
return store;
}
String uriStr = getConfigUri();
if (uriStr == null) {
if (getConfigPname() == null) {
throw new ConfigException("Either a uri or property name must be specified");
}
uriStr = System.getProperty(getConfigPname());
if (uriStr == null) {
throw new ConfigException("No property with name \"" + getConfigPname() + "\"");
}
}
URI uri;
try {
uri = new URI(uriStr);
} catch (URISyntaxException use) {
throw new ConfigException(use);
}
String scheme = uri.getScheme();
if ((scheme == null) || (scheme.equals("file"))) {
String path = uri.getPath();
if (getPathSuffix() != null) {
if (!path.endsWith(File.separator)) {
path += File.separator;
}
path += getPathSuffix() + File.separator;
}
store = new ConfigurationFileStore(path);
return store;
}
throw new ConfigException("Unsupported ConfigurationStore: " + uri);
}
/**
* @return the object we are managing
*/
public T getConfig() {
return cfg;
}
protected Set<ObjectName> getRegisteredMBeans() {
return registeredMBeans;
}
/* ========================================================================
* Attributes
* ======================================================================== */
@Override
public void setConfigName(final String val) {
configName = val;
}
@Override
public String getConfigName() {
return configName;
}
/* ========================================================================
* Operations
* ======================================================================== */
@Override
public String saveConfig() {
try {
T config = getConfig();
if (config == null) {
return "No configuration to save";
}
ConfigurationStore cs = getStore();
config.setName(configName);
cs.saveConfiguration(config);
return "saved";
} catch (Throwable t) {
error(t);
return t.getLocalizedMessage();
}
}
/* ====================================================================
* Private methods
* ==================================================================== */
/* ====================================================================
* JMX methods
* ==================================================================== */
/* */
private ObjectName serviceObjectName;
protected void register(final String serviceType,
final String name,
final Object view) {
try {
ObjectName objectName = createObjectName(serviceType, name);
register(objectName, view);
} catch (Throwable t) {
error("Failed to register " + serviceType + ":" + name);
error(t);
}
}
protected void unregister(final String serviceType,
final String name) {
try {
ObjectName objectName = createObjectName(serviceType, name);
unregister(objectName);
} catch (Throwable t) {
error("Failed to unregister " + serviceType + ":" + name);
error(t);
}
}
protected ObjectName getServiceObjectName() throws MalformedObjectNameException {
if (serviceObjectName == null) {
serviceObjectName = new ObjectName(getServiceName());
}
return serviceObjectName;
}
protected ObjectName createObjectName(final String serviceType,
final String name) throws MalformedObjectNameException {
// Build the object name for the bean
Map props = getServiceObjectName().getKeyPropertyList();
ObjectName objectName = new ObjectName(getServiceObjectName().getDomain() + ":" +
"service=" + props.get("service") + "," +
"Type=" + ManagementContext.encodeObjectNamePart(serviceType) + "," +
"Name=" + ManagementContext.encodeObjectNamePart(name));
return objectName;
}
/* ====================================================================
* Protected methods
* ==================================================================== */
/**
* @return config identified by current config name
*/
protected T getConfigInfo(final Class<T> cl)throws ConfigException {
return getConfigInfo(getStore(), getConfigName(), cl);
}
/**
* @return current state of config
*/
protected T getConfigInfo(final String configName,
final Class<T> cl)throws ConfigException {
return getConfigInfo(getStore(), configName, cl);
}
@SuppressWarnings("unchecked")
protected T getConfigInfo(final ConfigurationStore cfs,
final String configName,
final Class<T> cl) throws ConfigException {
try {
/* Try to load it */
return (T)getStore().getConfig(configName, cl);
} catch (ConfigException cfe) {
throw cfe;
} catch (Throwable t) {
throw new ConfigException(t);
}
}
/**
* @param cl
* @return config identified by current config name
*/
protected String loadConfig(final Class<T> cl) {
try {
/* Load up the config */
cfg = getConfigInfo(cl);
if (cfg == null) {
return "Unable to read configuration";
}
saveConfig(); // Just to ensure we have it for next time
return "OK";
} catch (Throwable t) {
error("Failed to load configuration: " + t.getLocalizedMessage());
error(t);
return "failed";
}
}
/** Load the configuration if we only expect one and we don't care or know
* what it's called.
*
* @param cl
* @return null for success or an error message (logged already)
*/
protected String loadOnlyConfig(final Class<T> cl) {
try {
/* Load up the config */
ConfigurationStore cs = getStore();
List<String> configNames = cs.getConfigs();
if (configNames.isEmpty()) {
error("No configuration on path " + cs.getLocation());
return "No configuration on path " + cs.getLocation();
}
if (configNames.size() != 1) {
error("1 and only 1 configuration allowed");
return "1 and only 1 configuration allowed";
}
String configName = configNames.iterator().next();
cfg = getConfigInfo(cs, configName, cl);
if (cfg == null) {
error("Unable to read configuration");
return "Unable to read configuration";
}
setConfigName(configName);
saveConfig(); // Just to ensure we have it for next time
return null;
} catch (Throwable t) {
error("Failed to load configuration: " + t.getLocalizedMessage());
error(t);
return "failed";
}
}
/**
* @param key
* @param bean
* @throws Exception
*/
protected void register(final ObjectName key,
final Object bean) throws Exception {
try {
AnnotatedMBean.registerMBean(getManagementContext(), bean, key);
getRegisteredMBeans().add(key);
} catch (Throwable e) {
warn("Failed to register MBean: " + key + ": " + e.getLocalizedMessage());
if (getLogger().isDebugEnabled()) {
error(e);
}
}
}
/**
* @param key
* @throws Exception
*/
protected void unregister(final ObjectName key) throws Exception {
if (getRegisteredMBeans().remove(key)) {
try {
getManagementContext().unregisterMBean(key);
} catch (Throwable e) {
warn("Failed to unregister MBean: " + key);
if (getLogger().isDebugEnabled()) {
error(e);
}
}
}
}
/**
* @return the management context.
*/
public static ManagementContext getManagementContext() {
if (managementContext == null) {
/* Try to find the jboss mbean server * /
MBeanServer mbsvr = null;
for (MBeanServer svr: MBeanServerFactory.findMBeanServer(null)) {
if (svr.getDefaultDomain().equals("jboss")) {
mbsvr = svr;
break;
}
}
if (mbsvr == null) {
Logger.getLogger(ConfBase.class).warn("Unable to locate jboss mbean server");
}
managementContext = new ManagementContext(mbsvr);
*/
managementContext = new ManagementContext(ManagementContext.DEFAULT_DOMAIN);
}
return managementContext;
}
protected static Object makeObject(final String className) {
try {
Object o = Class.forName(className).newInstance();
if (o == null) {
Logger.getLogger(ConfBase.class).error("Class " + className + " not found");
return null;
}
return o;
} catch (Throwable t) {
Logger.getLogger(ConfBase.class).error("Unable to make object ", t);
return null;
}
}
protected void info(final String msg) {
getLogger().info(msg);
}
protected void warn(final String msg) {
getLogger().warn(msg);
}
protected void debug(final String msg) {
getLogger().debug(msg);
}
protected void error(final Throwable t) {
getLogger().error(this, t);
}
protected void error(final String msg) {
getLogger().error(msg);
}
/* Get a logger for messages
*/
protected Logger getLogger() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
}
|
src/main/java/edu/rpi/cmt/jmx/ConfBase.java
|
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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 edu.rpi.cmt.jmx;
import edu.rpi.cmt.config.ConfigBase;
import edu.rpi.cmt.config.ConfigException;
import edu.rpi.cmt.config.ConfigurationFileStore;
import edu.rpi.cmt.config.ConfigurationStore;
import org.apache.log4j.Logger;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/** A configuration has a name and a location. The location can be specified in
* a number of ways: <ul>
* <li>An absolute path to the directory containing the config</li>
* <li>An http url(soon)</li>
* <li>A system property name</li>
* </ul>
*
* <p>Each may be augmented by providing a path suffix - used to add additional
* path elements to the base path.
*
* @author douglm
* @param <T>
*
*/
public abstract class ConfBase<T extends ConfigBase> implements ConfBaseMBean {
private transient Logger log;
protected boolean debug;
protected T cfg;
private String configName;
private String configuri;
private String configPname;
private String pathSuffix;
private static Set<ObjectName> registeredMBeans = new CopyOnWriteArraySet<ObjectName>();
private static ManagementContext managementContext;
private String serviceName;
private ConfigurationStore store;
/** At least setServiceName MUST be called
*
*/
protected ConfBase() {
debug = getLogger().isDebugEnabled();
}
protected ConfBase(final String serviceName) {
this.serviceName = serviceName;
debug = getLogger().isDebugEnabled();
}
/**
* @param val IDENTICAL to that defined for service.
*/
public void setServiceName(final String val) {
serviceName = val;
}
/**
* @return name IDENTICAL to that defined for service.
*/
public String getServiceName() {
return serviceName;
}
/** Specify the absolute path to the configuration directory.
*
* @param val
*/
public void setConfigUri(final String val) {
configuri = val;
store = null;
}
/**
* @return String path to configs
*/
public String getConfigUri() {
return configuri;
}
/** Specify a system property giving the absolute path to the configuration directory.
*
* @param val
*/
public void setConfigPname(final String val) {
configPname = val;
store = null;
}
/**
* @return String name of system property
*/
public String getConfigPname() {
return configPname;
}
/** Specify a suffix to the path to the configuration directory.
*
* @param val
*/
public void setPathSuffix(final String val) {
pathSuffix = val;
store = null;
}
/**
* @return String path suffix to configs
*/
public String getPathSuffix() {
return pathSuffix;
}
/** Set a ConfigurationStore
*
* @param val
*/
public void setStore(final ConfigurationStore val) {
store = val;
}
/** Get a ConfigurationStore based on the uri or property value.
*
* @return store
* @throws ConfigException
*/
public ConfigurationStore getStore() throws ConfigException {
if (store != null) {
return store;
}
String uriStr = getConfigUri();
if (uriStr == null) {
if (getConfigPname() == null) {
throw new ConfigException("Either a uri or property name must be specified");
}
uriStr = System.getProperty(getConfigPname());
if (uriStr == null) {
throw new ConfigException("No property with name \"" + getConfigPname() + "\"");
}
}
URI uri;
try {
uri = new URI(uriStr);
} catch (URISyntaxException use) {
throw new ConfigException(use);
}
String scheme = uri.getScheme();
if ((scheme == null) || (scheme.equals("file"))) {
String path = uri.getPath();
if (getPathSuffix() != null) {
if (!path.endsWith(File.separator)) {
path += File.separator;
}
path += getPathSuffix() + File.separator;
}
store = new ConfigurationFileStore(path);
return store;
}
throw new ConfigException("Unsupported ConfigurationStore: " + uri);
}
/**
* @return the object we are managing
*/
public T getConfig() {
return cfg;
}
protected Set<ObjectName> getRegisteredMBeans() {
return registeredMBeans;
}
/* ========================================================================
* Attributes
* ======================================================================== */
@Override
public void setConfigName(final String val) {
configName = val;
}
@Override
public String getConfigName() {
return configName;
}
/* ========================================================================
* Operations
* ======================================================================== */
@Override
public String saveConfig() {
try {
T config = getConfig();
if (config == null) {
return "No configuration to save";
}
ConfigurationStore cs = getStore();
config.setName(configName);
cs.saveConfiguration(config);
return "saved";
} catch (Throwable t) {
error(t);
return t.getLocalizedMessage();
}
}
/* ====================================================================
* Private methods
* ==================================================================== */
/* ====================================================================
* JMX methods
* ==================================================================== */
/* */
private ObjectName serviceObjectName;
protected void register(final String serviceType,
final String name,
final Object view) {
try {
ObjectName objectName = createObjectName(serviceType, name);
register(objectName, view);
} catch (Throwable t) {
error("Failed to register " + serviceType + ":" + name);
error(t);
}
}
protected void unregister(final String serviceType,
final String name) {
try {
ObjectName objectName = createObjectName(serviceType, name);
unregister(objectName);
} catch (Throwable t) {
error("Failed to unregister " + serviceType + ":" + name);
error(t);
}
}
protected ObjectName getServiceObjectName() throws MalformedObjectNameException {
if (serviceObjectName == null) {
serviceObjectName = new ObjectName(getServiceName());
}
return serviceObjectName;
}
protected ObjectName createObjectName(final String serviceType,
final String name) throws MalformedObjectNameException {
// Build the object name for the bean
Map props = getServiceObjectName().getKeyPropertyList();
ObjectName objectName = new ObjectName(getServiceObjectName().getDomain() + ":" +
"service=" + props.get("service") + "," +
"Type=" + ManagementContext.encodeObjectNamePart(serviceType) + "," +
"Name=" + ManagementContext.encodeObjectNamePart(name));
return objectName;
}
/* ====================================================================
* Protected methods
* ==================================================================== */
/**
* @return config identified by current config name
*/
protected T getConfigInfo(final Class<T> cl)throws ConfigException {
return getConfigInfo(getStore(), getConfigName(), cl);
}
/**
* @return current state of config
*/
protected T getConfigInfo(final String configName,
final Class<T> cl)throws ConfigException {
return getConfigInfo(getStore(), configName, cl);
}
@SuppressWarnings("unchecked")
protected T getConfigInfo(final ConfigurationStore cfs,
final String configName,
final Class<T> cl) throws ConfigException {
try {
/* Try to load it */
return (T)getStore().getConfig(configName, cl);
} catch (ConfigException cfe) {
throw cfe;
} catch (Throwable t) {
throw new ConfigException(t);
}
}
/**
* @param cl
* @return config identified by current config name
*/
protected String loadConfig(final Class<T> cl) {
try {
/* Load up the config */
cfg = getConfigInfo(cl);
if (cfg == null) {
return "Unable to read configuration";
}
saveConfig(); // Just to ensure we have it for next time
return "OK";
} catch (Throwable t) {
error("Failed to start management context");
error(t);
return "failed";
}
}
/** Load the configuration if we only expect one and we don't care or know
* what it's called.
*
* @param cl
* @return null for success or an error message (logged already)
*/
protected String loadOnlyConfig(final Class<T> cl) {
try {
/* Load up the config */
ConfigurationStore cs = getStore();
List<String> configNames = cs.getConfigs();
if (configNames.isEmpty()) {
error("No configuration on path " + cs.getLocation());
return "No configuration on path " + cs.getLocation();
}
if (configNames.size() != 1) {
error("1 and only 1 configuration allowed");
return "1 and only 1 configuration allowed";
}
String configName = configNames.iterator().next();
cfg = getConfigInfo(cs, configName, cl);
if (cfg == null) {
error("Unable to read configuration");
return "Unable to read configuration";
}
setConfigName(configName);
saveConfig(); // Just to ensure we have it for next time
return null;
} catch (Throwable t) {
error("Failed to start management context: " + t.getLocalizedMessage());
error(t);
return "failed";
}
}
/**
* @param key
* @param bean
* @throws Exception
*/
protected void register(final ObjectName key,
final Object bean) throws Exception {
try {
AnnotatedMBean.registerMBean(getManagementContext(), bean, key);
getRegisteredMBeans().add(key);
} catch (Throwable e) {
warn("Failed to register MBean: " + key + ": " + e.getLocalizedMessage());
if (getLogger().isDebugEnabled()) {
error(e);
}
}
}
/**
* @param key
* @throws Exception
*/
protected void unregister(final ObjectName key) throws Exception {
if (getRegisteredMBeans().remove(key)) {
try {
getManagementContext().unregisterMBean(key);
} catch (Throwable e) {
warn("Failed to unregister MBean: " + key);
if (getLogger().isDebugEnabled()) {
error(e);
}
}
}
}
/**
* @return the management context.
*/
public static ManagementContext getManagementContext() {
if (managementContext == null) {
/* Try to find the jboss mbean server * /
MBeanServer mbsvr = null;
for (MBeanServer svr: MBeanServerFactory.findMBeanServer(null)) {
if (svr.getDefaultDomain().equals("jboss")) {
mbsvr = svr;
break;
}
}
if (mbsvr == null) {
Logger.getLogger(ConfBase.class).warn("Unable to locate jboss mbean server");
}
managementContext = new ManagementContext(mbsvr);
*/
managementContext = new ManagementContext(ManagementContext.DEFAULT_DOMAIN);
}
return managementContext;
}
protected static Object makeObject(final String className) {
try {
Object o = Class.forName(className).newInstance();
if (o == null) {
Logger.getLogger(ConfBase.class).error("Class " + className + " not found");
return null;
}
return o;
} catch (Throwable t) {
Logger.getLogger(ConfBase.class).error("Unable to make object ", t);
return null;
}
}
protected void info(final String msg) {
getLogger().info(msg);
}
protected void warn(final String msg) {
getLogger().warn(msg);
}
protected void debug(final String msg) {
getLogger().debug(msg);
}
protected void error(final Throwable t) {
getLogger().error(this, t);
}
protected void error(final String msg) {
getLogger().error(msg);
}
/* Get a logger for messages
*/
protected Logger getLogger() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
}
|
Better error message
|
src/main/java/edu/rpi/cmt/jmx/ConfBase.java
|
Better error message
|
|
Java
|
apache-2.0
|
a3fe717435a760e4c9553cace593fa372930c3e8
| 0
|
consulo/consulo-maven,consulo/consulo-maven
|
/*
* Copyright 2000-2009 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 org.jetbrains.idea.maven.navigator;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.swing.TransferHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenGoalLocation;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.model.MavenConstants;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenDataKeys;
import org.jetbrains.idea.maven.utils.actions.MavenActionUtil;
import com.intellij.execution.Location;
import com.intellij.ide.dnd.FileCopyPasteUtil;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.treeStructure.SimpleTree;
import com.intellij.util.containers.ContainerUtil;
public class MavenProjectsNavigatorPanel extends SimpleToolWindowPanel implements DataProvider {
private final Project myProject;
private final SimpleTree myTree;
private final Comparator<String> myGoalOrderComparator = new Comparator<String>() {
private Map<String, Integer> standardGoalOrder;
public int compare(String o1, String o2) {
return getStandardGoalOrder(o1) - getStandardGoalOrder(o2);
}
private int getStandardGoalOrder(String goal) {
if (standardGoalOrder == null) {
standardGoalOrder = new THashMap<String, Integer>();
int i = 0;
for (String aGoal : MavenConstants.PHASES) {
standardGoalOrder.put(aGoal, i++);
}
}
Integer order = standardGoalOrder.get(goal);
return order != null ? order.intValue() : standardGoalOrder.size();
}
};
public MavenProjectsNavigatorPanel(Project project, SimpleTree tree) {
super(true, true);
myProject = project;
myTree = tree;
final ActionManager actionManager = ActionManager.getInstance();
ActionToolbar actionToolbar = actionManager.createActionToolbar("Maven Navigator Toolbar",
(DefaultActionGroup)actionManager
.getAction("Maven.NavigatorActionsToolbar"),
true);
actionToolbar.setTargetComponent(tree);
setToolbar(actionToolbar.getComponent());
setContent(ScrollPaneFactory.createScrollPane(myTree));
setTransferHandler(new MyTransferHandler(project));
myTree.addMouseListener(new PopupHandler() {
public void invokePopup(final Component comp, final int x, final int y) {
final String id = getMenuId(getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class));
if (id != null) {
final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(id);
if (actionGroup != null) {
actionManager.createActionPopupMenu("", actionGroup).getComponent().show(comp, x, y);
}
}
}
@Nullable
private String getMenuId(Collection<? extends MavenProjectsStructure.MavenSimpleNode> nodes) {
String id = null;
for (MavenProjectsStructure.MavenSimpleNode node : nodes) {
String menuId = node.getMenuId();
if (menuId == null) {
return null;
}
if (id == null) {
id = menuId;
}
else if (!id.equals(menuId)) {
return null;
}
}
return id;
}
});
}
@Nullable
public Object getData(@NonNls String dataId) {
if (PlatformDataKeys.HELP_ID.is(dataId)) return "reference.toolWindows.mavenProjects";
if (CommonDataKeys.PROJECT.is(dataId)) return myProject;
if (PlatformDataKeys.VIRTUAL_FILE.is(dataId)) return extractVirtualFile();
if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) return extractVirtualFiles();
if (Location.DATA_KEY.is(dataId)) return extractLocation();
if (PlatformDataKeys.NAVIGATABLE_ARRAY.is(dataId)) return extractNavigatables();
if (MavenDataKeys.MAVEN_GOALS.is(dataId)) return extractGoals(true);
if (MavenDataKeys.MAVEN_PROFILES.is(dataId)) return extractProfiles();
if (MavenDataKeys.MAVEN_DEPENDENCIES.is(dataId)) {
return extractDependencies();
}
if (MavenDataKeys.MAVEN_PROJECTS_TREE.is(dataId)) {
return myTree;
}
return super.getData(dataId);
}
private VirtualFile extractVirtualFile() {
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
VirtualFile file = each.getVirtualFile();
if (file != null && file.isValid()) return file;
}
final MavenProjectsStructure.ProjectNode projectNode = getContextProjectNode();
if (projectNode == null) return null;
VirtualFile file = projectNode.getVirtualFile();
if (file == null || !file.isValid()) return null;
return file;
}
private Object extractVirtualFiles() {
final List<VirtualFile> files = new ArrayList<VirtualFile>();
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
VirtualFile file = each.getVirtualFile();
if (file != null && file.isValid()) files.add(file);
}
return files.isEmpty() ? null : VfsUtil.toVirtualFileArray(files);
}
private Object extractNavigatables() {
final List<Navigatable> navigatables = new ArrayList<Navigatable>();
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
Navigatable navigatable = each.getNavigatable();
if (navigatable != null) navigatables.add(navigatable);
}
return navigatables.isEmpty() ? null : navigatables.toArray(new Navigatable[navigatables.size()]);
}
private Object extractLocation() {
VirtualFile file = extractVirtualFile();
if (file == null) return null;
List<String> goals = extractGoals(false);
if (goals == null) return null;
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
return psiFile == null ? null : new MavenGoalLocation(myProject, psiFile, goals);
}
private List<String> extractGoals(boolean qualifiedGoals) {
final MavenProjectsStructure.ProjectNode projectNode = getSelectedProjectNode();
if (projectNode != null) {
MavenProject project = projectNode.getMavenProject();
String goal = project.getDefaultGoal();
if (!StringUtil.isEmptyOrSpaces(goal)) {
// Maven uses StringTokenizer to split defaultGoal. See DefaultLifecycleTaskSegmentCalculator#calculateTaskSegments()
return ContainerUtil.newArrayList(StringUtil.tokenize(new StringTokenizer(goal)));
}
}
else {
final List<MavenProjectsStructure.GoalNode> nodes = getSelectedNodes(MavenProjectsStructure.GoalNode.class);
if (MavenProjectsStructure.getCommonProjectNode(nodes) == null) {
return null;
}
final List<String> goals = new ArrayList<String>();
for (MavenProjectsStructure.GoalNode node : nodes) {
goals.add(qualifiedGoals ? node.getGoal() : node.getName());
}
Collections.sort(goals, myGoalOrderComparator);
return goals;
}
return null;
}
private Object extractProfiles() {
final List<MavenProjectsStructure.ProfileNode> nodes = getSelectedNodes(MavenProjectsStructure.ProfileNode.class);
final List<String> profiles = new ArrayList<String>();
for (MavenProjectsStructure.ProfileNode node : nodes) {
profiles.add(node.getProfileName());
}
return profiles;
}
private Set<MavenArtifact> extractDependencies() {
Set<MavenArtifact> result = new THashSet<MavenArtifact>();
List<MavenProjectsStructure.ProjectNode> projectNodes = getSelectedProjectNodes();
if (!projectNodes.isEmpty()) {
for (MavenProjectsStructure.ProjectNode each : projectNodes) {
result.addAll(each.getMavenProject().getDependencies());
}
return result;
}
List<MavenProjectsStructure.BaseDependenciesNode> nodes = getSelectedNodes(MavenProjectsStructure.BaseDependenciesNode.class);
for (MavenProjectsStructure.BaseDependenciesNode each : nodes) {
if (each instanceof MavenProjectsStructure.DependenciesNode) {
result.addAll(each.getMavenProject().getDependencies());
}
else {
result.add(((MavenProjectsStructure.DependencyNode)each).getArtifact());
}
}
return result;
}
private <T extends MavenProjectsStructure.MavenSimpleNode> List<T> getSelectedNodes(Class<T> aClass) {
return MavenProjectsStructure.getSelectedNodes(myTree, aClass);
}
private List<MavenProjectsStructure.ProjectNode> getSelectedProjectNodes() {
return getSelectedNodes(MavenProjectsStructure.ProjectNode.class);
}
@Nullable
private MavenProjectsStructure.ProjectNode getSelectedProjectNode() {
final List<MavenProjectsStructure.ProjectNode> projectNodes = getSelectedProjectNodes();
return projectNodes.size() == 1 ? projectNodes.get(0) : null;
}
@Nullable
private MavenProjectsStructure.ProjectNode getContextProjectNode() {
MavenProjectsStructure.ProjectNode projectNode = getSelectedProjectNode();
if (projectNode != null) return projectNode;
return MavenProjectsStructure.getCommonProjectNode(getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class));
}
private static class MyTransferHandler extends TransferHandler {
private final Project myProject;
private MyTransferHandler(Project project) {
myProject = project;
}
@Override
public boolean importData(final TransferSupport support) {
if (canImport(support)) {
List<VirtualFile> pomFiles = new ArrayList<VirtualFile>();
final List<File> fileList = FileCopyPasteUtil.getFileList(support.getTransferable());
if (fileList == null) return false;
MavenProjectsManager manager = MavenProjectsManager.getInstance(myProject);
for (File file : fileList) {
VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
if (file.isFile()
&& virtualFile != null
&& MavenActionUtil.isMavenProjectFile(virtualFile)
&& !manager.isManagedFile(virtualFile)) {
pomFiles.add(virtualFile);
}
}
if (pomFiles.isEmpty()) {
return false;
}
manager.addManagedFiles(pomFiles);
return true;
}
return false;
}
@Override
public boolean canImport(final TransferSupport support) {
return FileCopyPasteUtil.isFileListFlavorAvailable(support.getDataFlavors());
}
}
}
|
src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java
|
/*
* Copyright 2000-2009 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 org.jetbrains.idea.maven.navigator;
import com.intellij.execution.Location;
import com.intellij.ide.dnd.FileCopyPasteUtil;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.treeStructure.SimpleTree;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenGoalLocation;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.model.MavenConstants;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenDataKeys;
import org.jetbrains.idea.maven.utils.actions.MavenActionUtil;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
public class MavenProjectsNavigatorPanel extends SimpleToolWindowPanel implements DataProvider {
private final Project myProject;
private final SimpleTree myTree;
private final Comparator<String> myGoalOrderComparator = new Comparator<String>() {
private Map<String, Integer> standardGoalOrder;
public int compare(String o1, String o2) {
return getStandardGoalOrder(o1) - getStandardGoalOrder(o2);
}
private int getStandardGoalOrder(String goal) {
if (standardGoalOrder == null) {
standardGoalOrder = new THashMap<String, Integer>();
int i = 0;
for (String aGoal : MavenConstants.PHASES) {
standardGoalOrder.put(aGoal, i++);
}
}
Integer order = standardGoalOrder.get(goal);
return order != null ? order.intValue() : standardGoalOrder.size();
}
};
public MavenProjectsNavigatorPanel(Project project, SimpleTree tree) {
super(true, true);
myProject = project;
myTree = tree;
final ActionManager actionManager = ActionManager.getInstance();
ActionToolbar actionToolbar = actionManager.createActionToolbar("Maven Navigator Toolbar",
(DefaultActionGroup)actionManager
.getAction("Maven.NavigatorActionsToolbar"),
true);
actionToolbar.setTargetComponent(tree);
setToolbar(actionToolbar.getComponent());
setContent(ScrollPaneFactory.createScrollPane(myTree));
setTransferHandler(new MyTransferHandler(project));
myTree.addMouseListener(new PopupHandler() {
public void invokePopup(final Component comp, final int x, final int y) {
final String id = getMenuId(getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class));
if (id != null) {
final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(id);
if (actionGroup != null) {
actionManager.createActionPopupMenu("", actionGroup).getComponent().show(comp, x, y);
}
}
}
@Nullable
private String getMenuId(Collection<? extends MavenProjectsStructure.MavenSimpleNode> nodes) {
String id = null;
for (MavenProjectsStructure.MavenSimpleNode node : nodes) {
String menuId = node.getMenuId();
if (menuId == null) {
return null;
}
if (id == null) {
id = menuId;
}
else if (!id.equals(menuId)) {
return null;
}
}
return id;
}
});
}
@Nullable
public Object getData(@NonNls String dataId) {
if (PlatformDataKeys.HELP_ID.is(dataId)) return "reference.toolWindows.mavenProjects";
if (CommonDataKeys.PROJECT.is(dataId)) return myProject;
if (PlatformDataKeys.VIRTUAL_FILE.is(dataId)) return extractVirtualFile();
if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) return extractVirtualFiles();
if (Location.DATA_KEY.is(dataId)) return extractLocation();
if (PlatformDataKeys.NAVIGATABLE_ARRAY.is(dataId)) return extractNavigatables();
if (MavenDataKeys.MAVEN_GOALS.is(dataId)) return extractGoals(true);
if (MavenDataKeys.MAVEN_PROFILES.is(dataId)) return extractProfiles();
if (MavenDataKeys.MAVEN_DEPENDENCIES.is(dataId)) {
return extractDependencies();
}
if (MavenDataKeys.MAVEN_PROJECTS_TREE.is(dataId)) {
return myTree;
}
return super.getData(dataId);
}
private VirtualFile extractVirtualFile() {
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
VirtualFile file = each.getVirtualFile();
if (file != null && file.isValid()) return file;
}
final MavenProjectsStructure.ProjectNode projectNode = getContextProjectNode();
if (projectNode == null) return null;
VirtualFile file = projectNode.getVirtualFile();
if (file == null || !file.isValid()) return null;
return file;
}
private Object extractVirtualFiles() {
final List<VirtualFile> files = new ArrayList<VirtualFile>();
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
VirtualFile file = each.getVirtualFile();
if (file != null && file.isValid()) files.add(file);
}
return files.isEmpty() ? null : VfsUtil.toVirtualFileArray(files);
}
private Object extractNavigatables() {
final List<Navigatable> navigatables = new ArrayList<Navigatable>();
for (MavenProjectsStructure.MavenSimpleNode each : getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class)) {
Navigatable navigatable = each.getNavigatable();
if (navigatable != null) navigatables.add(navigatable);
}
return navigatables.isEmpty() ? null : navigatables.toArray(new Navigatable[navigatables.size()]);
}
private Object extractLocation() {
VirtualFile file = extractVirtualFile();
if (file == null) return null;
List<String> goals = extractGoals(false);
if (goals == null) return null;
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
return psiFile == null ? null : new MavenGoalLocation(myProject, psiFile, goals);
}
private List<String> extractGoals(boolean qualifiedGoals) {
final MavenProjectsStructure.ProjectNode projectNode = getSelectedProjectNode();
if (projectNode != null) {
MavenProject project = projectNode.getMavenProject();
String goal = project.getDefaultGoal();
if (!StringUtil.isEmptyOrSpaces(goal)) {
// Maven uses StringTokenizer to split defaultGoal. See DefaultLifecycleTaskSegmentCalculator#calculateTaskSegments()
return ContainerUtil.newArrayList(StringUtil.tokenize(new StringTokenizer(goal)));
}
}
else {
final List<MavenProjectsStructure.GoalNode> nodes = getSelectedNodes(MavenProjectsStructure.GoalNode.class);
if (MavenProjectsStructure.getCommonProjectNode(nodes) == null) {
return null;
}
final List<String> goals = new ArrayList<String>();
for (MavenProjectsStructure.GoalNode node : nodes) {
goals.add(qualifiedGoals ? node.getGoal() : node.getName());
}
Collections.sort(goals, myGoalOrderComparator);
return goals;
}
return null;
}
private Object extractProfiles() {
final List<MavenProjectsStructure.ProfileNode> nodes = getSelectedNodes(MavenProjectsStructure.ProfileNode.class);
final List<String> profiles = new ArrayList<String>();
for (MavenProjectsStructure.ProfileNode node : nodes) {
profiles.add(node.getProfileName());
}
return profiles;
}
private Set<MavenArtifact> extractDependencies() {
Set<MavenArtifact> result = new THashSet<MavenArtifact>();
List<MavenProjectsStructure.ProjectNode> projectNodes = getSelectedProjectNodes();
if (!projectNodes.isEmpty()) {
for (MavenProjectsStructure.ProjectNode each : projectNodes) {
result.addAll(each.getMavenProject().getDependencies());
}
return result;
}
List<MavenProjectsStructure.BaseDependenciesNode> nodes = getSelectedNodes(MavenProjectsStructure.BaseDependenciesNode.class);
for (MavenProjectsStructure.BaseDependenciesNode each : nodes) {
if (each instanceof MavenProjectsStructure.DependenciesNode) {
result.addAll(each.getMavenProject().getDependencies());
}
else {
result.add(((MavenProjectsStructure.DependencyNode)each).getArtifact());
}
}
return result;
}
private <T extends MavenProjectsStructure.MavenSimpleNode> List<T> getSelectedNodes(Class<T> aClass) {
return MavenProjectsStructure.getSelectedNodes(myTree, aClass);
}
private List<MavenProjectsStructure.ProjectNode> getSelectedProjectNodes() {
return getSelectedNodes(MavenProjectsStructure.ProjectNode.class);
}
@Nullable
private MavenProjectsStructure.ProjectNode getSelectedProjectNode() {
final List<MavenProjectsStructure.ProjectNode> projectNodes = getSelectedProjectNodes();
return projectNodes.size() == 1 ? projectNodes.get(0) : null;
}
@Nullable
private MavenProjectsStructure.ProjectNode getContextProjectNode() {
MavenProjectsStructure.ProjectNode projectNode = getSelectedProjectNode();
if (projectNode != null) return projectNode;
return MavenProjectsStructure.getCommonProjectNode(getSelectedNodes(MavenProjectsStructure.MavenSimpleNode.class));
}
private static class MyTransferHandler extends TransferHandler {
private final Project myProject;
private MyTransferHandler(Project project) {
myProject = project;
}
@Override
public boolean importData(final TransferSupport support) {
if (canImport(support)) {
List<VirtualFile> pomFiles = new ArrayList<VirtualFile>();
final List<File> fileList = FileCopyPasteUtil.getFileList(support.getTransferable());
if (fileList == null) return false;
MavenProjectsManager manager = MavenProjectsManager.getInstance(myProject);
for (File file : fileList) {
VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
if (file.isFile()
&& virtualFile != null
&& MavenActionUtil.isMavenProjectFile(virtualFile)
&& !manager.isManagedFile(virtualFile)) {
pomFiles.add(virtualFile);
}
}
if (pomFiles.isEmpty()) {
return false;
}
manager.addManagedFiles(pomFiles);
return true;
}
return false;
}
@Override
public boolean canImport(final TransferSupport support) {
return FileCopyPasteUtil.isFileListFlavorSupported(support.getDataFlavors());
}
}
}
|
compilation fixed
|
src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigatorPanel.java
|
compilation fixed
|
|
Java
|
apache-2.0
|
2c700ef6d1880905e7aecdd7f4de38d48c262854
| 0
|
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
|
package swift.client;
import static sys.net.api.Networking.Networking;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import swift.client.proto.CommitUpdatesReply;
import swift.client.proto.CommitUpdatesReply.CommitStatus;
import swift.client.proto.CommitUpdatesReplyHandler;
import swift.client.proto.CommitUpdatesRequest;
import swift.client.proto.FastRecentUpdatesReply;
import swift.client.proto.FastRecentUpdatesReply.ObjectSubscriptionInfo;
import swift.client.proto.FastRecentUpdatesReply.SubscriptionStatus;
import swift.client.proto.FastRecentUpdatesReplyHandler;
import swift.client.proto.FastRecentUpdatesRequest;
import swift.client.proto.FetchObjectDeltaRequest;
import swift.client.proto.FetchObjectVersionReply;
import swift.client.proto.FetchObjectVersionReply.FetchStatus;
import swift.client.proto.FetchObjectVersionReplyHandler;
import swift.client.proto.FetchObjectVersionRequest;
import swift.client.proto.GenerateTimestampReply;
import swift.client.proto.GenerateTimestampReplyHandler;
import swift.client.proto.GenerateTimestampRequest;
import swift.client.proto.LatestKnownClockReply;
import swift.client.proto.LatestKnownClockReplyHandler;
import swift.client.proto.LatestKnownClockRequest;
import swift.client.proto.SubscriptionType;
import swift.clocks.CausalityClock;
import swift.clocks.CausalityClock.CMP_CLOCK;
import swift.clocks.ClockFactory;
import swift.clocks.IncrementalTimestampGenerator;
import swift.clocks.Timestamp;
import swift.crdt.CRDTIdentifier;
import swift.crdt.interfaces.CRDT;
import swift.crdt.interfaces.CRDTOperationDependencyPolicy;
import swift.crdt.interfaces.CachePolicy;
import swift.crdt.interfaces.IsolationLevel;
import swift.crdt.interfaces.ObjectUpdatesListener;
import swift.crdt.interfaces.Swift;
import swift.crdt.interfaces.TxnLocalCRDT;
import swift.crdt.interfaces.TxnStatus;
import swift.crdt.operations.CRDTObjectOperationsGroup;
import swift.exceptions.VersionNotFoundException;
import swift.exceptions.NetworkException;
import swift.exceptions.NoSuchObjectException;
import swift.exceptions.WrongTypeException;
import sys.net.api.Endpoint;
import sys.net.api.rpc.RpcConnection;
import sys.net.api.rpc.RpcEndpoint;
/**
* Implementation of Swift client and transactions manager.
*
* @see Swift, TxnManager
* @author mzawirski
*/
public class SwiftImpl implements Swift, TxnManager {
// TODO: cache eviction and pruning
// TODO: server failover
// WISHME: This class uses very coarse-grained locking, but given the
// complexity of causality tracking and timestamps remapping, unless we
// prove it is a real issue for a client application, I would rather keep it
// this way. In any case, locking should not affect responsiveness to
// pendingTxn requests.
public static int DEFAULT_TIMEOUT_MILLIS = 10000;
private static final String CLIENT_CLOCK_ID = "client";
private static Logger logger = Logger.getLogger(SwiftImpl.class.getName());
/**
* Creates new instance of Swift using provided network settings and default
* cache parameters.
*
* @param localPort
* port to bind local RPC endpoint
* @param serverHostname
* hostname of storage server
* @param serverPort
* TCP port of storage server
* @return instance of Swift client
*/
public static SwiftImpl newInstance(int localPort, String serverHostname, int serverPort) {
return new SwiftImpl(Networking.rpcBind(localPort, null), Networking.resolve(serverHostname, serverPort),
new InfiniteObjectsCache(), DEFAULT_TIMEOUT_MILLIS);
}
private static String generateClientId() {
final Random random = new Random(System.currentTimeMillis());
return Long.toHexString(System.identityHashCode(random) + random.nextLong());
}
private boolean stopFlag;
private boolean stopGracefully;
private final String clientId;
private final RpcEndpoint localEndpoint;
private final Endpoint serverEndpoint;
private final CommitterThread committerThread;
// Cache of objects.
// Invariant: if object is in the cache, it must include all updates
// of locally and globally committed locally-originating transactions.
private final InfiniteObjectsCache objectsCache;
// Invariant: committedVersion only grows.
private final CausalityClock commitedVersion;
// Invariant: there is at most one pending (open) transaction.
private AbstractTxnHandle pendingTxn;
// Locally committed transactions (in commit order), the first one is
// possibly committing to the store.
private final LinkedList<AbstractTxnHandle> locallyCommittedTxnsQueue;
// Local dependencies of a pending transaction.
private final LinkedList<AbstractTxnHandle> pendingTxnLocalDependencies;
private final Map<CRDTIdentifier, ObjectUpdatesSubscription> subscribedObjectsAccesses;
private final NotoficationsProcessorThread notificationsThread;
private IncrementalTimestampGenerator clientTimestampGenerator;
private final int timeoutMillis;
SwiftImpl(final RpcEndpoint localEndpoint, final Endpoint serverEndpoint, InfiniteObjectsCache objectsCache,
int timeoutMillis) {
this.clientId = generateClientId();
this.timeoutMillis = timeoutMillis;
this.localEndpoint = localEndpoint;
this.serverEndpoint = serverEndpoint;
this.objectsCache = objectsCache;
this.locallyCommittedTxnsQueue = new LinkedList<AbstractTxnHandle>();
this.pendingTxnLocalDependencies = new LinkedList<AbstractTxnHandle>();
this.commitedVersion = ClockFactory.newClock();
this.clientTimestampGenerator = new IncrementalTimestampGenerator(CLIENT_CLOCK_ID);
this.committerThread = new CommitterThread();
this.committerThread.start();
this.subscribedObjectsAccesses = new HashMap<CRDTIdentifier, ObjectUpdatesSubscription>();
this.notificationsThread = new NotoficationsProcessorThread();
this.notificationsThread.start();
}
@Override
public void stop(boolean waitForCommit) {
synchronized (this) {
stopFlag = true;
stopGracefully = waitForCommit;
this.notifyAll();
}
try {
committerThread.join();
// No need to close notifications thread in theory, but it brakes
// the connection and makes debugging harder.
notificationsThread.join();
} catch (InterruptedException e) {
logger.warning(e.getMessage());
}
}
@Override
public synchronized AbstractTxnHandle beginTxn(IsolationLevel isolationLevel, CachePolicy cachePolicy,
boolean readOnly) throws NetworkException {
// FIXME: Ooops, readOnly is present here at API level, respect it here
// and in TxnHandleImpl or remove it from API.
assertNoPendingTransaction();
assertRunning();
switch (isolationLevel) {
case SNAPSHOT_ISOLATION:
if (cachePolicy == CachePolicy.MOST_RECENT || cachePolicy == CachePolicy.STRICTLY_MOST_RECENT) {
final AtomicBoolean doneFlag = new AtomicBoolean(false);
localEndpoint.send(serverEndpoint, new LatestKnownClockRequest(clientId),
new LatestKnownClockReplyHandler() {
@Override
public void onReceive(RpcConnection conn, LatestKnownClockReply reply) {
updateCommittedVersion(reply.getClock());
doneFlag.set(true);
}
}, timeoutMillis);
if (!doneFlag.get() && cachePolicy == CachePolicy.STRICTLY_MOST_RECENT) {
throw new NetworkException("timed out to get transcation snapshot point");
}
}
final Timestamp localTimestmap = clientTimestampGenerator.generateNew();
// Invariant: for SI snapshotClock of a new transaction dominates
// clock of all previous SI transaction (monotonic reads), since
// commitedVersion only grows.
final CausalityClock snapshotClock = commitedVersion.clone();
setPendingTxn(new SnapshotIsolationTxnHandle(this, cachePolicy, localTimestmap, snapshotClock));
logger.info("SI transaction " + localTimestmap + " started with global snapshot point: " + snapshotClock);
return pendingTxn;
default:
// FIXME: implement other isolation levels.
throw new UnsupportedOperationException("isolation level " + isolationLevel + " unsupported");
}
}
private synchronized void updateCommittedVersion(final CausalityClock clock) {
if (clock == null) {
logger.warning("server returned null clock");
return;
}
commitedVersion.merge(clock);
final AbstractTxnHandle commitingTxn = locallyCommittedTxnsQueue.peekFirst();
if (commitingTxn != null && clock.includes(commitingTxn.getGlobalTimestamp())) {
// We observe global visibility (and possibly updates) of locally
// committed transaction before the CommitUpdatesReply has been
// received.
applyGloballyCommittedTxn(commitingTxn);
}
}
@Override
public synchronized <V extends CRDT<V>> TxnLocalCRDT<V> getObjectTxnView(AbstractTxnHandle txn, CRDTIdentifier id,
CausalityClock minVersion, final boolean tryMoreRecent, boolean create, Class<V> classOfV,
final ObjectUpdatesListener updatesListener) throws WrongTypeException, NoSuchObjectException,
VersionNotFoundException, NetworkException {
assertPendingTransaction(txn);
if (minVersion.hasEventFrom(CLIENT_CLOCK_ID)) {
throw new IllegalArgumentException("transaction requested visibility of local transaction");
}
// FIXME honor tryMoreRecent and check with commitedVersion
TxnLocalCRDT<V> localView = getCachedObjectForTxn(id, minVersion, classOfV);
if (localView != null) {
return localView;
}
// FIXME: support updatesListener for real
final CausalityClock clock = clockWithLocalDependencies(minVersion);
clock.drop(CLIENT_CLOCK_ID);
fetchLatestObject(id, create, classOfV, clock, updatesListener != null);
localView = getCachedObjectForTxn(id, minVersion, classOfV);
if (localView == null) {
throw new IllegalStateException(
"Internal error: just retrieved object unavailable in appropriate version in the cache");
}
return localView;
}
private CausalityClock clockWithLocalDependencies(CausalityClock clock) {
clock = clock.clone();
for (final AbstractTxnHandle dependentTxn : pendingTxnLocalDependencies) {
// Include in clock those dependent transactions that already
// committed globally after the pending transaction started.
if (dependentTxn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
clock.record(dependentTxn.getGlobalTimestamp());
} else {
clock.record(dependentTxn.getLocalTimestamp());
}
}
return clock;
}
@SuppressWarnings("unchecked")
private synchronized <V extends CRDT<V>> TxnLocalCRDT<V> getCachedObjectForTxn(CRDTIdentifier id,
CausalityClock clock, Class<V> classOfV) throws WrongTypeException, VersionNotFoundException {
V crdt;
try {
crdt = (V) objectsCache.get(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
if (crdt == null) {
return null;
}
if (clock == null) {
// Return the most recent version.
clock = crdt.getClock();
}
clock = clockWithLocalDependencies(clock);
final CausalityClock globalClock = clock.clone();
globalClock.drop(CLIENT_CLOCK_ID);
final CMP_CLOCK clockCmp = crdt.getClock().compareTo(globalClock);
if (clockCmp == CMP_CLOCK.CMP_CONCURRENT || clockCmp == CMP_CLOCK.CMP_ISDOMINATED) {
return null;
}
final CMP_CLOCK pruneCmp = globalClock.compareTo(crdt.getPruneClock());
if (pruneCmp == CMP_CLOCK.CMP_ISDOMINATED || pruneCmp == CMP_CLOCK.CMP_CONCURRENT) {
throw new VersionNotFoundException("version consistent with current snapshot is not available in the store");
// TODO: Or just in the cache? return to it if server returns pruned
// crdt.
}
final TxnLocalCRDT<V> crdtView;
// Are there any local dependencies to apply on the cached object?
if (clock.hasEventFrom(CLIENT_CLOCK_ID)) {
// Apply them on sandboxed copy of an object, since these operations
// use local timestamps.
final V crdtCopy = crdt.copy();
for (final AbstractTxnHandle dependentTxn : pendingTxnLocalDependencies) {
final CRDTObjectOperationsGroup<V> localOps;
try {
localOps = (CRDTObjectOperationsGroup<V>) dependentTxn.getObjectLocalOperations(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
if (localOps != null) {
crdtCopy.execute(localOps, CRDTOperationDependencyPolicy.IGNORE);
}
}
crdtView = crdtCopy.getTxnLocalCopy(clock, pendingTxn);
} else {
crdtView = crdt.getTxnLocalCopy(clock, pendingTxn);
}
return crdtView;
}
private <V extends CRDT<V>> void fetchLatestObject(CRDTIdentifier id, boolean create, Class<V> classOfV,
CausalityClock minVersion, final boolean subscribeUpdates) throws WrongTypeException,
NoSuchObjectException, VersionNotFoundException, NetworkException {
final V crdt;
synchronized (this) {
try {
crdt = (V) objectsCache.get(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
}
if (crdt == null) {
fetchLatestObjectFromScratch(id, create, classOfV, minVersion, subscribeUpdates);
} else {
fetchLatestObjectByRefresh(id, create, classOfV, crdt, minVersion, subscribeUpdates);
}
}
@SuppressWarnings("unchecked")
private <V extends CRDT<V>> void fetchLatestObjectFromScratch(CRDTIdentifier id, boolean create, Class<V> classOfV,
CausalityClock minVersion, boolean subscribeUpdates) throws NoSuchObjectException, WrongTypeException,
VersionNotFoundException, NetworkException {
final AtomicReference<FetchObjectVersionReply> replyRef = new AtomicReference<FetchObjectVersionReply>();
final SubscriptionType subscriptionType = subscribeUpdates ? SubscriptionType.UPDATES : SubscriptionType.NONE;
localEndpoint.send(serverEndpoint, new FetchObjectVersionRequest(clientId, id, minVersion, subscriptionType),
new FetchObjectVersionReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FetchObjectVersionReply reply) {
replyRef.set(reply);
}
}, timeoutMillis);
if (replyRef.get() == null) {
throw new NetworkException("Fetching object version timed out");
}
processFetchObjectReply(id, create, classOfV, replyRef.get());
}
@SuppressWarnings("unchecked")
private <V extends CRDT<V>> void fetchLatestObjectByRefresh(CRDTIdentifier id, boolean create, Class<V> classOfV,
V cachedCrdt, CausalityClock minVersion, boolean subscribeUpdates) throws NoSuchObjectException,
WrongTypeException, VersionNotFoundException, NetworkException {
final CausalityClock oldCrdtClock;
synchronized (this) {
oldCrdtClock = cachedCrdt.getClock().clone();
}
// WISHME: we should replace it with deltas or operations list
final AtomicReference<FetchObjectVersionReply> replyRef = new AtomicReference<FetchObjectVersionReply>();
final SubscriptionType subscriptionType = subscribeUpdates ? SubscriptionType.UPDATES : SubscriptionType.NONE;
localEndpoint.send(serverEndpoint, new FetchObjectDeltaRequest(clientId, id, oldCrdtClock, minVersion,
subscriptionType), new FetchObjectVersionReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FetchObjectVersionReply reply) {
replyRef.set(reply);
}
}, timeoutMillis);
if (replyRef.get() == null) {
throw new NetworkException("Fetching newer object version timed out");
}
processFetchObjectReply(id, create, classOfV, replyRef.get());
}
private <V extends CRDT<V>> void processFetchObjectReply(CRDTIdentifier id, boolean create, Class<V> classOfV,
final FetchObjectVersionReply fetchReply) throws NoSuchObjectException, WrongTypeException,
VersionNotFoundException {
final V crdt;
switch (fetchReply.getStatus()) {
case OBJECT_NOT_FOUND:
if (!create) {
throw new NoSuchObjectException("object " + id.toString() + " not found");
}
try {
crdt = classOfV.newInstance();
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
crdt.init(id, fetchReply.getVersion(), fetchReply.getPruneClock(), true);
break;
case VERSION_NOT_FOUND:
case OK:
try {
crdt = (V) fetchReply.getCrdt();
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
crdt.init(id, fetchReply.getVersion(), fetchReply.getPruneClock(), true);
break;
default:
throw new IllegalStateException("Unexpected status code" + fetchReply.getStatus());
}
synchronized (this) {
final V cachedCRDT;
try {
cachedCRDT = (V) objectsCache.get(id);
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
if (cachedCRDT == null) {
objectsCache.add(crdt);
} else {
cachedCRDT.merge(crdt);
// FIXME: check for updates and notify listener?
}
updateCommittedVersion(fetchReply.getEstimatedLatestKnownClock());
}
if (fetchReply.getStatus() == FetchStatus.VERSION_NOT_FOUND) {
// FIXME: retry if version <= minVerson?
throw new VersionNotFoundException("requested version not found in the store");
}
}
private void applyObjectUpdates(final CRDTIdentifier id, final CausalityClock dependencyClock,
final List<CRDTObjectOperationsGroup<?>> ops, final CausalityClock outputClock) {
final CRDT crdt;
final CausalityClock crdtClockCopy;
synchronized (this) {
crdt = objectsCache.get(id);
crdtClockCopy = crdt == null ? null : crdt.getClock().clone();
}
if (crdt == null) {
// Ooops, we evicted the object from the cache.
logger.warning("cannot apply received updates on object " + id + " as it has been evicted from the cache");
// FIXME trigger fetch() and then applyObjectUpdates()
return;
}
final CMP_CLOCK clkCmp = crdtClockCopy.compareTo(dependencyClock);
if (clkCmp == CMP_CLOCK.CMP_ISDOMINATED || clkCmp == CMP_CLOCK.CMP_CONCURRENT) {
// Ooops, we missed some update or messages were ordered.
logger.warning("cannot apply received updates on object " + id + " due to unsatisfied dependencies");
// FIXME trigger fetch() and then applyObjectUpdates()
return;
}
synchronized (this) {
for (final CRDTObjectOperationsGroup<?> op : ops) {
if (crdt.execute(op, CRDTOperationDependencyPolicy.RECORD_BLINDLY)) {
// FIXME: notify listener?
}
}
crdt.getClock().merge(outputClock);
}
}
@Override
public synchronized void discardTxn(AbstractTxnHandle txn) {
assertPendingTransaction(txn);
setPendingTxn(null);
}
@Override
public synchronized void commitTxn(AbstractTxnHandle txn) {
assertPendingTransaction(txn);
assertRunning();
// Big WISHME: write disk log and allow local recovery.
txn.markLocallyCommitted();
logger.info("transaction " + txn.getLocalTimestamp() + " commited locally");
if (txn.isReadOnly()) {
// Read-only transaction can be immediately discarded.
txn.markGloballyCommitted();
logger.info("read-only transaction " + txn.getLocalTimestamp() + " (virtually) commited globally");
} else {
for (final AbstractTxnHandle dependeeTxn : pendingTxnLocalDependencies) {
// Replace timestamps of transactions that globally committed
// when this transaction was pending.
if (dependeeTxn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
txn.includeGlobalDependency(dependeeTxn.getLocalTimestamp(), dependeeTxn.getGlobalTimestamp());
}
}
// Update transaction is queued up for global commit.
addLocallyCommittedTransaction(txn);
}
setPendingTxn(null);
}
private void addLocallyCommittedTransaction(AbstractTxnHandle txn) {
locallyCommittedTxnsQueue.addLast(txn);
// Notify committer thread.
this.notifyAll();
}
/**
* Stubborn commit procedure, tries to get a global timestamp for a
* transaction and commit using this timestamp. Repeats until it succeeds.
*
* @param txn
* locally committed transaction
*/
private void commitToStore(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL);
if (txn.getUpdatesDependencyClock().hasEventFrom(CLIENT_CLOCK_ID)) {
throw new IllegalStateException("Trying to commit to data store with client clock");
}
final AtomicReference<CommitUpdatesReply> commitReplyRef = new AtomicReference<CommitUpdatesReply>();
do {
requestTxnGlobalTimestamp(txn);
final LinkedList<CRDTObjectOperationsGroup<?>> operationsGroups = new LinkedList<CRDTObjectOperationsGroup<?>>(
txn.getAllGlobalOperations());
// Commit at server.
do {
localEndpoint.send(serverEndpoint, new CommitUpdatesRequest(clientId, txn.getGlobalTimestamp(),
operationsGroups), new CommitUpdatesReplyHandler() {
@Override
public void onReceive(RpcConnection conn, CommitUpdatesReply reply) {
commitReplyRef.set(reply);
}
}, timeoutMillis);
} while (commitReplyRef.get() == null);
} while (commitReplyRef.get().getStatus() == CommitStatus.INVALID_TIMESTAMP);
if (commitReplyRef.get().getStatus() == CommitStatus.ALREADY_COMMITTED) {
// FIXME Perhaps we could move this complexity to RequestTimestamp
// on server side?
throw new UnsupportedOperationException("transaction committed under another timestamp");
}
logger.info("transaction " + txn.getLocalTimestamp() + " commited globally as " + txn.getGlobalTimestamp());
}
/**
* Requests and assigns a new global timestamp for the transaction.
*
* @param txn
* locally committed transaction
*/
private void requestTxnGlobalTimestamp(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL);
final AtomicReference<GenerateTimestampReply> timestampReplyRef = new AtomicReference<GenerateTimestampReply>();
do {
localEndpoint.send(serverEndpoint, new GenerateTimestampRequest(clientId, txn.getUpdatesDependencyClock(),
txn.getGlobalTimestamp()), new GenerateTimestampReplyHandler() {
@Override
public void onReceive(RpcConnection conn, GenerateTimestampReply reply) {
timestampReplyRef.set(reply);
}
}, timeoutMillis);
} while (timestampReplyRef.get() == null);
// And replace old timestamp in operations with timestamp from server.
txn.setGlobalTimestamp(timestampReplyRef.get().getTimestamp());
}
/**
* Applies globally committed transaction locally using a global timestamp.
*
* @param txn
* globally committed transaction to apply locally
*/
private synchronized void applyGloballyCommittedTxn(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL);
if (txn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
return;
}
txn.markGloballyCommitted();
for (final CRDTObjectOperationsGroup opsGroup : txn.getAllGlobalOperations()) {
// Try to apply changes in a cached copy of an object.
final CRDT<?> crdt = objectsCache.get(opsGroup.getTargetUID());
if (crdt == null) {
logger.warning("object evicted from the local cache before global commit");
} else {
crdt.execute(opsGroup, CRDTOperationDependencyPolicy.IGNORE);
}
}
for (final AbstractTxnHandle dependingTxn : locallyCommittedTxnsQueue) {
if (dependingTxn != txn) {
dependingTxn.includeGlobalDependency(txn.getLocalTimestamp(), txn.getGlobalTimestamp());
}
// pendingTxn will map timestamp later inside commitToStore().
// TODO [tricky]: to implement IsolationLevel.READ_COMMITTED we may
// need to replace timestamps in pending transaction too.
}
commitedVersion.record(txn.getGlobalTimestamp());
}
private synchronized AbstractTxnHandle getNextLocallyCommittedTxnBlocking() {
while (locallyCommittedTxnsQueue.isEmpty() && !stopFlag) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
return locallyCommittedTxnsQueue.peekFirst();
}
private synchronized void setPendingTxn(final AbstractTxnHandle txn) {
pendingTxn = txn;
pendingTxnLocalDependencies.clear();
if (txn != null) {
pendingTxnLocalDependencies.addAll(locallyCommittedTxnsQueue);
}
}
private void fetchSubscribedNotifications() {
final AtomicReference<FastRecentUpdatesReply> replyRef = new AtomicReference<FastRecentUpdatesReply>();
localEndpoint.send(serverEndpoint, new FastRecentUpdatesRequest(clientId), new FastRecentUpdatesReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FastRecentUpdatesReply reply) {
replyRef.set(reply);
}
}, timeoutMillis);
final FastRecentUpdatesReply notifications = replyRef.get();
if (notifications == null) {
logger.warning("server timed out on subscriptions information request");
return;
}
logger.fine("notifications received for " + notifications.getSubscriptions().size() + " objects");
updateCommittedVersion(notifications.getEstimatedLatestKnownClock());
if (notifications.getStatus() == SubscriptionStatus.ACTIVE) {
for (final ObjectSubscriptionInfo subscriptionInfo : notifications.getSubscriptions()) {
if (subscriptionInfo.isDirty() && subscriptionInfo.getUpdates().isEmpty()) {
// FIXME
logger.warning("unexpected server notification information without update");
} else {
applyObjectUpdates(subscriptionInfo.getId(), subscriptionInfo.getOldClock(),
subscriptionInfo.getUpdates(), subscriptionInfo.getNewClock());
}
}
} else {
// FIXME: renew subscriptions
}
// FIXME: wait? or will server block and control the frequency on its
// own?
// FIXME: GC of subscriptions
// FIXME: real notifications to the client
}
private void assertNoPendingTransaction() {
if (pendingTxn != null) {
throw new IllegalStateException("Only one transaction can be executing at the time");
}
}
private void assertPendingTransaction(final AbstractTxnHandle expectedTxn) {
if (!pendingTxn.equals(expectedTxn)) {
throw new IllegalStateException(
"Corrupted state: unexpected transaction is bothering me, not the pending one");
}
}
private void assertRunning() {
if (stopFlag) {
throw new IllegalStateException("client is stopped");
}
}
/**
* Thread continuously committing locally committed transactions. The thread
* takes the oldest locally committed transaction one by one, tries to
* commit it to the store and applies to it to local cache and depender
* transactions.
*/
private class CommitterThread extends Thread {
public CommitterThread() {
super("SwiftTransactionCommitterThread");
}
@Override
public void run() {
while (true) {
final AbstractTxnHandle nextToCommit = getNextLocallyCommittedTxnBlocking();
if (stopFlag && (!stopGracefully || nextToCommit == null)) {
return;
}
commitToStore(nextToCommit);
applyGloballyCommittedTxn(nextToCommit);
// Clean up after nextToCommit.
if (locallyCommittedTxnsQueue.removeFirst() != nextToCommit) {
throw new IllegalStateException("internal error, concurrently commiting transactions?");
}
}
}
}
private class NotoficationsProcessorThread extends Thread {
public NotoficationsProcessorThread() {
super("SwiftNotificationsProcessorThread");
}
@Override
public void run() {
while (true) {
synchronized (SwiftImpl.this) {
if (stopFlag) {
return;
}
}
fetchSubscribedNotifications();
}
}
}
private static class ObjectUpdatesSubscription {
private CausalityClock versionRead;
private boolean notified;
private AbstractTxnHandle txn;
private TxnLocalCRDT<?> crdtView;
public ObjectUpdatesSubscription(CausalityClock version, AbstractTxnHandle txn, TxnLocalCRDT<?> crdtView) {
this.versionRead = version;
this.txn = txn;
this.crdtView = crdtView;
this.notified = false;
}
}
}
|
src/swift/client/SwiftImpl.java
|
package swift.client;
import static sys.net.api.Networking.Networking;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import swift.client.proto.CommitUpdatesReply;
import swift.client.proto.CommitUpdatesReply.CommitStatus;
import swift.client.proto.CommitUpdatesReplyHandler;
import swift.client.proto.CommitUpdatesRequest;
import swift.client.proto.FastRecentUpdatesReply;
import swift.client.proto.FastRecentUpdatesReply.ObjectSubscriptionInfo;
import swift.client.proto.FastRecentUpdatesReply.SubscriptionStatus;
import swift.client.proto.FastRecentUpdatesReplyHandler;
import swift.client.proto.FastRecentUpdatesRequest;
import swift.client.proto.FetchObjectDeltaRequest;
import swift.client.proto.FetchObjectVersionReply;
import swift.client.proto.FetchObjectVersionReply.FetchStatus;
import swift.client.proto.FetchObjectVersionReplyHandler;
import swift.client.proto.FetchObjectVersionRequest;
import swift.client.proto.GenerateTimestampReply;
import swift.client.proto.GenerateTimestampReplyHandler;
import swift.client.proto.GenerateTimestampRequest;
import swift.client.proto.LatestKnownClockReply;
import swift.client.proto.LatestKnownClockReplyHandler;
import swift.client.proto.LatestKnownClockRequest;
import swift.client.proto.SubscriptionType;
import swift.clocks.CausalityClock;
import swift.clocks.CausalityClock.CMP_CLOCK;
import swift.clocks.ClockFactory;
import swift.clocks.IncrementalTimestampGenerator;
import swift.clocks.Timestamp;
import swift.crdt.CRDTIdentifier;
import swift.crdt.interfaces.CRDT;
import swift.crdt.interfaces.CRDTOperationDependencyPolicy;
import swift.crdt.interfaces.CachePolicy;
import swift.crdt.interfaces.IsolationLevel;
import swift.crdt.interfaces.ObjectUpdatesListener;
import swift.crdt.interfaces.Swift;
import swift.crdt.interfaces.TxnLocalCRDT;
import swift.crdt.interfaces.TxnStatus;
import swift.crdt.operations.CRDTObjectOperationsGroup;
import swift.exceptions.VersionNotFoundException;
import swift.exceptions.NetworkException;
import swift.exceptions.NoSuchObjectException;
import swift.exceptions.WrongTypeException;
import sys.net.api.Endpoint;
import sys.net.api.rpc.RpcConnection;
import sys.net.api.rpc.RpcEndpoint;
/**
* Implementation of Swift client and transactions manager.
*
* @see Swift, TxnManager
* @author mzawirski
*/
public class SwiftImpl implements Swift, TxnManager {
// TODO: cache eviction and pruning
// TODO: server failover
// WISHME: This class uses very coarse-grained locking, but given the
// complexity of causality tracking and timestamps remapping, unless we
// prove it is a real issue for a client application, I would rather keep it
// this way. In any case, locking should not affect responsiveness to
// pendingTxn requests.
public static int DEFAULT_TIMEOUT_MILLIS = 10000;
private static final String CLIENT_CLOCK_ID = "client";
private static Logger logger = Logger.getLogger(SwiftImpl.class.getName());
/**
* Creates new instance of Swift using provided network settings and default
* cache parameters.
*
* @param localPort
* port to bind local RPC endpoint
* @param serverHostname
* hostname of storage server
* @param serverPort
* TCP port of storage server
* @return instance of Swift client
*/
public static SwiftImpl newInstance(int localPort, String serverHostname, int serverPort) {
return new SwiftImpl(Networking.rpcBind(localPort, null), Networking.resolve(serverHostname, serverPort),
new InfiniteObjectsCache(), DEFAULT_TIMEOUT_MILLIS);
}
private static String generateClientId() {
final Random random = new Random(System.currentTimeMillis());
return Long.toHexString(System.identityHashCode(random) + random.nextLong());
}
private boolean stopFlag;
private boolean stopGracefully;
private final String clientId;
private final RpcEndpoint localEndpoint;
private final Endpoint serverEndpoint;
private final CommitterThread committerThread;
// Cache of objects.
// Invariant: if object is in the cache, it must include all updates
// of locally and globally committed locally-originating transactions.
private final InfiniteObjectsCache objectsCache;
// Invariant: committedVersion only grows.
private final CausalityClock commitedVersion;
// Invariant: there is at most one pending (open) transaction.
private AbstractTxnHandle pendingTxn;
// Locally committed transactions (in commit order), the first one is
// possibly committing to the store.
private final LinkedList<AbstractTxnHandle> locallyCommittedTxnsQueue;
// Local dependencies of a pending transaction.
private final LinkedList<AbstractTxnHandle> pendingTxnLocalDependencies;
private final Map<CRDTIdentifier, ObjectUpdatesSubscription> subscribedObjectsAccesses;
private final NotoficationsProcessorThread notificationsThread;
private IncrementalTimestampGenerator clientTimestampGenerator;
private final int timeoutMillis;
SwiftImpl(final RpcEndpoint localEndpoint, final Endpoint serverEndpoint, InfiniteObjectsCache objectsCache,
int timeoutMillis) {
this.clientId = generateClientId();
this.timeoutMillis = timeoutMillis;
this.localEndpoint = localEndpoint;
this.serverEndpoint = serverEndpoint;
this.objectsCache = objectsCache;
this.locallyCommittedTxnsQueue = new LinkedList<AbstractTxnHandle>();
this.pendingTxnLocalDependencies = new LinkedList<AbstractTxnHandle>();
this.commitedVersion = ClockFactory.newClock();
this.clientTimestampGenerator = new IncrementalTimestampGenerator(CLIENT_CLOCK_ID);
this.committerThread = new CommitterThread();
this.committerThread.start();
this.subscribedObjectsAccesses = new HashMap<CRDTIdentifier, ObjectUpdatesSubscription>();
this.notificationsThread = new NotoficationsProcessorThread();
this.notificationsThread.start();
}
@Override
public void stop(boolean waitForCommit) {
synchronized (this) {
stopFlag = true;
stopGracefully = waitForCommit;
this.notifyAll();
}
try {
committerThread.join();
notificationsThread.join();
} catch (InterruptedException e) {
logger.warning(e.getMessage());
}
}
@Override
public synchronized AbstractTxnHandle beginTxn(IsolationLevel isolationLevel, CachePolicy cachePolicy,
boolean readOnly) throws NetworkException {
// FIXME: Ooops, readOnly is present here at API level, respect it here
// and in TxnHandleImpl or remove it from API.
assertNoPendingTransaction();
assertRunning();
switch (isolationLevel) {
case SNAPSHOT_ISOLATION:
if (cachePolicy == CachePolicy.MOST_RECENT || cachePolicy == CachePolicy.STRICTLY_MOST_RECENT) {
final AtomicBoolean doneFlag = new AtomicBoolean(false);
localEndpoint.send(serverEndpoint, new LatestKnownClockRequest(clientId),
new LatestKnownClockReplyHandler() {
@Override
public void onReceive(RpcConnection conn, LatestKnownClockReply reply) {
updateCommittedVersion(reply.getClock());
doneFlag.set(true);
}
}, timeoutMillis);
if (!doneFlag.get() && cachePolicy == CachePolicy.STRICTLY_MOST_RECENT) {
throw new NetworkException("timed out to get transcation snapshot point");
}
}
final Timestamp localTimestmap = clientTimestampGenerator.generateNew();
// Invariant: for SI snapshotClock of a new transaction dominates
// clock of all previous SI transaction (monotonic reads), since
// commitedVersion only grows.
final CausalityClock snapshotClock = commitedVersion.clone();
setPendingTxn(new SnapshotIsolationTxnHandle(this, cachePolicy, localTimestmap, snapshotClock));
logger.info("SI transaction " + localTimestmap + " started with global snapshot point: " + snapshotClock);
return pendingTxn;
default:
// FIXME: implement other isolation levels.
throw new UnsupportedOperationException("isolation level " + isolationLevel + " unsupported");
}
}
private synchronized void updateCommittedVersion(final CausalityClock clock) {
if (clock == null) {
logger.warning("server returned null clock");
return;
}
commitedVersion.merge(clock);
final AbstractTxnHandle commitingTxn = locallyCommittedTxnsQueue.peekFirst();
if (commitingTxn != null && clock.includes(commitingTxn.getGlobalTimestamp())) {
// We observe global visibility (and possibly updates) of locally
// committed transaction before the CommitUpdatesReply has been
// received.
applyGloballyCommittedTxn(commitingTxn);
}
}
@Override
public synchronized <V extends CRDT<V>> TxnLocalCRDT<V> getObjectTxnView(AbstractTxnHandle txn, CRDTIdentifier id,
CausalityClock minVersion, final boolean tryMoreRecent, boolean create, Class<V> classOfV,
final ObjectUpdatesListener updatesListener) throws WrongTypeException, NoSuchObjectException,
VersionNotFoundException, NetworkException {
assertPendingTransaction(txn);
if (minVersion.hasEventFrom(CLIENT_CLOCK_ID)) {
throw new IllegalArgumentException("transaction requested visibility of local transaction");
}
// FIXME honor tryMoreRecent and check with commitedVersion
TxnLocalCRDT<V> localView = getCachedObjectForTxn(id, minVersion, classOfV);
if (localView != null) {
return localView;
}
// FIXME: support updatesListener for real
final CausalityClock clock = clockWithLocalDependencies(minVersion);
clock.drop(CLIENT_CLOCK_ID);
fetchLatestObject(id, create, classOfV, clock, updatesListener != null);
localView = getCachedObjectForTxn(id, minVersion, classOfV);
if (localView == null) {
throw new IllegalStateException(
"Internal error: just retrieved object unavailable in appropriate version in the cache");
}
return localView;
}
private CausalityClock clockWithLocalDependencies(CausalityClock clock) {
clock = clock.clone();
for (final AbstractTxnHandle dependentTxn : pendingTxnLocalDependencies) {
// Include in clock those dependent transactions that already
// committed globally after the pending transaction started.
if (dependentTxn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
clock.record(dependentTxn.getGlobalTimestamp());
} else {
clock.record(dependentTxn.getLocalTimestamp());
}
}
return clock;
}
@SuppressWarnings("unchecked")
private synchronized <V extends CRDT<V>> TxnLocalCRDT<V> getCachedObjectForTxn(CRDTIdentifier id,
CausalityClock clock, Class<V> classOfV) throws WrongTypeException, VersionNotFoundException {
V crdt;
try {
crdt = (V) objectsCache.get(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
if (crdt == null) {
return null;
}
if (clock == null) {
// Return the most recent version.
clock = crdt.getClock();
}
clock = clockWithLocalDependencies(clock);
final CausalityClock globalClock = clock.clone();
globalClock.drop(CLIENT_CLOCK_ID);
final CMP_CLOCK clockCmp = crdt.getClock().compareTo(globalClock);
if (clockCmp == CMP_CLOCK.CMP_CONCURRENT || clockCmp == CMP_CLOCK.CMP_ISDOMINATED) {
return null;
}
final CMP_CLOCK pruneCmp = globalClock.compareTo(crdt.getPruneClock());
if (pruneCmp == CMP_CLOCK.CMP_ISDOMINATED || pruneCmp == CMP_CLOCK.CMP_CONCURRENT) {
throw new VersionNotFoundException("version consistent with current snapshot is not available in the store");
// TODO: Or just in the cache? return to it if server returns pruned
// crdt.
}
final TxnLocalCRDT<V> crdtView;
// Are there any local dependencies to apply on the cached object?
if (clock.hasEventFrom(CLIENT_CLOCK_ID)) {
// Apply them on sandboxed copy of an object, since these operations
// use local timestamps.
final V crdtCopy = crdt.copy();
for (final AbstractTxnHandle dependentTxn : pendingTxnLocalDependencies) {
final CRDTObjectOperationsGroup<V> localOps;
try {
localOps = (CRDTObjectOperationsGroup<V>) dependentTxn.getObjectLocalOperations(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
if (localOps != null) {
crdtCopy.execute(localOps, CRDTOperationDependencyPolicy.IGNORE);
}
}
crdtView = crdtCopy.getTxnLocalCopy(clock, pendingTxn);
} else {
crdtView = crdt.getTxnLocalCopy(clock, pendingTxn);
}
return crdtView;
}
private <V extends CRDT<V>> void fetchLatestObject(CRDTIdentifier id, boolean create, Class<V> classOfV,
CausalityClock minVersion, final boolean subscribeUpdates) throws WrongTypeException,
NoSuchObjectException, VersionNotFoundException, NetworkException {
final V crdt;
synchronized (this) {
try {
crdt = (V) objectsCache.get(id);
} catch (ClassCastException x) {
throw new WrongTypeException(x.getMessage());
}
}
if (crdt == null) {
fetchLatestObjectFromScratch(id, create, classOfV, minVersion, subscribeUpdates);
} else {
fetchLatestObjectByRefresh(id, classOfV, crdt, minVersion, subscribeUpdates);
}
}
@SuppressWarnings("unchecked")
private <V extends CRDT<V>> V fetchLatestObjectFromScratch(CRDTIdentifier id, boolean create, Class<V> classOfV,
CausalityClock minVersion, boolean subscribeUpdates) throws NoSuchObjectException, WrongTypeException,
VersionNotFoundException, NetworkException {
final AtomicReference<FetchObjectVersionReply> replyRef = new AtomicReference<FetchObjectVersionReply>();
final SubscriptionType subscriptionType = subscribeUpdates ? SubscriptionType.UPDATES : SubscriptionType.NONE;
localEndpoint.send(serverEndpoint, new FetchObjectVersionRequest(clientId, id, minVersion, subscriptionType),
new FetchObjectVersionReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FetchObjectVersionReply reply) {
replyRef.set(reply);
}
}, timeoutMillis);
if (replyRef.get() == null) {
throw new NetworkException("Fetching object version timed out");
}
final FetchObjectVersionReply fetchReply = replyRef.get();
final V crdt;
final boolean presentInStore;
switch (fetchReply.getStatus()) {
case OBJECT_NOT_FOUND:
if (!create) {
throw new NoSuchObjectException("object " + id.toString() + " not found");
}
try {
crdt = classOfV.newInstance();
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
presentInStore = false;
break;
case VERSION_NOT_FOUND:
case OK:
try {
crdt = (V) fetchReply.getCrdt();
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
presentInStore = true;
break;
default:
throw new IllegalStateException("Unexpected status code" + fetchReply.getStatus());
}
crdt.init(id, fetchReply.getVersion(), fetchReply.getPruneClock(), presentInStore);
synchronized (this) {
final V concurrentlyCachedCRDT;
try {
concurrentlyCachedCRDT = (V) objectsCache.get(id);
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
if (concurrentlyCachedCRDT == null) {
objectsCache.add(crdt);
} else {
concurrentlyCachedCRDT.merge(crdt);
}
updateCommittedVersion(fetchReply.getEstimatedLatestKnownClock());
}
if (fetchReply.getStatus() == FetchStatus.VERSION_NOT_FOUND) {
// FIXME: retry if version <= minVerson?
throw new VersionNotFoundException("unexpected server reply - version not found in the store");
}
return crdt;
}
@SuppressWarnings("unchecked")
private <V extends CRDT<V>> void fetchLatestObjectByRefresh(CRDTIdentifier id, Class<V> classOfV, V cachedCrdt,
CausalityClock minVersion, boolean subscribeUpdates) throws NoSuchObjectException, WrongTypeException,
VersionNotFoundException, NetworkException {
final CausalityClock oldCrdtClock;
synchronized (this) {
oldCrdtClock = cachedCrdt.getClock().clone();
}
// WISHME: we should replace it with deltas or operations list
final AtomicReference<FetchObjectVersionReply> replyRef = new AtomicReference<FetchObjectVersionReply>();
final SubscriptionType subscriptionType = subscribeUpdates ? SubscriptionType.UPDATES : SubscriptionType.NONE;
localEndpoint.send(serverEndpoint, new FetchObjectDeltaRequest(clientId, id, oldCrdtClock, minVersion,
subscriptionType), new FetchObjectVersionReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FetchObjectVersionReply reply) {
replyRef.set(reply);
}
}, timeoutMillis);
if (replyRef.get() == null) {
throw new NetworkException("Fetching newer object version timed out");
}
synchronized (this) {
try {
cachedCrdt = (V) objectsCache.get(id);
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
final FetchObjectVersionReply refreshReply = replyRef.get();
switch (refreshReply.getStatus()) {
case OBJECT_NOT_FOUND:
// Just update the clock of local version.
cachedCrdt.getClock().merge(refreshReply.getVersion());
break;
case VERSION_NOT_FOUND:
case OK:
// Merge it with the local version.
V crdt;
try {
crdt = (V) refreshReply.getCrdt();
} catch (Exception e) {
throw new WrongTypeException(e.getMessage());
}
crdt.init(id, refreshReply.getVersion(), refreshReply.getPruneClock(), true);
cachedCrdt.merge(crdt);
break;
default:
throw new IllegalStateException("Unexpected status code" + refreshReply.getStatus());
}
updateCommittedVersion(refreshReply.getEstimatedLatestKnownClock());
}
}
private void applyObjectUpdates(final CRDTIdentifier id, final CausalityClock dependencyClock,
final List<CRDTObjectOperationsGroup<?>> ops, final CausalityClock outputClock) {
final CRDT crdt;
final CMP_CLOCK clkCmp;
synchronized (this) {
crdt = objectsCache.get(id);
clkCmp = crdt.getClock().compareTo(dependencyClock);
}
if (clkCmp == CMP_CLOCK.CMP_ISDOMINATED || clkCmp == CMP_CLOCK.CMP_CONCURRENT) {
// Ooops, we missed some update or messages were ordered.
logger.warning("cannot apply updates on object " + id + " due to unsatisfied dependencies");
// FIXME trigger fetch() and then applyObjectUpdates()
return;
}
synchronized (this) {
for (final CRDTObjectOperationsGroup<?> op : ops) {
crdt.execute(op, CRDTOperationDependencyPolicy.RECORD_BLINDLY);
}
crdt.getClock().merge(outputClock);
}
}
@Override
public synchronized void discardTxn(AbstractTxnHandle txn) {
assertPendingTransaction(txn);
setPendingTxn(null);
}
@Override
public synchronized void commitTxn(AbstractTxnHandle txn) {
assertPendingTransaction(txn);
assertRunning();
// Big WISHME: write disk log and allow local recovery.
txn.markLocallyCommitted();
logger.info("transaction " + txn.getLocalTimestamp() + " commited locally");
if (txn.isReadOnly()) {
// Read-only transaction can be immediately discarded.
txn.markGloballyCommitted();
logger.info("read-only transaction " + txn.getLocalTimestamp() + " (virtually) commited globally");
} else {
for (final AbstractTxnHandle dependeeTxn : pendingTxnLocalDependencies) {
// Replace timestamps of transactions that globally committed
// when this transaction was pending.
if (dependeeTxn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
txn.includeGlobalDependency(dependeeTxn.getLocalTimestamp(), dependeeTxn.getGlobalTimestamp());
}
}
// Update transaction is queued up for global commit.
addLocallyCommittedTransaction(txn);
}
setPendingTxn(null);
}
private void addLocallyCommittedTransaction(AbstractTxnHandle txn) {
locallyCommittedTxnsQueue.addLast(txn);
// Notify committer thread.
this.notifyAll();
}
/**
* Stubborn commit procedure, tries to get a global timestamp for a
* transaction and commit using this timestamp. Repeats until it succeeds.
*
* @param txn
* locally committed transaction
*/
private void commitToStore(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL);
if (txn.getUpdatesDependencyClock().hasEventFrom(CLIENT_CLOCK_ID)) {
throw new IllegalStateException("Trying to commit to data store with client clock");
}
final AtomicReference<CommitUpdatesReply> commitReplyRef = new AtomicReference<CommitUpdatesReply>();
do {
requestTxnGlobalTimestamp(txn);
final LinkedList<CRDTObjectOperationsGroup<?>> operationsGroups = new LinkedList<CRDTObjectOperationsGroup<?>>(
txn.getAllGlobalOperations());
// Commit at server.
do {
localEndpoint.send(serverEndpoint, new CommitUpdatesRequest(clientId, txn.getGlobalTimestamp(),
operationsGroups), new CommitUpdatesReplyHandler() {
@Override
public void onReceive(RpcConnection conn, CommitUpdatesReply reply) {
commitReplyRef.set(reply);
}
}, timeoutMillis);
} while (commitReplyRef.get() == null);
} while (commitReplyRef.get().getStatus() == CommitStatus.INVALID_TIMESTAMP);
if (commitReplyRef.get().getStatus() == CommitStatus.ALREADY_COMMITTED) {
// FIXME Perhaps we could move this complexity to RequestTimestamp
// on server side?
throw new UnsupportedOperationException("transaction committed under another timestamp");
}
logger.info("transaction " + txn.getLocalTimestamp() + " commited globally as " + txn.getGlobalTimestamp());
}
/**
* Requests and assigns a new global timestamp for the transaction.
*
* @param txn
* locally committed transaction
*/
private void requestTxnGlobalTimestamp(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL);
final AtomicReference<GenerateTimestampReply> timestampReplyRef = new AtomicReference<GenerateTimestampReply>();
do {
localEndpoint.send(serverEndpoint, new GenerateTimestampRequest(clientId, txn.getUpdatesDependencyClock(),
txn.getGlobalTimestamp()), new GenerateTimestampReplyHandler() {
@Override
public void onReceive(RpcConnection conn, GenerateTimestampReply reply) {
timestampReplyRef.set(reply);
}
}, timeoutMillis);
} while (timestampReplyRef.get() == null);
// And replace old timestamp in operations with timestamp from server.
txn.setGlobalTimestamp(timestampReplyRef.get().getTimestamp());
}
/**
* Applies globally committed transaction locally using a global timestamp.
*
* @param txn
* globally committed transaction to apply locally
*/
private synchronized void applyGloballyCommittedTxn(AbstractTxnHandle txn) {
txn.assertStatus(TxnStatus.COMMITTED_LOCAL, TxnStatus.COMMITTED_GLOBAL);
if (txn.getStatus() == TxnStatus.COMMITTED_GLOBAL) {
return;
}
txn.markGloballyCommitted();
for (final CRDTObjectOperationsGroup opsGroup : txn.getAllGlobalOperations()) {
// Try to apply changes in a cached copy of an object.
final CRDT<?> crdt = objectsCache.get(opsGroup.getTargetUID());
if (crdt == null) {
logger.warning("object evicted from the local cache before global commit");
} else {
crdt.execute(opsGroup, CRDTOperationDependencyPolicy.IGNORE);
}
}
for (final AbstractTxnHandle dependingTxn : locallyCommittedTxnsQueue) {
if (dependingTxn != txn) {
dependingTxn.includeGlobalDependency(txn.getLocalTimestamp(), txn.getGlobalTimestamp());
}
// pendingTxn will map timestamp later inside commitToStore().
// TODO [tricky]: to implement IsolationLevel.READ_COMMITTED we may
// need
// to replace timestamps in pending transaction too.
}
commitedVersion.record(txn.getGlobalTimestamp());
}
private synchronized AbstractTxnHandle getNextLocallyCommittedTxnBlocking() {
while (locallyCommittedTxnsQueue.isEmpty() && !stopFlag) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
return locallyCommittedTxnsQueue.peekFirst();
}
private synchronized void setPendingTxn(final AbstractTxnHandle txn) {
pendingTxn = txn;
pendingTxnLocalDependencies.clear();
if (txn != null) {
pendingTxnLocalDependencies.addAll(locallyCommittedTxnsQueue);
}
}
private void assertNoPendingTransaction() {
if (pendingTxn != null) {
throw new IllegalStateException("Only one transaction can be executing at the time");
}
}
private void assertPendingTransaction(final AbstractTxnHandle expectedTxn) {
if (!pendingTxn.equals(expectedTxn)) {
throw new IllegalStateException(
"Corrupted state: unexpected transaction is bothering me, not the pending one");
}
}
private void assertRunning() {
if (stopFlag) {
throw new IllegalStateException("client is stopped");
}
}
/**
* Thread continuously committing locally committed transactions. The thread
* takes the oldest locally committed transaction one by one, tries to
* commit it to the store and applies to it to local cache and depender
* transactions.
*/
private class CommitterThread extends Thread {
public CommitterThread() {
super("SwiftTransactionCommitterThread");
}
@Override
public void run() {
while (true) {
final AbstractTxnHandle nextToCommit = getNextLocallyCommittedTxnBlocking();
if (stopFlag && (!stopGracefully || nextToCommit == null)) {
return;
}
commitToStore(nextToCommit);
applyGloballyCommittedTxn(nextToCommit);
// Clean up after nextToCommit.
if (locallyCommittedTxnsQueue.removeFirst() != nextToCommit) {
throw new IllegalStateException("internal error, concurrently commiting transactions?");
}
}
}
}
private class NotoficationsProcessorThread extends Thread {
public NotoficationsProcessorThread() {
super("SwiftNotificationsProcessorThread");
}
@Override
public void run() {
// FIXME: this is just to test the server!!
while (true) {
synchronized (SwiftImpl.this) {
if (stopFlag) {
return;
}
}
localEndpoint.send(serverEndpoint, new FastRecentUpdatesRequest(clientId),
new FastRecentUpdatesReplyHandler() {
@Override
public void onReceive(RpcConnection conn, FastRecentUpdatesReply reply) {
logger.fine("notifications received for " + reply.getSubscriptions().size()
+ " objects");
updateCommittedVersion(reply.getEstimatedLatestKnownClock());
if (reply.getStatus() == SubscriptionStatus.ACTIVE) {
for (final ObjectSubscriptionInfo subscriptionInfo : reply.getSubscriptions()) {
if (subscriptionInfo.isDirty() && subscriptionInfo.getUpdates().isEmpty()) {
// FIXME
logger.warning("unexpected server notification information without update");
} else {
applyObjectUpdates(subscriptionInfo.getId(),
subscriptionInfo.getOldClock(), subscriptionInfo.getUpdates(),
subscriptionInfo.getNewClock());
}
}
} else {
// FIXME: renew subscriptions
}
}
}, timeoutMillis);
// FIXME: wait?
// FIXME: GC of subscriptions
// FIXME: real notifications to the client
}
}
}
private static class ObjectUpdatesSubscription {
private CausalityClock versionRead;
private boolean notified;
private AbstractTxnHandle txn;
private TxnLocalCRDT<?> crdtView;
public ObjectUpdatesSubscription(CausalityClock version, AbstractTxnHandle txn, TxnLocalCRDT<?> crdtView) {
this.versionRead = version;
this.txn = txn;
this.crdtView = crdtView;
this.notified = false;
}
}
}
|
SwiftImpl: notifications - continued
git-svn-id: a3fb842d882947c797cf684233f17bdc7f2c8277@465 049c2a90-bdf1-4f83-8191-3719d539f8e0
|
src/swift/client/SwiftImpl.java
|
SwiftImpl: notifications - continued
|
|
Java
|
apache-2.0
|
3205f21387d579264004728255806eee1fc0bab4
| 0
|
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
|
package org.opensingular.form.wicket.mapper.selection;
import com.google.common.collect.Lists;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.opensingular.form.RefService;
import org.opensingular.form.SIComposite;
import org.opensingular.form.SInstance;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.document.SDocument;
import org.opensingular.form.provider.SimpleProvider;
import org.opensingular.form.type.core.SIString;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.wicket.helpers.SingularFormBaseTest;
import java.util.List;
import java.util.stream.Collectors;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.opensingular.form.wicket.helpers.TestFinders.findTag;
@Ignore("We have to figure out how to deal with this case of TypeAhead")
@RunWith(Enclosed.class)
public class STypeStringSelectionFromProviderFieldTest {
@Ignore("We have to figure out how to deal with this case of TypeAhead")
public static class Base extends SingularFormBaseTest {
protected List<String> referenceOptions = Lists.newArrayList("strawberry", "apple", "orange", "banana", "avocado", "grapes");
protected STypeString selectType;
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
selectType = baseType.addFieldString("favoriteFruit");
}
protected SimpleProvider createProviderWithOptions(final List<String> options) {
return (SimpleProvider<String, SInstance>) ins -> options;
}
protected Object getSelectKeyFromValue(String value) {
SIString mvalue = selectType.newInstance();
mvalue.setValue(value);
return page.getCurrentInstance().getField("favoriteFruit").asAtrProvider().getIdFunction().apply(value);
}
List<?> getReferenceOptionsKeys() {
return referenceOptions.stream().map(value -> getSelectKeyFromValue(value)).collect(Collectors.toList());
}
@Test
public void rendersAnDropDownWithSpecifiedOptionsByName() {
tester.assertEnabled(formField(form, "favoriteFruit"));
form.submit();
List<DropDownChoice> options = (List) findTag(form.getForm(), DropDownChoice.class);
assertThat(options).hasSize(1);
DropDownChoice choices = options.get(0);
assertThat(choices.getChoices())
.containsExactly(getReferenceOptionsKeys().toArray());
}
}
public static class WithSpecifiedProviderBindedByName extends Base {
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
super.buildBaseType(baseType);
selectType.withSelectionFromProvider("fruitProvider");
}
@Override
protected void populateInstance(SIComposite instance) {
SimpleProvider provider = createProviderWithOptions(referenceOptions);
SDocument document = instance.getDocument();
document.bindLocalService("fruitProvider", SimpleProvider.class, RefService.of(provider));
}
}
public static class WithSpecifiedProviderBindedByType extends Base {
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
super.buildBaseType(baseType);
selectType.withSelectionFromProvider(SimpleProvider.class);
}
@Override
protected void populateInstance(SIComposite instance) {
SimpleProvider provider = createProviderWithOptions(referenceOptions);
SDocument document = instance.getDocument();
document.bindLocalService(SimpleProvider.class, RefService.of(provider));
}
}
}
|
form/wicket/src/test/java/org/opensingular/form/wicket/mapper/selection/STypeStringSelectionFromProviderFieldTest.java
|
package org.opensingular.form.wicket.mapper.selection;
import org.opensingular.form.RefService;
import org.opensingular.form.SIComposite;
import org.opensingular.form.SInstance;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.document.SDocument;
import org.opensingular.form.provider.SimpleProvider;
import org.opensingular.form.type.core.SIString;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.wicket.helpers.SingularFormBaseTest;
import com.google.common.collect.Lists;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.stream.Collectors;
import static org.opensingular.form.wicket.helpers.TestFinders.findTag;
import static org.fest.assertions.api.Assertions.assertThat;
@Ignore("We have to figure out how to deal with this case of TypeAhead")
@RunWith(Enclosed.class)
public class STypeStringSelectionFromProviderFieldTest {
private static class Base extends SingularFormBaseTest {
protected List<String> referenceOptions = Lists.newArrayList("strawberry", "apple", "orange", "banana", "avocado", "grapes");
protected STypeString selectType;
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
selectType = baseType.addFieldString("favoriteFruit");
}
protected SimpleProvider createProviderWithOptions(final List<String> options) {
return (SimpleProvider<String, SInstance>) ins -> options;
}
protected Object getSelectKeyFromValue(String value) {
SIString mvalue = selectType.newInstance();
mvalue.setValue(value);
return page.getCurrentInstance().getField("favoriteFruit").asAtrProvider().getIdFunction().apply(value);
}
List<?> getReferenceOptionsKeys() {
return referenceOptions.stream().map(value -> getSelectKeyFromValue(value)).collect(Collectors.toList());
}
@Test
public void rendersAnDropDownWithSpecifiedOptionsByName() {
tester.assertEnabled(formField(form, "favoriteFruit"));
form.submit();
List<DropDownChoice> options = (List) findTag(form.getForm(), DropDownChoice.class);
assertThat(options).hasSize(1);
DropDownChoice choices = options.get(0);
assertThat(choices.getChoices())
.containsExactly(getReferenceOptionsKeys().toArray());
}
}
public static class WithSpecifiedProviderBindedByName extends Base {
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
super.buildBaseType(baseType);
selectType.withSelectionFromProvider("fruitProvider");
}
@Override
protected void populateInstance(SIComposite instance) {
SimpleProvider provider = createProviderWithOptions(referenceOptions);
SDocument document = instance.getDocument();
document.bindLocalService("fruitProvider", SimpleProvider.class, RefService.of(provider));
}
}
public static class WithSpecifiedProviderBindedByType extends Base {
@Override
protected void buildBaseType(STypeComposite<?> baseType) {
super.buildBaseType(baseType);
selectType.withSelectionFromProvider(SimpleProvider.class);
}
@Override
protected void populateInstance(SIComposite instance) {
SimpleProvider provider = createProviderWithOptions(referenceOptions);
SDocument document = instance.getDocument();
document.bindLocalService(SimpleProvider.class, RefService.of(provider));
}
}
}
|
[SONAR] Ajustes do Sonar
|
form/wicket/src/test/java/org/opensingular/form/wicket/mapper/selection/STypeStringSelectionFromProviderFieldTest.java
|
[SONAR] Ajustes do Sonar
|
|
Java
|
apache-2.0
|
48715013ebbe22b2b3386902b8570fd54711fa89
| 0
|
smgoller/geode,PurelyApplied/geode,PurelyApplied/geode,smgoller/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,PurelyApplied/geode,masaki-yamakawa/geode,smgoller/geode,smgoller/geode,PurelyApplied/geode,jdeppe-pivotal/geode,davebarnes97/geode,smgoller/geode,smgoller/geode,davebarnes97/geode,PurelyApplied/geode,davinash/geode,jdeppe-pivotal/geode,davebarnes97/geode,davebarnes97/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,davebarnes97/geode,davinash/geode,davinash/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,PurelyApplied/geode,davebarnes97/geode,PurelyApplied/geode,davinash/geode,davinash/geode,masaki-yamakawa/geode,davinash/geode,davebarnes97/geode,davinash/geode,masaki-yamakawa/geode
|
/*
* 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.geode.internal.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.apache.geode.LogWriter;
import org.apache.geode.cache.CacheWriter;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.EntryExistsException;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.PartitionedRegionStorageException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.RegionEvent;
import org.apache.geode.cache30.RegionTestCase;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.logging.LogService;
/**
* Test for Partitioned Region operations on a single node. Following tests are included:
* <P>
* (1) testPut() - Tests the put() functionality for the partitioned region.
* </P>
*
*
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PartitionedRegionSingleNodeOperationsJUnitTest {
private static final Logger logger = LogService.getLogger();
static DistributedSystem sys = null;
static int var = 1;
final String val = "string_value";
LogWriter logWriter = null;
@Before
public void setUp() throws Exception {
logWriter = PartitionedRegionTestHelper.getLogger();
}
@After
public void tearDown() {
PartitionedRegionTestHelper.closeCache();
}
/**
* This isa test for PartitionedRegion put() operation.
* <p>
* Following functionalities are tested:
* </p>
* <p>
* 1) put() on PR with localMaxMemory = 0. PartitionedRegionException expected.
* </p>
* <p>
* 2)test the put() operation and validate that old values are returned in case of PR with scope
* D_ACK.
* </p>
*
*
*/
@Test
public void test000Put() throws Exception {
String regionname = "testPut";
int localMaxMemory = 0;
System.setProperty(PartitionedRegion.RETRY_TIMEOUT_PROPERTY, "20000");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionname, String.valueOf(localMaxMemory), 0);
System.setProperty(PartitionedRegion.RETRY_TIMEOUT_PROPERTY,
Integer.toString(PartitionedRegionHelper.DEFAULT_TOTAL_WAIT_RETRY_ITERATION));
final String expectedExceptions = PartitionedRegionStorageException.class.getName();
logger.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.put(new Integer(1), val);
fail("testPut()- Expected PartitionedRegionException not thrown for localMaxMemory = 0");
} catch (PartitionedRegionStorageException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testPut() - Got a correct exception-PartitionedRegionStorageException for localMaxMemory=0 ");
}
}
logger.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
if (!pr.isDestroyed())
pr.destroyRegion();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionname,
String.valueOf(400), 0);
final int maxEntries = 3;
for (int num = 0; num < maxEntries; num++) {
final Integer key = new Integer(num);
final Object oldVal = pr.put(key, this.val);
// Assert a more generic return value here because the bucket has not been allocated yet
// thus do not know if the value is local or not
assertTrue(oldVal == null);
assertEquals(this.val, pr.get(key));
final Region.Entry entry = pr.getEntry(key);
assertNotNull(entry);
assertEquals(this.val, entry.getValue());
assertTrue(pr.values().contains(this.val));
if (RegionTestCase.entryIsLocal(entry)) {
assertEquals("Failed for key " + num, this.val, pr.put(key, key));
} else {
assertEquals("Failed for key " + num, null, pr.put(key, key));
}
assertEquals((num + 1) * 2, ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getPuts());
}
if (!pr.isDestroyed())
pr.destroyRegion();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionname,
String.valueOf(400), 0);
for (int num = 0; num < maxEntries; num++) {
pr.put(new Integer(num), this.val);
Object retval = pr.get(new Integer(num));
assertEquals(this.val, retval);
}
for (int num = 0; num < maxEntries; num++) {
if (RegionTestCase.entryIsLocal(pr.getEntry(new Integer(num)))) {
assertEquals(this.val, pr.put(new Integer(num), this.val));
} else {
assertEquals(null, pr.put(new Integer(num), this.val));
}
}
final Object dummyVal = "DummyVal";
for (int num = 0; num < maxEntries; num++) {
final Object getObj = pr.get(new Integer(num));
final Object oldPut = pr.put(new Integer(num), dummyVal);
if (((EntrySnapshot) pr.getEntry(new Integer(num))).wasInitiallyLocal()) {
assertEquals("Returned value from put operation is not same as the old value", getObj,
oldPut);
} else {
assertEquals(null, oldPut);
}
assertEquals("testPut()- error in putting the value in the Partitioned Region", dummyVal,
pr.get(new Integer(num)));
}
}
/**
* This is a test for PartitionedRegion destroy(key) operation.
*
*/
@Test
public void test001Destroy() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testDestroy", String.valueOf(200), 0);
final String expectedExceptions = EntryNotFoundException.class.getName();
final String addExpected =
"<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>";
final String removeExpected =
"<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>";
logger.info(addExpected);
for (int num = 0; num < 3; num++) {
try {
pr.destroy(new Integer(num));
fail(
"Destroy doesn't throw EntryNotFoundException for the entry which never existed in the system");
} catch (EntryNotFoundException expected) {
}
}
logger.info(removeExpected);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
final int initialDestroyCount = getDestroyCount(pr);
pr.destroy(new Integer(num));
assertEquals(initialDestroyCount + 1, getDestroyCount(pr));
}
for (int num = 0; num < 3; num++) {
Object retval = pr.get(new Integer(num));
if (retval != null)
fail("testDestroy()- entry not destroyed properly in destroy(key)");
}
logger.info(addExpected);
for (int num = 0; num < 3; num++) {
try {
pr.destroy(new Integer(num));
fail(
"Destroy doesn't throw EntryNotFoundException for the entry which is already deleted from the system");
} catch (EntryNotFoundException enf) {
}
}
logger.info(removeExpected);
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testDestroy() Completed successfully ... ");
}
}
private int getDestroyCount(PartitionedRegion pr) {
return ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getDestroys();
}
private int getCreateCount(PartitionedRegion pr) {
return ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getCreates();
}
/**
* This is a test for PartitionedRegion get(key) operation.
*
*/
@Test
public void test002Get() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGet", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
Object retval = pr.get(new Integer(num));
if (!val.equals(String.valueOf(retval))) {
fail("testGet() - get operation failed for Partitioned Region ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGet() Completed successfully ... ");
}
}
/**
* This is a test for PartitionedRegion destroyRegion() operation.
*/
@Test
public void test003DestroyRegion() throws Exception {
String regionName = "testDestroyRegion";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
pr.put(new Integer(1), new Integer(1));
pr.get(new Integer(1));
if (pr.isDestroyed()) {
fail(
"PartitionedRegionSingleNodeOperationsJUnitTest:testDestroyRegion(): Returns true in isDestroyed method, before the region is destroyed");
}
logWriter.info("JDEBUG 1");
pr.destroyRegion();
logWriter.info("JDEBUG 2");
// Validate that the meta-data and bucket regions are cleaned.
assertTrue(pr.isDestroyed());
// assertTrue(pr.getBucket2Node().isEmpty());
Region root = PartitionedRegionHelper.getPRRoot(PartitionedRegionTestHelper.createCache());
// assertNull(PartitionedRegionHelper.getPRConfigRegion(root,
// PartitionedRegionTestHelper.createCache()).get(regionName));
java.util.Iterator regItr = root.subregions(false).iterator();
while (regItr.hasNext()) {
Region rg = (Region) regItr.next();
// System.out.println("Region = " + rg.getName());
assertEquals(
rg.getName().indexOf(PartitionedRegionHelper.BUCKET_REGION_PREFIX + pr.getPRId() + "_"),
-1);
}
if (!pr.isDestroyed()) {
fail("testDestroyRegion(): "
+ "Returns false in isDestroyed method, after the region is destroyed");
}
logWriter.info("JDEBUG 3");
try {
pr.put(new Integer(2), new Integer(2));
fail("testdestroyRegion() Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testDestroyRegion() got a corect RegionDestroyedException for put() after destroyRegion()");
}
}
logWriter.info("JDEBUG 4");
try {
pr.get(new Integer(2));
fail("testdestroyRegion() - Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - "
+ "testDestroyRegion() got a correct RegionDestroyedException for get() after destroyRegion()");
}
}
logWriter.info("JDEBUG 5");
try {
pr.destroy(new Integer(1));
fail("testdestroyRegion() Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - "
+ "testDestroyRegion() got a correct RegionDestroyedException for destroy() after destroyRegion()");
}
}
logWriter.info("JDEBUG 6");
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionName,
String.valueOf(200), 0);
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - testDestroyRegion():"
+ " PartitionedRegion with same name as the destroyed region, can be created.");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testDestroyRegion(): Completed Successfully ...");
}
}
/**
* Tests getCache() API of PR. This should return same value as the cache used.
*
*/
@Test
public void test004GetCache() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetCache", String.valueOf(200), 0);
GemFireCacheImpl ca = (GemFireCacheImpl) pr.getCache();
if (!PartitionedRegionTestHelper.createCache().equals(ca)) {
fail("testGetCache() - getCache method is not returning proper cache handle");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetCache() Completed Successfully");
}
}
/**
* Tests getFullPath() API of PartitionedRegion.
*
*/
@Test
public void test005GetFullPath() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetFullPath", String.valueOf(200), 0);
String fullPath = pr.getFullPath();
if (!(Region.SEPARATOR + "testGetFullPath").equals(fullPath)) {
fail("testGetFullPath() - getFullPath method is not returning proper fullPath");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetFullPath() Completed Successfully");
}
}
/**
* Tests getParentRegion() API of PR. This should return null as PR doesnt have a parentRegion
*
*/
@Test
public void test006GetParentRegion() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetParentRegion", String.valueOf(200), 0);
Region parentRegion = pr.getParentRegion();
if (parentRegion != null) {
fail("getParentRegion method is not returning null as parent region for a PartitionedRegion");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetParentRegion() Completed Successfully");
}
}
/**
* Tests getName() API of PR. Name returned should be same as the one used to create PR.
*
*/
@Test
public void test007GetName() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetName", String.valueOf(200), 0);
String name = pr.getName();
if (!("testGetName").equals(name)) {
fail("getName() method is not returning proper region name");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetName() Completed Successfully");
}
}
/**
* This method validates containsKey() operations.
*/
@Test
public void test008ContainsKey() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testContainsKey", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
boolean retval = pr.containsKey(new Integer(num));
if (!retval) {
fail("PartitionedRegionSingleNodeOperationTest:testContainsKey() operation failed");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testContainsKey() Completed successfully ... ");
}
}
/**
* This method validates containsKey() operations.
*/
@Test
public void test009ContainsValueForKey() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testContainsValueForKey", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
boolean retval = pr.containsValueForKey(new Integer(num));
if (!retval) {
fail(
"PartitionedRegionSingleNodeOperationTest:testContainsValueForKey() operation failed");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testContainsValueForKey() Completed successfully ... ");
}
}
/**
* Tests close() API of PR. It should close the accessor and delete the data-store and related
* meta-data information.
*
*/
@Test
public void test010Close() throws Exception {
logWriter.fine("Getting inside testClose method");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testClose", String.valueOf(200), 0);
pr.put("K1", "V1");
pr.get("K1");
pr.close();
if (!pr.isClosed || !pr.isDestroyed())
fail("testClose(): After close isClosed = " + pr.isClosed + " and isDestroyed = "
+ pr.isDestroyed());
try {
pr.put("K2", "V2");
fail("testClose(): put operation completed on a closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
}
// validating get operation
try {
pr.get("K1");
fail("testClose(): get operation should not succeed on closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
// if (logger.fineEnabled()) {
// logger.fine("Got correct RegionDestroyedException after close() ");
// }
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testClose() Completed successfully ... ");
}
}
/**
* Tests localDestroyRegion() API of PR. It should locallyDestroy the accessor, data store and
* meta-data.
*
*/
@Test
public void test011LocalDestroyRegion() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testClose", String.valueOf(200), 0);
pr.put("K1", "V1");
pr.get("K1");
pr.localDestroyRegion();
if (pr.isClosed || !pr.isDestroyed())
fail("testClose(): After close isClosed = " + pr.isClosed + " and isDestroyed = "
+ pr.isDestroyed());
try {
pr.put("K2", "V2");
fail("testClose(): put operation completed on a closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
}
try {
pr.get("K1");
fail("testClose(): get operation should not succeed on closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
if (logWriter.fineEnabled()) {
logWriter.fine("Got correct RegionDestroyedException after close() ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testClose() Completed successfully ... ");
}
}
/**
* This method is used to test the isDestroyed() functionality.
*
*/
@Test
public void test012IsDestroyed() throws Exception {
String regionName = "testIsDestroyed";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
pr.put(new Integer(1), new Integer(1));
pr.get(new Integer(1));
if (pr.isDestroyed()) {
fail(
"PartitionedRegionSingleNodeOperationsJUnitTest:testIsDestroyed(): Returns true in isDestroyed method, before the region is destroyed");
}
pr.destroyRegion();
if (!pr.isDestroyed()) {
fail("PartitionedRegionSingleNodeOperationsJUnitTest:testIsDestroyed(): "
+ "Returns false in isDestroyed method, after the region is destroyed");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsDestroyed() Completed successfully ... ");
}
}
/**
* This method validates that PR closed behavior matches that of local region closed behavior.
*
*/
/*
* public void xxNoTestValidateCloseFunction() throws Exception { String partitionRegionName =
* "testValidateCloseFunction"; PartitionedRegion pr =
* (PartitionedRegion)PartitionedRegionTestHelper .createPartitionedRegion(partitionRegionName,
* String.valueOf(200), 2, Scope.DISTRIBUTED_ACK); String diRegion = "diRegion";
*
* Region distRegion = null;
*
* AttributesFactory af = new AttributesFactory(); RegionAttributes regionAttributes; // setting
* property af.setScope(Scope.DISTRIBUTED_ACK); // creating region attributes regionAttributes =
* af.create(); try { distRegion = PartitionedRegionTestHelper.createCache().createRegion(
* diRegion, regionAttributes); } catch (RegionExistsException rex) { distRegion =
* PartitionedRegionTestHelper.createCache() .getRegion(diRegion); } // Closing the regions
* distRegion.close(); pr.close();
*
* if (!pr.getCache().equals(distRegion.getCache())) {
* fail("testValidateCloseFunction: getCache is not matching. "); } else { if
* (logger.fineEnabled()) { logger.fine("getCache() matched on closed PR and distributed region
* "); } } if (distRegion.getName().length() != pr.getName().length()) {
* fail("testValidateCloseFunction: getName behavior not matching. "); } else { if
* (logger.fineEnabled()) { logger.fine("getName) matched on closed PR and distributed region ");
* } }
*
* if (distRegion.getFullPath().length() != pr.getFullPath().length()) {
* fail("testValidateCloseFunction: getFullPath behavior not matching. "); } else { if
* (logger.fineEnabled()) { logger .fine("getFullPath) matched on closed PR and distributed region
* "); } }
*
* if (logger.fineEnabled()) { logger .fine("PartitionedRegionSingleNodeOperationsJUnitTest -
* testValidateCloseFunction() Completed successfully ... "); } }
*/
// /**
// * This method is used to test the entrySet method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestEntrySet() throws Exception
// {
// String regionName = "testEntrySet";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
//
// try {
// Set s = pr.entrySet(true);
// fail("testEntrySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testEntrySet() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Set s = pr.entrySet(true);
// fail("testEntrySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testEntrySet() is correctly throwing UnsupportedOperationException on a non-empty PR");
// }
// }
//
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testEntrySet() Completed successfully
// ... ");
// }
// }
/**
* Test either the keySet() or keys() methods, which logically are expected to be the same
*/
private void keysSetTester(Region pr) {
assertEquals(Collections.EMPTY_SET, pr.keySet());
pr.put(new Integer(1), "won");
pr.put(new Integer(2), "to");
pr.put(new Integer(3), "free");
pr.put(new Integer(5), "hive");
final Set ks = pr.keySet();
assertEquals(4, ks.size());
try {
ks.clear();
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.add("foo");
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.addAll(Arrays.asList(new String[] {"one", "two", "three"}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.remove("boom");
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.removeAll(Arrays.asList(new Integer[] {new Integer(1), new Integer(2)}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.retainAll(Arrays.asList(new Integer[] {new Integer(3), new Integer(5)}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
final Iterator ksI = ks.iterator();
for (int i = 0; i < 4; i++) {
try {
ksI.remove();
fail("Expected key set iterator to be read only");
} catch (Exception expected) {
}
assertTrue(ksI.hasNext());
Object key = ksI.next();
assertEquals(Integer.class, key.getClass());
}
try {
ksI.remove();
fail("Expected key set iterator to be read only");
} catch (Exception expected) {
}
try {
ksI.next();
fail("Expected no such element exception");
} catch (NoSuchElementException expected) {
}
}
@Test
public void test014KeySet() throws Exception {
String regionName = "testKeysSet";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
keysSetTester(pr);
}
// /**
// * This method is used to test the keySet method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestKeySet() throws Exception
// {
// String regionName = "testKeySet";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
//
// try {
// Set s = pr.keySet();
// fail("testKeySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testKeySet() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Set s = pr.keySet();
// fail("testKeySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine("testKeySet() is correctly throwing UnsupportedOperationException on a non-empty PR");
// }
// }
//
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testKeySet() Completed successfully ...
// ");
// }
// }
// /**
// * This method is used to test the putAll method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestPutAll() throws Exception
// {
// final String rName = "testPutAll";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(rName, String.valueOf(8), 0,
// Scope.DISTRIBUTED_ACK);
// try {
// assertNotNull(pr);
// final String foo = "foo";
// final String bing = "bing";
// final String supper = "super";
// HashMap data = new HashMap();
// data.put(foo, "bar");
// data.put(bing, "bam");
// data.put(supper, "hero");
//
// assertNull(pr.get(foo));
// assertNull(pr.get(bing));
// assertNull(pr.get(supper));
// try {
// pr.putAll(data);
// fail("testPutAll() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testPutall() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
// assertNull(pr.get(foo));
// assertNull(pr.get(bing));
// assertNull(pr.get(supper));
// }
// finally {
// pr.destroyRegion();
// }
// }
// /**
// * This method is used to test the values functionality. It verifies that it
// * throws UnsupportedOperationException.
// *
// */
// public void xxNoTestValues() throws Exception
// {
// String regionName = "testValues";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
// try {
// Collection c = pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testValues() correctly throwing UnsupportedOperationException on an empty PR ");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Collection c = pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine("testValues() is correctly throwing UnsupportedOperationException on a non-empty PR ");
// }
// }
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testValues() Completed successfully ...
// ");
// }
// }
// /**
// * This method validates containsKey operations. It verifies that it throws
// * UnsupportedOperationException.
// */
// public void xxNoTestContainsValue() throws Exception
// {
// int key = 0;
// Region pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion("testContainsValue", String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
// for (int num = 0; num < 3; num++) {
// key++;
// pr.put(new Integer(key), val);
// try {
// boolean retval = pr.containsValue(val);
// fail("PartitionedRegionSingleNodeOperationTest:testContainsValue() operation failed");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine(" testContainsValue is correctly throwing UnsupportedOperationException for value = "
// + val);
// }
// }
// }
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testContainsValue() Completed
// successfully ... ");
// }
// }
/**
* This method is used to test the setUserAttributes functionality. It verifies that it sets the
* UserAttributes on an open PR without throwing any exception. It also verifies that it throws
* RegionDestroyedException on a closed PR.
*
*/
@Test
public void test015SetUserAttributes() throws Exception {
String regionName = "testSetUserAttributes";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
String s = "DUMMY";
pr.setUserAttribute(s);
// Close PR
pr.close();
try {
pr.setUserAttribute(s);
fail(
"testSetUserAttributes() doesnt throw RegionDestroyedException on a closed PartitionedRegion.");
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testSetUserAttributes(): setUserAttributes() throws RegionDestroyedException on a closed PartitionedRegion. ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSetUserAttributes() Completed successfully ... ");
}
}
/**
* This method is used to test the getUserAttributes functionality. It verifies that it gets the
* UserAttributes on an open PR without throwing any exception. It also verifies that it throws
* RegionDestroyedException on a closed PR.
*
*/
@Test
public void test016GetUserAttributes() throws Exception {
String regionName = "testGetUserAttributes";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
String s = "DUMMY";
pr.setUserAttribute(s);
Object o = pr.getUserAttribute();
if (!o.equals(s)) {
fail("testGetUserAttributes() returns null on an open accessor");
}
// Close PR
pr.close();
assertEquals(s, pr.getUserAttribute());
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetUserAttributes() Completed successfully ... ");
}
}
/**
* This method is used to test the getAttributesMutator functionality. It verifies that it gets
* the handle for attributes mutator on an open PR without throwing any exception. It also
* verifies that it throws RegionDestroyedException on a closed PR.
*
*/
@Test
public void test017GetAttributesMutator() throws Exception {
String regionName = "testGetAttributesMutator";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
Object o = pr.getAttributesMutator();
if (o == null) {
fail("testGetAttributesMutator(): getAttributesMutator() returns null on an open accessor");
}
// Close PR
pr.close();
try {
o = pr.getAttributesMutator();
fail(
"testGetAttributesMutator() does not throw RegionDestroyedException on a closed PartitionedRegion.");
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testGetAttributesMutator(): getAttributesMutator() throws RegionDestroyedException on a closed PartitionedRegion. ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetAttributesMutator() Completed successfully ... ");
}
}
/**
* Test to check local-cache property. Creates PR with default local-cache setting. TODO Enable
* this when we have local caching properly implemented -- mthomas 2/23/2006
*/
//
// public void xxNoTestLoalCache() throws Exception
// {
// String regionName = "testLocalCache";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 2,
// Scope.DISTRIBUTED_ACK, false);
// assertFalse(pr.getAttributes().getPartitionAttributes()
// .isLocalCacheEnabled());
//
// PartitionedRegion pr1 = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName + 2, String.valueOf(200), 2,
// Scope.DISTRIBUTED_ACK, true);
// assertTrue(pr1.getAttributes().getPartitionAttributes()
// .isLocalCacheEnabled());
//
// pr.destroyRegion();
// pr1.destroyRegion();
//
// }
/**
* Test to verify the scope of the Bucket Regions created. Scope is Local for redundantCopies 0.
* Scope is DISTRIBUTED_ACK if redundantCopies > 0 and Region scope is DISTRIBUTED_ACK.Scope is
* DISTRIBUTED_NO_ACK if redundantCopies > 0 and Region scope is DISTRIBUTED_NO_ACK
*/
@Test
public void test018BucketScope() throws Exception {
String regionName = "testBucketScope";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
putSomeValues(pr);
java.util.Iterator buckRegionIterator =
pr.getDataStore().getLocalBucket2RegionMap().values().iterator();
while (buckRegionIterator.hasNext()) {
Region bucket = (Region) buckRegionIterator.next();
// assertIndexDetailsEquals(Scope.LOCAL, bucket.getAttributes().getScope());
// assertIndexDetailsEquals(DataPolicy.NORMAL, bucket.getAttributes().getDataPolicy());
assertEquals(BucketRegion.class, bucket.getClass());
}
pr.destroyRegion();
/*
* PartitionedRegion pr1 = (PartitionedRegion)PartitionedRegionTestHelper
* .createPartitionedRegion(regionName + 2, String.valueOf(200), 0, Scope.DISTRIBUTED_ACK);
*
* putSomeValues(pr1); java.util.Iterator buckRegionIterator1 =
* pr1.getDataStore().localBucket2RegionMap .values().iterator(); while
* (buckRegionIterator1.hasNext()) { Region bucket = (Region)buckRegionIterator1.next();
* assertIndexDetailsEquals(Scope.DISTRIBUTED_ACK, bucket.getAttributes().getScope());
* assertIndexDetailsEquals(MirrorType.KEYS_VALUES, bucket.getAttributes() .getMirrorType()); }
*
* pr1.destroyRegion();
*
* PartitionedRegion pr2 = (PartitionedRegion)PartitionedRegionTestHelper
* .createPartitionedRegion(regionName + 2, String.valueOf(200), 0, Scope.DISTRIBUTED_NO_ACK);
*
* putSomeValues(pr2); java.util.Iterator buckRegionIterator2 =
* pr2.getDataStore().localBucket2RegionMap .values().iterator(); while
* (buckRegionIterator2.hasNext()) { Region bucket = (Region)buckRegionIterator2.next();
* assertIndexDetailsEquals(Scope.DISTRIBUTED_NO_ACK, bucket.getAttributes().getScope());
* assertIndexDetailsEquals(MirrorType.KEYS_VALUES, bucket.getAttributes() .getMirrorType()); }
* pr2.destroyRegion();
*/
}
private void putSomeValues(Region r) {
for (int i = 0; i < 10; i++) {
r.put("" + i, "" + i);
}
}
/**
* This method validates create operations. It verfies that entries are created and if entry
* already exists, it throws EntryExistsException.
*/
@Test
public void test019Create() throws EntryExistsException {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCreate", String.valueOf(200), 0);
// testing if the create is working fine.
// It checks that it throws EntryExistsException for an already existing key
final String expectedExceptions = EntryExistsException.class.getName();
for (int num = 0; num < 3; num++) {
key++;
final int initialCreates = getCreateCount(pr);
pr.create(new Integer(key), val + num);
assertEquals(initialCreates + 1, getCreateCount(pr));
final Object getObj1 = pr.get(new Integer(key));
if (!getObj1.equals(val + num)) {
fail("Create could not create an entry");
}
pr.getCache().getLogger()
.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.create(new Integer(key), val + num + "Added number");
fail(
"create doesnt throw EntryExistsException subsequent create on an already existing key");
} catch (EntryExistsException eee) {
}
pr.getCache().getLogger()
.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
final Object getObj2 = pr.get(new Integer(key));
if (!getObj1.equals(getObj2)) {
fail("Create could not create an entry");
}
}
// I am going to null val check;
for (int cnt = 0; cnt < 3; cnt++) {
Object dummyObj = "DummyVal";
Object nonNullKey = new Long(cnt);
Object nullVal = null;
Object nonNullVal = cnt + "";
pr.create(nonNullKey, nullVal);
dummyObj = pr.get(nonNullKey);
if (dummyObj != null) {
fail("Create can not create an entry with null value");
}
pr.getCache().getLogger()
.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.create(nonNullKey, nonNullVal);
fail("Create does not throw EntryExistsException with for an existing null value as well");
} catch (EntryExistsException eee) {
}
pr.getCache().getLogger()
.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
}
}
@Test
public void test020CreateWriter() {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCreateWriter", String.valueOf(200), 0);
MyCacheWriter writer = new MyCacheWriter();
pr.getAttributesMutator().setCacheWriter(writer);
writer.setExpectedKeyAndValue("key1", "value1");
pr.create("key1", "value1");
assertTrue(writer.isValidationSuccessful());
writer.setExpectedKeyAndValue("key1", "value2");
pr.put("key1", "value2");
assertTrue(writer.isValidationSuccessful());
writer.setExpectedKeyAndValue("key1", "value2");
pr.destroy("key1");
assertTrue(writer.isValidationSuccessful());
}
private class MyCacheWriter implements CacheWriter {
private Object key;
private Object value;
private boolean validationSuccessful = false;
public void setExpectedKeyAndValue(Object key, Object value) {
this.key = key;
this.value = value;
this.validationSuccessful = false;
}
public boolean isValidationSuccessful() {
return validationSuccessful;
}
@Override
public void beforeCreate(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isCreate());
assertTrue(!event.getRegion().containsKey(this.key));
assertTrue(!event.getRegion().containsValueForKey(this.key));
assertNull(event.getRegion().getEntry(event.getKey()));
this.validationSuccessful = true;
}
@Override
public void beforeDestroy(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isDestroy());
assertTrue(event.getRegion().containsKey(this.key));
assertTrue(event.getRegion().containsValueForKey(this.key));
this.validationSuccessful = true;
}
@Override
public void beforeRegionClear(RegionEvent event) throws CacheWriterException {}
@Override
public void beforeRegionDestroy(RegionEvent event) throws CacheWriterException {}
@Override
public void beforeUpdate(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isUpdate());
assertTrue(event.getRegion().containsKey(this.key));
assertTrue(event.getRegion().containsValueForKey(this.key));
assertNotNull(event.getRegion().getEntry(this.key));
assertNotSame(this.value, event.getRegion().get(this.key));
this.validationSuccessful = true;
}
@Override
public void close() {}
}
/**
* This method validates invalidate operations. It verfies that if entry exists, it is
* invalidated. If entry does not exist, it throws EntryNotFoundException.
*/
@Test
public void test021Invalidate() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testInvalidate", String.valueOf(200), 0);
// testing if the create is working fine.
// It checks that it throws EntryExistsException for an already existing key
Object getObj1 = null;
Object getObj2 = null;
for (int num = 0; num < 3; num++) {
key++;
try {
pr.put(new Integer(key), val + num);
} catch (Exception e) {
fail("testInvalidate(): put throws exception");
}
getObj1 = pr.get(new Integer(key));
if (!getObj1.equals(val + num)) {
fail("testInvalidate(): Could not put a correct entry");
}
pr.invalidate(new Integer(key));
getObj2 = pr.get(new Integer(key));
if (getObj2 != null) {
fail("testInvalidate(): Invalidate could not invalidate an entry");
}
String prefix = "1";
String dummyKey = prefix + key;
try {
pr.invalidate(new Integer(dummyKey));
fail("testInvalidate(): Invalidate doesnt not throw EntryNotFoundException");
} catch (EntryNotFoundException enf) {
if (logWriter.fineEnabled()) {
logWriter.fine("testInvalidate(): Invalidate throws EntryNotFoundException");
}
}
pr.destroy(new Integer(key));
try {
pr.invalidate(new Integer(dummyKey));
fail("testInvalidate(): Invalidate doesnt not throw EntryNotFoundException");
} catch (EntryNotFoundException enf) {
if (logWriter.fineEnabled()) {
logWriter.fine("testInvalidate(): Invalidate throws EntryNotFoundException");
}
} catch (Exception e) {
fail("testInvalidate(): Invalidate throws exception other than EntryNotFoundException");
}
assertEquals(num + 1,
((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getInvalidates());
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testInvalidate() Completed successfully ... ");
}
}
@Test
public void test022GetEntry() throws Exception {
Region pr = null;
try {
pr = PartitionedRegionTestHelper.createPartitionedRegion("testGetEntry", String.valueOf(200),
0);
final Integer one = new Integer(1);
pr.put(one, "one");
final Region.Entry re = pr.getEntry(one);
assertFalse(re.isDestroyed());
assertFalse(re.isLocal());
assertTrue(((EntrySnapshot) re).wasInitiallyLocal());
assertEquals("one", re.getValue());
assertEquals(one, re.getKey());
// TODO: Finish out the entry operations
assertNull(pr.getEntry("nuthin"));
} finally {
if (pr != null) {
pr.destroyRegion();
}
}
}
@Test
public void test023UnsupportedOps() throws Exception {
Region pr = null;
try {
pr = PartitionedRegionTestHelper.createPartitionedRegion("testUnsupportedOps",
String.valueOf(200), 0);
pr.put(new Integer(1), "one");
pr.put(new Integer(2), "two");
pr.put(new Integer(3), "three");
pr.getEntry("key");
try {
pr.clear();
fail(
"PartitionedRegionSingleNodeOperationTest:testUnSupportedOps() operation failed on a blank PartitionedRegion");
} catch (UnsupportedOperationException expected) {
}
// try {
// pr.entries(true);
// fail();
// }
// catch (UnsupportedOperationException expected) {
// }
// try {
// pr.entrySet(true);
// fail();
// }
// catch (UnsupportedOperationException expected) {
// }
try {
HashMap data = new HashMap();
data.put("foo", "bar");
data.put("bing", "bam");
data.put("supper", "hero");
pr.putAll(data);
// fail("testPutAll() does NOT throw UnsupportedOperationException");
} catch (UnsupportedOperationException onse) {
}
// try {
// pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException expected) {
// }
try {
pr.containsValue("foo");
} catch (UnsupportedOperationException ex) {
fail("PartitionedRegionSingleNodeOperationTest:testContainsValue() operation failed");
}
} finally {
if (pr != null) {
pr.destroyRegion();
}
}
}
/**
* This method validates size operations. It verifies that it returns correct size of the
* PartitionedRegion.
*/
@Test
public void test024Size() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testSize", String.valueOf(200), 0);
int size = 0;
size = pr.size();
assertEquals(size, 0);
int count = 10;
int removeCnt = 5;
// Testing for a populated PR
for (int num = 1; num <= count; num++) {
key++;
pr.put(new Integer(key), val);
Object tmpVal = pr.get(new Integer(key));
int tmpSize = pr.size();
assertEquals(num, tmpSize);
}
size = pr.size();
assertEquals(size, count);
// Testing for a populated PR
for (int num = 1; num <= removeCnt; num++) {
pr.destroy(new Integer(num));
}
size = pr.size();
assertEquals(size, (count - removeCnt));
pr.close();
try {
pr.size();
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSize() returns RegionDestroyedException on a closed PartitionedRegion.");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSize() Completed successfully ... ");
}
}
/**
* This method validates isEmpty operation. It verifies that it returns true if PartitionedRegion
* is empty.
*/
@Test
public void test025IsEmpty() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testIsEmpty", String.valueOf(200), 0);
boolean isEmpty = pr.isEmpty();
assertEquals(isEmpty, true);
int count = 10;
for (int num = 1; num <= count; num++) {
key++;
pr.put(new Integer(key), val);
assertEquals(num, pr.size());
}
isEmpty = pr.isEmpty();
assertEquals(isEmpty, false);
for (int num = 1; num <= count; num++) {
pr.destroy(new Integer(num));
}
isEmpty = pr.isEmpty();
assertEquals(isEmpty, true);
pr.close();
try {
pr.isEmpty();
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsEmpty() returns RegionDestroyedException on a closed PartitionedRegion.");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsEmpty() Completed successfully ... ");
}
}
@Test
public void test026CloseDestroy() throws Exception {
logWriter.fine("Getting inside testCloseDestroy");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCloseDestroy", String.valueOf(200), 0);
pr.close();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion("testCloseDestroy",
String.valueOf(200), 0);
try {
pr.destroyRegion();
} catch (RegionDestroyedException expected) {
fail("testCloseDestroy(): Can not destroy a newly created region.");
}
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion("testCloseDestroy",
String.valueOf(200), 0);
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testCloseDestroy() Completed successfully ... ");
}
}
}
|
geode-core/src/integrationTest/java/org/apache/geode/internal/cache/PartitionedRegionSingleNodeOperationsJUnitTest.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.geode.internal.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.apache.geode.LogWriter;
import org.apache.geode.cache.CacheWriter;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.EntryExistsException;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.PartitionedRegionStorageException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.RegionEvent;
import org.apache.geode.cache30.RegionTestCase;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.logging.LogService;
/**
* Test for Partitioned Region operations on a single node. Following tests are included:
* <P>
* (1) testPut() - Tests the put() functionality for the partitioned region.
* </P>
*
*
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PartitionedRegionSingleNodeOperationsJUnitTest {
private static final Logger logger = LogService.getLogger();
static DistributedSystem sys = null;
static int var = 1;
final String val = "string_value";
LogWriter logWriter = null;
@Before
public void setUp() throws Exception {
logWriter = PartitionedRegionTestHelper.getLogger();
}
/**
* This isa test for PartitionedRegion put() operation.
* <p>
* Following functionalities are tested:
* </p>
* <p>
* 1) put() on PR with localMaxMemory = 0. PartitionedRegionException expected.
* </p>
* <p>
* 2)test the put() operation and validate that old values are returned in case of PR with scope
* D_ACK.
* </p>
*
*
*/
@Test
public void test000Put() throws Exception {
String regionname = "testPut";
int localMaxMemory = 0;
System.setProperty(PartitionedRegion.RETRY_TIMEOUT_PROPERTY, "20000");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionname, String.valueOf(localMaxMemory), 0);
System.setProperty(PartitionedRegion.RETRY_TIMEOUT_PROPERTY,
Integer.toString(PartitionedRegionHelper.DEFAULT_TOTAL_WAIT_RETRY_ITERATION));
final String expectedExceptions = PartitionedRegionStorageException.class.getName();
logger.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.put(new Integer(1), val);
fail("testPut()- Expected PartitionedRegionException not thrown for localMaxMemory = 0");
} catch (PartitionedRegionStorageException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testPut() - Got a correct exception-PartitionedRegionStorageException for localMaxMemory=0 ");
}
}
logger.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
if (!pr.isDestroyed())
pr.destroyRegion();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionname,
String.valueOf(400), 0);
final int maxEntries = 3;
for (int num = 0; num < maxEntries; num++) {
final Integer key = new Integer(num);
final Object oldVal = pr.put(key, this.val);
// Assert a more generic return value here because the bucket has not been allocated yet
// thus do not know if the value is local or not
assertTrue(oldVal == null);
assertEquals(this.val, pr.get(key));
final Region.Entry entry = pr.getEntry(key);
assertNotNull(entry);
assertEquals(this.val, entry.getValue());
assertTrue(pr.values().contains(this.val));
if (RegionTestCase.entryIsLocal(entry)) {
assertEquals("Failed for key " + num, this.val, pr.put(key, key));
} else {
assertEquals("Failed for key " + num, null, pr.put(key, key));
}
assertEquals((num + 1) * 2, ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getPuts());
}
if (!pr.isDestroyed())
pr.destroyRegion();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionname,
String.valueOf(400), 0);
for (int num = 0; num < maxEntries; num++) {
pr.put(new Integer(num), this.val);
Object retval = pr.get(new Integer(num));
assertEquals(this.val, retval);
}
for (int num = 0; num < maxEntries; num++) {
if (RegionTestCase.entryIsLocal(pr.getEntry(new Integer(num)))) {
assertEquals(this.val, pr.put(new Integer(num), this.val));
} else {
assertEquals(null, pr.put(new Integer(num), this.val));
}
}
final Object dummyVal = "DummyVal";
for (int num = 0; num < maxEntries; num++) {
final Object getObj = pr.get(new Integer(num));
final Object oldPut = pr.put(new Integer(num), dummyVal);
if (((EntrySnapshot) pr.getEntry(new Integer(num))).wasInitiallyLocal()) {
assertEquals("Returned value from put operation is not same as the old value", getObj,
oldPut);
} else {
assertEquals(null, oldPut);
}
assertEquals("testPut()- error in putting the value in the Partitioned Region", dummyVal,
pr.get(new Integer(num)));
}
}
/**
* This is a test for PartitionedRegion destroy(key) operation.
*
*/
@Test
public void test001Destroy() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testDestroy", String.valueOf(200), 0);
final String expectedExceptions = EntryNotFoundException.class.getName();
final String addExpected =
"<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>";
final String removeExpected =
"<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>";
logger.info(addExpected);
for (int num = 0; num < 3; num++) {
try {
pr.destroy(new Integer(num));
fail(
"Destroy doesn't throw EntryNotFoundException for the entry which never existed in the system");
} catch (EntryNotFoundException expected) {
}
}
logger.info(removeExpected);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
final int initialDestroyCount = getDestroyCount(pr);
pr.destroy(new Integer(num));
assertEquals(initialDestroyCount + 1, getDestroyCount(pr));
}
for (int num = 0; num < 3; num++) {
Object retval = pr.get(new Integer(num));
if (retval != null)
fail("testDestroy()- entry not destroyed properly in destroy(key)");
}
logger.info(addExpected);
for (int num = 0; num < 3; num++) {
try {
pr.destroy(new Integer(num));
fail(
"Destroy doesn't throw EntryNotFoundException for the entry which is already deleted from the system");
} catch (EntryNotFoundException enf) {
}
}
logger.info(removeExpected);
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testDestroy() Completed successfully ... ");
}
}
private int getDestroyCount(PartitionedRegion pr) {
return ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getDestroys();
}
private int getCreateCount(PartitionedRegion pr) {
return ((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getCreates();
}
/**
* This is a test for PartitionedRegion get(key) operation.
*
*/
@Test
public void test002Get() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGet", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
Object retval = pr.get(new Integer(num));
if (!val.equals(String.valueOf(retval))) {
fail("testGet() - get operation failed for Partitioned Region ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGet() Completed successfully ... ");
}
}
/**
* This is a test for PartitionedRegion destroyRegion() operation.
*/
@Test
public void test003DestroyRegion() throws Exception {
String regionName = "testDestroyRegion";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
pr.put(new Integer(1), new Integer(1));
pr.get(new Integer(1));
if (pr.isDestroyed()) {
fail(
"PartitionedRegionSingleNodeOperationsJUnitTest:testDestroyRegion(): Returns true in isDestroyed method, before the region is destroyed");
}
logWriter.info("JDEBUG 1");
pr.destroyRegion();
logWriter.info("JDEBUG 2");
// Validate that the meta-data and bucket regions are cleaned.
assertTrue(pr.isDestroyed());
// assertTrue(pr.getBucket2Node().isEmpty());
Region root = PartitionedRegionHelper.getPRRoot(PartitionedRegionTestHelper.createCache());
// assertNull(PartitionedRegionHelper.getPRConfigRegion(root,
// PartitionedRegionTestHelper.createCache()).get(regionName));
java.util.Iterator regItr = root.subregions(false).iterator();
while (regItr.hasNext()) {
Region rg = (Region) regItr.next();
// System.out.println("Region = " + rg.getName());
assertEquals(
rg.getName().indexOf(PartitionedRegionHelper.BUCKET_REGION_PREFIX + pr.getPRId() + "_"),
-1);
}
if (!pr.isDestroyed()) {
fail("testDestroyRegion(): "
+ "Returns false in isDestroyed method, after the region is destroyed");
}
logWriter.info("JDEBUG 3");
try {
pr.put(new Integer(2), new Integer(2));
fail("testdestroyRegion() Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testDestroyRegion() got a corect RegionDestroyedException for put() after destroyRegion()");
}
}
logWriter.info("JDEBUG 4");
try {
pr.get(new Integer(2));
fail("testdestroyRegion() - Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - "
+ "testDestroyRegion() got a correct RegionDestroyedException for get() after destroyRegion()");
}
}
logWriter.info("JDEBUG 5");
try {
pr.destroy(new Integer(1));
fail("testdestroyRegion() Expected RegionDestroyedException not thrown");
} catch (RegionDestroyedException ex) {
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - "
+ "testDestroyRegion() got a correct RegionDestroyedException for destroy() after destroyRegion()");
}
}
logWriter.info("JDEBUG 6");
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion(regionName,
String.valueOf(200), 0);
if (logWriter.fineEnabled()) {
logWriter.fine("PartitionedRegionSingleNodeOperationsJUnitTest - testDestroyRegion():"
+ " PartitionedRegion with same name as the destroyed region, can be created.");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testDestroyRegion(): Completed Successfully ...");
}
}
/**
* Tests getCache() API of PR. This should return same value as the cache used.
*
*/
@Test
public void test004GetCache() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetCache", String.valueOf(200), 0);
GemFireCacheImpl ca = (GemFireCacheImpl) pr.getCache();
if (!PartitionedRegionTestHelper.createCache().equals(ca)) {
fail("testGetCache() - getCache method is not returning proper cache handle");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetCache() Completed Successfully");
}
}
/**
* Tests getFullPath() API of PartitionedRegion.
*
*/
@Test
public void test005GetFullPath() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetFullPath", String.valueOf(200), 0);
String fullPath = pr.getFullPath();
if (!(Region.SEPARATOR + "testGetFullPath").equals(fullPath)) {
fail("testGetFullPath() - getFullPath method is not returning proper fullPath");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetFullPath() Completed Successfully");
}
}
/**
* Tests getParentRegion() API of PR. This should return null as PR doesnt have a parentRegion
*
*/
@Test
public void test006GetParentRegion() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetParentRegion", String.valueOf(200), 0);
Region parentRegion = pr.getParentRegion();
if (parentRegion != null) {
fail("getParentRegion method is not returning null as parent region for a PartitionedRegion");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetParentRegion() Completed Successfully");
}
}
/**
* Tests getName() API of PR. Name returned should be same as the one used to create PR.
*
*/
@Test
public void test007GetName() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testGetName", String.valueOf(200), 0);
String name = pr.getName();
if (!("testGetName").equals(name)) {
fail("getName() method is not returning proper region name");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetName() Completed Successfully");
}
}
/**
* This method validates containsKey() operations.
*/
@Test
public void test008ContainsKey() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testContainsKey", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
boolean retval = pr.containsKey(new Integer(num));
if (!retval) {
fail("PartitionedRegionSingleNodeOperationTest:testContainsKey() operation failed");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testContainsKey() Completed successfully ... ");
}
}
/**
* This method validates containsKey() operations.
*/
@Test
public void test009ContainsValueForKey() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testContainsValueForKey", String.valueOf(200), 0);
for (int num = 0; num < 3; num++) {
pr.put(new Integer(num), val);
boolean retval = pr.containsValueForKey(new Integer(num));
if (!retval) {
fail(
"PartitionedRegionSingleNodeOperationTest:testContainsValueForKey() operation failed");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testContainsValueForKey() Completed successfully ... ");
}
}
/**
* Tests close() API of PR. It should close the accessor and delete the data-store and related
* meta-data information.
*
*/
@Test
public void test010Close() throws Exception {
logWriter.fine("Getting inside testClose method");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testClose", String.valueOf(200), 0);
pr.put("K1", "V1");
pr.get("K1");
pr.close();
if (!pr.isClosed || !pr.isDestroyed())
fail("testClose(): After close isClosed = " + pr.isClosed + " and isDestroyed = "
+ pr.isDestroyed());
try {
pr.put("K2", "V2");
fail("testClose(): put operation completed on a closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
}
// validating get operation
try {
pr.get("K1");
fail("testClose(): get operation should not succeed on closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
// if (logger.fineEnabled()) {
// logger.fine("Got correct RegionDestroyedException after close() ");
// }
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testClose() Completed successfully ... ");
}
}
/**
* Tests localDestroyRegion() API of PR. It should locallyDestroy the accessor, data store and
* meta-data.
*
*/
@Test
public void test011LocalDestroyRegion() throws Exception {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testClose", String.valueOf(200), 0);
pr.put("K1", "V1");
pr.get("K1");
pr.localDestroyRegion();
if (pr.isClosed || !pr.isDestroyed())
fail("testClose(): After close isClosed = " + pr.isClosed + " and isDestroyed = "
+ pr.isDestroyed());
try {
pr.put("K2", "V2");
fail("testClose(): put operation completed on a closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
}
try {
pr.get("K1");
fail("testClose(): get operation should not succeed on closed PartitionedRegion. ");
} catch (RegionDestroyedException expected) {
if (logWriter.fineEnabled()) {
logWriter.fine("Got correct RegionDestroyedException after close() ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testClose() Completed successfully ... ");
}
}
/**
* This method is used to test the isDestroyed() functionality.
*
*/
@Test
public void test012IsDestroyed() throws Exception {
String regionName = "testIsDestroyed";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
pr.put(new Integer(1), new Integer(1));
pr.get(new Integer(1));
if (pr.isDestroyed()) {
fail(
"PartitionedRegionSingleNodeOperationsJUnitTest:testIsDestroyed(): Returns true in isDestroyed method, before the region is destroyed");
}
pr.destroyRegion();
if (!pr.isDestroyed()) {
fail("PartitionedRegionSingleNodeOperationsJUnitTest:testIsDestroyed(): "
+ "Returns false in isDestroyed method, after the region is destroyed");
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsDestroyed() Completed successfully ... ");
}
}
/**
* This method validates that PR closed behavior matches that of local region closed behavior.
*
*/
/*
* public void xxNoTestValidateCloseFunction() throws Exception { String partitionRegionName =
* "testValidateCloseFunction"; PartitionedRegion pr =
* (PartitionedRegion)PartitionedRegionTestHelper .createPartitionedRegion(partitionRegionName,
* String.valueOf(200), 2, Scope.DISTRIBUTED_ACK); String diRegion = "diRegion";
*
* Region distRegion = null;
*
* AttributesFactory af = new AttributesFactory(); RegionAttributes regionAttributes; // setting
* property af.setScope(Scope.DISTRIBUTED_ACK); // creating region attributes regionAttributes =
* af.create(); try { distRegion = PartitionedRegionTestHelper.createCache().createRegion(
* diRegion, regionAttributes); } catch (RegionExistsException rex) { distRegion =
* PartitionedRegionTestHelper.createCache() .getRegion(diRegion); } // Closing the regions
* distRegion.close(); pr.close();
*
* if (!pr.getCache().equals(distRegion.getCache())) {
* fail("testValidateCloseFunction: getCache is not matching. "); } else { if
* (logger.fineEnabled()) { logger.fine("getCache() matched on closed PR and distributed region
* "); } } if (distRegion.getName().length() != pr.getName().length()) {
* fail("testValidateCloseFunction: getName behavior not matching. "); } else { if
* (logger.fineEnabled()) { logger.fine("getName) matched on closed PR and distributed region ");
* } }
*
* if (distRegion.getFullPath().length() != pr.getFullPath().length()) {
* fail("testValidateCloseFunction: getFullPath behavior not matching. "); } else { if
* (logger.fineEnabled()) { logger .fine("getFullPath) matched on closed PR and distributed region
* "); } }
*
* if (logger.fineEnabled()) { logger .fine("PartitionedRegionSingleNodeOperationsJUnitTest -
* testValidateCloseFunction() Completed successfully ... "); } }
*/
// /**
// * This method is used to test the entrySet method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestEntrySet() throws Exception
// {
// String regionName = "testEntrySet";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
//
// try {
// Set s = pr.entrySet(true);
// fail("testEntrySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testEntrySet() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Set s = pr.entrySet(true);
// fail("testEntrySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testEntrySet() is correctly throwing UnsupportedOperationException on a non-empty PR");
// }
// }
//
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testEntrySet() Completed successfully
// ... ");
// }
// }
/**
* Test either the keySet() or keys() methods, which logically are expected to be the same
*/
private void keysSetTester(Region pr) {
assertEquals(Collections.EMPTY_SET, pr.keySet());
pr.put(new Integer(1), "won");
pr.put(new Integer(2), "to");
pr.put(new Integer(3), "free");
pr.put(new Integer(5), "hive");
final Set ks = pr.keySet();
assertEquals(4, ks.size());
try {
ks.clear();
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.add("foo");
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.addAll(Arrays.asList(new String[] {"one", "two", "three"}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.remove("boom");
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.removeAll(Arrays.asList(new Integer[] {new Integer(1), new Integer(2)}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
try {
ks.retainAll(Arrays.asList(new Integer[] {new Integer(3), new Integer(5)}));
fail("Expected key set to be read only");
} catch (Exception expected) {
}
final Iterator ksI = ks.iterator();
for (int i = 0; i < 4; i++) {
try {
ksI.remove();
fail("Expected key set iterator to be read only");
} catch (Exception expected) {
}
assertTrue(ksI.hasNext());
Object key = ksI.next();
assertEquals(Integer.class, key.getClass());
}
try {
ksI.remove();
fail("Expected key set iterator to be read only");
} catch (Exception expected) {
}
try {
ksI.next();
fail("Expected no such element exception");
} catch (NoSuchElementException expected) {
}
}
@Test
public void test014KeySet() throws Exception {
String regionName = "testKeysSet";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
keysSetTester(pr);
}
// /**
// * This method is used to test the keySet method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestKeySet() throws Exception
// {
// String regionName = "testKeySet";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
//
// try {
// Set s = pr.keySet();
// fail("testKeySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testKeySet() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Set s = pr.keySet();
// fail("testKeySet() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine("testKeySet() is correctly throwing UnsupportedOperationException on a non-empty PR");
// }
// }
//
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testKeySet() Completed successfully ...
// ");
// }
// }
// /**
// * This method is used to test the putAll method. It verifies that it throws
// * UnsupportedOperationException.
// *
// */
// public void xxNoTestPutAll() throws Exception
// {
// final String rName = "testPutAll";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(rName, String.valueOf(8), 0,
// Scope.DISTRIBUTED_ACK);
// try {
// assertNotNull(pr);
// final String foo = "foo";
// final String bing = "bing";
// final String supper = "super";
// HashMap data = new HashMap();
// data.put(foo, "bar");
// data.put(bing, "bam");
// data.put(supper, "hero");
//
// assertNull(pr.get(foo));
// assertNull(pr.get(bing));
// assertNull(pr.get(supper));
// try {
// pr.putAll(data);
// fail("testPutAll() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testPutall() is correctly throwing UnsupportedOperationException on an empty PR");
// }
// }
// assertNull(pr.get(foo));
// assertNull(pr.get(bing));
// assertNull(pr.get(supper));
// }
// finally {
// pr.destroyRegion();
// }
// }
// /**
// * This method is used to test the values functionality. It verifies that it
// * throws UnsupportedOperationException.
// *
// */
// public void xxNoTestValues() throws Exception
// {
// String regionName = "testValues";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
// try {
// Collection c = pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
// if (logger.fineEnabled()) {
// logger
// .fine("testValues() correctly throwing UnsupportedOperationException on an empty PR ");
// }
// }
//
// pr.put(new Integer(1), new Integer(1));
//
// try {
// Collection c = pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine("testValues() is correctly throwing UnsupportedOperationException on a non-empty PR ");
// }
// }
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testValues() Completed successfully ...
// ");
// }
// }
// /**
// * This method validates containsKey operations. It verifies that it throws
// * UnsupportedOperationException.
// */
// public void xxNoTestContainsValue() throws Exception
// {
// int key = 0;
// Region pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion("testContainsValue", String.valueOf(200), 0,
// Scope.DISTRIBUTED_ACK);
// for (int num = 0; num < 3; num++) {
// key++;
// pr.put(new Integer(key), val);
// try {
// boolean retval = pr.containsValue(val);
// fail("PartitionedRegionSingleNodeOperationTest:testContainsValue() operation failed");
// }
// catch (UnsupportedOperationException onse) {
//
// if (logger.fineEnabled()) {
// logger
// .fine(" testContainsValue is correctly throwing UnsupportedOperationException for value = "
// + val);
// }
// }
// }
// if (logger.fineEnabled()) {
// logger
// .fine("PartitionedRegionSingleNodeOperationsJUnitTest - testContainsValue() Completed
// successfully ... ");
// }
// }
/**
* This method is used to test the setUserAttributes functionality. It verifies that it sets the
* UserAttributes on an open PR without throwing any exception. It also verifies that it throws
* RegionDestroyedException on a closed PR.
*
*/
@Test
public void test015SetUserAttributes() throws Exception {
String regionName = "testSetUserAttributes";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
String s = "DUMMY";
pr.setUserAttribute(s);
// Close PR
pr.close();
try {
pr.setUserAttribute(s);
fail(
"testSetUserAttributes() doesnt throw RegionDestroyedException on a closed PartitionedRegion.");
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testSetUserAttributes(): setUserAttributes() throws RegionDestroyedException on a closed PartitionedRegion. ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSetUserAttributes() Completed successfully ... ");
}
}
/**
* This method is used to test the getUserAttributes functionality. It verifies that it gets the
* UserAttributes on an open PR without throwing any exception. It also verifies that it throws
* RegionDestroyedException on a closed PR.
*
*/
@Test
public void test016GetUserAttributes() throws Exception {
String regionName = "testGetUserAttributes";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
String s = "DUMMY";
pr.setUserAttribute(s);
Object o = pr.getUserAttribute();
if (!o.equals(s)) {
fail("testGetUserAttributes() returns null on an open accessor");
}
// Close PR
pr.close();
assertEquals(s, pr.getUserAttribute());
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetUserAttributes() Completed successfully ... ");
}
}
/**
* This method is used to test the getAttributesMutator functionality. It verifies that it gets
* the handle for attributes mutator on an open PR without throwing any exception. It also
* verifies that it throws RegionDestroyedException on a closed PR.
*
*/
@Test
public void test017GetAttributesMutator() throws Exception {
String regionName = "testGetAttributesMutator";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
Object o = pr.getAttributesMutator();
if (o == null) {
fail("testGetAttributesMutator(): getAttributesMutator() returns null on an open accessor");
}
// Close PR
pr.close();
try {
o = pr.getAttributesMutator();
fail(
"testGetAttributesMutator() does not throw RegionDestroyedException on a closed PartitionedRegion.");
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"testGetAttributesMutator(): getAttributesMutator() throws RegionDestroyedException on a closed PartitionedRegion. ");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testGetAttributesMutator() Completed successfully ... ");
}
}
/**
* Test to check local-cache property. Creates PR with default local-cache setting. TODO Enable
* this when we have local caching properly implemented -- mthomas 2/23/2006
*/
//
// public void xxNoTestLoalCache() throws Exception
// {
// String regionName = "testLocalCache";
// PartitionedRegion pr = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName, String.valueOf(200), 2,
// Scope.DISTRIBUTED_ACK, false);
// assertFalse(pr.getAttributes().getPartitionAttributes()
// .isLocalCacheEnabled());
//
// PartitionedRegion pr1 = (PartitionedRegion)PartitionedRegionTestHelper
// .createPartitionedRegion(regionName + 2, String.valueOf(200), 2,
// Scope.DISTRIBUTED_ACK, true);
// assertTrue(pr1.getAttributes().getPartitionAttributes()
// .isLocalCacheEnabled());
//
// pr.destroyRegion();
// pr1.destroyRegion();
//
// }
/**
* Test to verify the scope of the Bucket Regions created. Scope is Local for redundantCopies 0.
* Scope is DISTRIBUTED_ACK if redundantCopies > 0 and Region scope is DISTRIBUTED_ACK.Scope is
* DISTRIBUTED_NO_ACK if redundantCopies > 0 and Region scope is DISTRIBUTED_NO_ACK
*/
@Test
public void test018BucketScope() throws Exception {
String regionName = "testBucketScope";
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(regionName, String.valueOf(200), 0);
putSomeValues(pr);
java.util.Iterator buckRegionIterator =
pr.getDataStore().getLocalBucket2RegionMap().values().iterator();
while (buckRegionIterator.hasNext()) {
Region bucket = (Region) buckRegionIterator.next();
// assertIndexDetailsEquals(Scope.LOCAL, bucket.getAttributes().getScope());
// assertIndexDetailsEquals(DataPolicy.NORMAL, bucket.getAttributes().getDataPolicy());
assertEquals(BucketRegion.class, bucket.getClass());
}
pr.destroyRegion();
/*
* PartitionedRegion pr1 = (PartitionedRegion)PartitionedRegionTestHelper
* .createPartitionedRegion(regionName + 2, String.valueOf(200), 0, Scope.DISTRIBUTED_ACK);
*
* putSomeValues(pr1); java.util.Iterator buckRegionIterator1 =
* pr1.getDataStore().localBucket2RegionMap .values().iterator(); while
* (buckRegionIterator1.hasNext()) { Region bucket = (Region)buckRegionIterator1.next();
* assertIndexDetailsEquals(Scope.DISTRIBUTED_ACK, bucket.getAttributes().getScope());
* assertIndexDetailsEquals(MirrorType.KEYS_VALUES, bucket.getAttributes() .getMirrorType()); }
*
* pr1.destroyRegion();
*
* PartitionedRegion pr2 = (PartitionedRegion)PartitionedRegionTestHelper
* .createPartitionedRegion(regionName + 2, String.valueOf(200), 0, Scope.DISTRIBUTED_NO_ACK);
*
* putSomeValues(pr2); java.util.Iterator buckRegionIterator2 =
* pr2.getDataStore().localBucket2RegionMap .values().iterator(); while
* (buckRegionIterator2.hasNext()) { Region bucket = (Region)buckRegionIterator2.next();
* assertIndexDetailsEquals(Scope.DISTRIBUTED_NO_ACK, bucket.getAttributes().getScope());
* assertIndexDetailsEquals(MirrorType.KEYS_VALUES, bucket.getAttributes() .getMirrorType()); }
* pr2.destroyRegion();
*/
}
private void putSomeValues(Region r) {
for (int i = 0; i < 10; i++) {
r.put("" + i, "" + i);
}
}
/**
* This method validates create operations. It verfies that entries are created and if entry
* already exists, it throws EntryExistsException.
*/
@Test
public void test019Create() throws EntryExistsException {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCreate", String.valueOf(200), 0);
// testing if the create is working fine.
// It checks that it throws EntryExistsException for an already existing key
final String expectedExceptions = EntryExistsException.class.getName();
for (int num = 0; num < 3; num++) {
key++;
final int initialCreates = getCreateCount(pr);
pr.create(new Integer(key), val + num);
assertEquals(initialCreates + 1, getCreateCount(pr));
final Object getObj1 = pr.get(new Integer(key));
if (!getObj1.equals(val + num)) {
fail("Create could not create an entry");
}
pr.getCache().getLogger()
.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.create(new Integer(key), val + num + "Added number");
fail(
"create doesnt throw EntryExistsException subsequent create on an already existing key");
} catch (EntryExistsException eee) {
}
pr.getCache().getLogger()
.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
final Object getObj2 = pr.get(new Integer(key));
if (!getObj1.equals(getObj2)) {
fail("Create could not create an entry");
}
}
// I am going to null val check;
for (int cnt = 0; cnt < 3; cnt++) {
Object dummyObj = "DummyVal";
Object nonNullKey = new Long(cnt);
Object nullVal = null;
Object nonNullVal = cnt + "";
pr.create(nonNullKey, nullVal);
dummyObj = pr.get(nonNullKey);
if (dummyObj != null) {
fail("Create can not create an entry with null value");
}
pr.getCache().getLogger()
.info("<ExpectedException action=add>" + expectedExceptions + "</ExpectedException>");
try {
pr.create(nonNullKey, nonNullVal);
fail("Create does not throw EntryExistsException with for an existing null value as well");
} catch (EntryExistsException eee) {
}
pr.getCache().getLogger()
.info("<ExpectedException action=remove>" + expectedExceptions + "</ExpectedException>");
}
}
@Test
public void test020CreateWriter() {
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCreateWriter", String.valueOf(200), 0);
MyCacheWriter writer = new MyCacheWriter();
pr.getAttributesMutator().setCacheWriter(writer);
writer.setExpectedKeyAndValue("key1", "value1");
pr.create("key1", "value1");
assertTrue(writer.isValidationSuccessful());
writer.setExpectedKeyAndValue("key1", "value2");
pr.put("key1", "value2");
assertTrue(writer.isValidationSuccessful());
writer.setExpectedKeyAndValue("key1", "value2");
pr.destroy("key1");
assertTrue(writer.isValidationSuccessful());
}
private class MyCacheWriter implements CacheWriter {
private Object key;
private Object value;
private boolean validationSuccessful = false;
public void setExpectedKeyAndValue(Object key, Object value) {
this.key = key;
this.value = value;
this.validationSuccessful = false;
}
public boolean isValidationSuccessful() {
return validationSuccessful;
}
@Override
public void beforeCreate(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isCreate());
assertTrue(!event.getRegion().containsKey(this.key));
assertTrue(!event.getRegion().containsValueForKey(this.key));
assertNull(event.getRegion().getEntry(event.getKey()));
this.validationSuccessful = true;
}
@Override
public void beforeDestroy(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isDestroy());
assertTrue(event.getRegion().containsKey(this.key));
assertTrue(event.getRegion().containsValueForKey(this.key));
this.validationSuccessful = true;
}
@Override
public void beforeRegionClear(RegionEvent event) throws CacheWriterException {}
@Override
public void beforeRegionDestroy(RegionEvent event) throws CacheWriterException {}
@Override
public void beforeUpdate(EntryEvent event) throws CacheWriterException {
assertTrue(event.getOperation().isUpdate());
assertTrue(event.getRegion().containsKey(this.key));
assertTrue(event.getRegion().containsValueForKey(this.key));
assertNotNull(event.getRegion().getEntry(this.key));
assertNotSame(this.value, event.getRegion().get(this.key));
this.validationSuccessful = true;
}
@Override
public void close() {}
}
/**
* This method validates invalidate operations. It verfies that if entry exists, it is
* invalidated. If entry does not exist, it throws EntryNotFoundException.
*/
@Test
public void test021Invalidate() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testInvalidate", String.valueOf(200), 0);
// testing if the create is working fine.
// It checks that it throws EntryExistsException for an already existing key
Object getObj1 = null;
Object getObj2 = null;
for (int num = 0; num < 3; num++) {
key++;
try {
pr.put(new Integer(key), val + num);
} catch (Exception e) {
fail("testInvalidate(): put throws exception");
}
getObj1 = pr.get(new Integer(key));
if (!getObj1.equals(val + num)) {
fail("testInvalidate(): Could not put a correct entry");
}
pr.invalidate(new Integer(key));
getObj2 = pr.get(new Integer(key));
if (getObj2 != null) {
fail("testInvalidate(): Invalidate could not invalidate an entry");
}
String prefix = "1";
String dummyKey = prefix + key;
try {
pr.invalidate(new Integer(dummyKey));
fail("testInvalidate(): Invalidate doesnt not throw EntryNotFoundException");
} catch (EntryNotFoundException enf) {
if (logWriter.fineEnabled()) {
logWriter.fine("testInvalidate(): Invalidate throws EntryNotFoundException");
}
}
pr.destroy(new Integer(key));
try {
pr.invalidate(new Integer(dummyKey));
fail("testInvalidate(): Invalidate doesnt not throw EntryNotFoundException");
} catch (EntryNotFoundException enf) {
if (logWriter.fineEnabled()) {
logWriter.fine("testInvalidate(): Invalidate throws EntryNotFoundException");
}
} catch (Exception e) {
fail("testInvalidate(): Invalidate throws exception other than EntryNotFoundException");
}
assertEquals(num + 1,
((GemFireCacheImpl) pr.getCache()).getCachePerfStats().getInvalidates());
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testInvalidate() Completed successfully ... ");
}
}
@Test
public void test022GetEntry() throws Exception {
Region pr = null;
try {
pr = PartitionedRegionTestHelper.createPartitionedRegion("testGetEntry", String.valueOf(200),
0);
final Integer one = new Integer(1);
pr.put(one, "one");
final Region.Entry re = pr.getEntry(one);
assertFalse(re.isDestroyed());
assertFalse(re.isLocal());
assertTrue(((EntrySnapshot) re).wasInitiallyLocal());
assertEquals("one", re.getValue());
assertEquals(one, re.getKey());
// TODO: Finish out the entry operations
assertNull(pr.getEntry("nuthin"));
} finally {
if (pr != null) {
pr.destroyRegion();
}
}
}
@Test
public void test023UnsupportedOps() throws Exception {
Region pr = null;
try {
pr = PartitionedRegionTestHelper.createPartitionedRegion("testUnsupportedOps",
String.valueOf(200), 0);
pr.put(new Integer(1), "one");
pr.put(new Integer(2), "two");
pr.put(new Integer(3), "three");
pr.getEntry("key");
try {
pr.clear();
fail(
"PartitionedRegionSingleNodeOperationTest:testUnSupportedOps() operation failed on a blank PartitionedRegion");
} catch (UnsupportedOperationException expected) {
}
// try {
// pr.entries(true);
// fail();
// }
// catch (UnsupportedOperationException expected) {
// }
// try {
// pr.entrySet(true);
// fail();
// }
// catch (UnsupportedOperationException expected) {
// }
try {
HashMap data = new HashMap();
data.put("foo", "bar");
data.put("bing", "bam");
data.put("supper", "hero");
pr.putAll(data);
// fail("testPutAll() does NOT throw UnsupportedOperationException");
} catch (UnsupportedOperationException onse) {
}
// try {
// pr.values();
// fail("testValues() does NOT throw UnsupportedOperationException");
// }
// catch (UnsupportedOperationException expected) {
// }
try {
pr.containsValue("foo");
} catch (UnsupportedOperationException ex) {
fail("PartitionedRegionSingleNodeOperationTest:testContainsValue() operation failed");
}
} finally {
if (pr != null) {
pr.destroyRegion();
}
}
}
/**
* This method validates size operations. It verifies that it returns correct size of the
* PartitionedRegion.
*/
@Test
public void test024Size() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testSize", String.valueOf(200), 0);
int size = 0;
size = pr.size();
assertEquals(size, 0);
int count = 10;
int removeCnt = 5;
// Testing for a populated PR
for (int num = 1; num <= count; num++) {
key++;
pr.put(new Integer(key), val);
Object tmpVal = pr.get(new Integer(key));
int tmpSize = pr.size();
assertEquals(num, tmpSize);
}
size = pr.size();
assertEquals(size, count);
// Testing for a populated PR
for (int num = 1; num <= removeCnt; num++) {
pr.destroy(new Integer(num));
}
size = pr.size();
assertEquals(size, (count - removeCnt));
pr.close();
try {
pr.size();
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSize() returns RegionDestroyedException on a closed PartitionedRegion.");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testSize() Completed successfully ... ");
}
}
/**
* This method validates isEmpty operation. It verifies that it returns true if PartitionedRegion
* is empty.
*/
@Test
public void test025IsEmpty() throws Exception {
int key = 0;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testIsEmpty", String.valueOf(200), 0);
boolean isEmpty = pr.isEmpty();
assertEquals(isEmpty, true);
int count = 10;
for (int num = 1; num <= count; num++) {
key++;
pr.put(new Integer(key), val);
assertEquals(num, pr.size());
}
isEmpty = pr.isEmpty();
assertEquals(isEmpty, false);
for (int num = 1; num <= count; num++) {
pr.destroy(new Integer(num));
}
isEmpty = pr.isEmpty();
assertEquals(isEmpty, true);
pr.close();
try {
pr.isEmpty();
} catch (RegionDestroyedException rde) {
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsEmpty() returns RegionDestroyedException on a closed PartitionedRegion.");
}
}
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testIsEmpty() Completed successfully ... ");
}
}
@Test
public void test026CloseDestroy() throws Exception {
logWriter.fine("Getting inside testCloseDestroy");
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion("testCloseDestroy", String.valueOf(200), 0);
pr.close();
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion("testCloseDestroy",
String.valueOf(200), 0);
try {
pr.destroyRegion();
} catch (RegionDestroyedException expected) {
fail("testCloseDestroy(): Can not destroy a newly created region.");
}
pr = (PartitionedRegion) PartitionedRegionTestHelper.createPartitionedRegion("testCloseDestroy",
String.valueOf(200), 0);
if (logWriter.fineEnabled()) {
logWriter.fine(
"PartitionedRegionSingleNodeOperationsJUnitTest - testCloseDestroy() Completed successfully ... ");
}
}
}
|
GEODE-6386: make test repeatable
Signed-off-by: Jacob Barrett <430acd6b176712169fb35e8bbdd7f6bbc56387d3@pivotal.io>
|
geode-core/src/integrationTest/java/org/apache/geode/internal/cache/PartitionedRegionSingleNodeOperationsJUnitTest.java
|
GEODE-6386: make test repeatable
|
|
Java
|
apache-2.0
|
55e2180c19a6f0260571cef4e9f4c6a5205dc720
| 0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.naoth.rc.components.videoanalyzer;
import de.naoth.rc.RobotControl;
import de.naoth.rc.core.dialog.AbstractJFXDialog;
import de.naoth.rc.core.dialog.DialogPlugin;
import de.naoth.rc.core.dialog.RCDialog;
import de.naoth.rc.core.manager.SwingCommandExecutor;
import de.naoth.rc.logmanager.LogFileEventManager;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.util.Duration;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
/**
*
* @author thomas
*/
public class VideoAnalyzer extends AbstractJFXDialog
{
@RCDialog(category = "Log", name = "VideoAnalyzer")
@PluginImplementation
public static class Plugin extends DialogPlugin<VideoAnalyzer>
{
@InjectPlugin
public static RobotControl parent;
@InjectPlugin
public static SwingCommandExecutor commandExecutor;
@InjectPlugin
public static LogFileEventManager logFileEventManager;
@Override
public String getDisplayName()
{
return "Video Analyzer";
}
}
public static class GameStateChange implements Serializable
{
public double time;
public String state;
@Override
public String toString()
{
Duration elapsed = Duration.seconds(time);
double minutes = Math.floor(elapsed.toMinutes());
double seconds = elapsed.toSeconds() - (minutes * 60);
return String.format("%s (at %02d:%02.0f)", state, (int) minutes, seconds);
}
}
public final static String KEY_VIDEO_FILE = "video-file";
public final static String KEY_SYNC_TIME_VIDEO = "sync-time-video";
public final static String KEY_SYNC_TIME_LOG = "sync-time-log";
public VideoAnalyzer()
{
}
@Override
public URL getFXMLRessource()
{
return VideoPlayerController.class.getResource("VideoAnalyzer.fxml");
}
@Override
public Map<KeyCombination, Runnable> getGlobalShortcuts()
{
HashMap<KeyCombination, Runnable> result = new HashMap<>();
Runnable togglePlayRunnable = new Runnable()
{
@Override
public void run()
{
VideoAnalyzerController c = VideoAnalyzer.this.<VideoAnalyzerController>getController();
c.togglePlay();
}
};
result.put(new KeyCodeCombination(KeyCode.SPACE), togglePlayRunnable);
result.put(new KeyCodeCombination(KeyCode.P), togglePlayRunnable);
return result;
}
}
|
RobotControl/JFXPlugins/src/de/naoth/rc/components/videoanalyzer/VideoAnalyzer.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.naoth.rc.components.videoanalyzer;
import de.naoth.rc.RobotControl;
import de.naoth.rc.core.dialog.AbstractJFXDialog;
import de.naoth.rc.core.dialog.DialogPlugin;
import de.naoth.rc.core.manager.SwingCommandExecutor;
import de.naoth.rc.logmanager.LogFileEventManager;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.util.Duration;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
/**
*
* @author thomas
*/
public class VideoAnalyzer extends AbstractJFXDialog
{
@PluginImplementation
public static class Plugin extends DialogPlugin<VideoAnalyzer>
{
@InjectPlugin
public static RobotControl parent;
@InjectPlugin
public static SwingCommandExecutor commandExecutor;
@InjectPlugin
public static LogFileEventManager logFileEventManager;
@Override
public String getDisplayName()
{
return "Video Analyzer";
}
}
public static class GameStateChange implements Serializable
{
public double time;
public String state;
@Override
public String toString()
{
Duration elapsed = Duration.seconds(time);
double minutes = Math.floor(elapsed.toMinutes());
double seconds = elapsed.toSeconds() - (minutes * 60);
return String.format("%s (at %02d:%02.0f)", state, (int) minutes, seconds);
}
}
public final static String KEY_VIDEO_FILE = "video-file";
public final static String KEY_SYNC_TIME_VIDEO = "sync-time-video";
public final static String KEY_SYNC_TIME_LOG = "sync-time-log";
public VideoAnalyzer()
{
}
@Override
public URL getFXMLRessource()
{
return VideoPlayerController.class.getResource("VideoAnalyzer.fxml");
}
@Override
public Map<KeyCombination, Runnable> getGlobalShortcuts()
{
HashMap<KeyCombination, Runnable> result = new HashMap<>();
Runnable togglePlayRunnable = new Runnable()
{
@Override
public void run()
{
VideoAnalyzerController c = VideoAnalyzer.this.<VideoAnalyzerController>getController();
c.togglePlay();
}
};
result.put(new KeyCodeCombination(KeyCode.SPACE), togglePlayRunnable);
result.put(new KeyCodeCombination(KeyCode.P), togglePlayRunnable);
return result;
}
}
|
oops, forgot one dialog :)
|
RobotControl/JFXPlugins/src/de/naoth/rc/components/videoanalyzer/VideoAnalyzer.java
|
oops, forgot one dialog :)
|
|
Java
|
apache-2.0
|
b6b54810c5c00732229f175a79b5d94e46750244
| 0
|
tillrohrmann/flink,StephanEwen/incubator-flink,clarkyzl/flink,StephanEwen/incubator-flink,sunjincheng121/flink,zentol/flink,wwjiang007/flink,twalthr/flink,zentol/flink,lincoln-lil/flink,aljoscha/flink,apache/flink,clarkyzl/flink,wwjiang007/flink,tony810430/flink,zjureel/flink,godfreyhe/flink,greghogan/flink,godfreyhe/flink,rmetzger/flink,gyfora/flink,zentol/flink,twalthr/flink,kl0u/flink,apache/flink,gyfora/flink,godfreyhe/flink,godfreyhe/flink,godfreyhe/flink,StephanEwen/incubator-flink,tony810430/flink,rmetzger/flink,zjureel/flink,aljoscha/flink,godfreyhe/flink,lincoln-lil/flink,clarkyzl/flink,twalthr/flink,twalthr/flink,xccui/flink,greghogan/flink,StephanEwen/incubator-flink,lincoln-lil/flink,zjureel/flink,aljoscha/flink,kl0u/flink,xccui/flink,darionyaphet/flink,gyfora/flink,tony810430/flink,sunjincheng121/flink,wwjiang007/flink,kl0u/flink,xccui/flink,sunjincheng121/flink,sunjincheng121/flink,twalthr/flink,zjureel/flink,tony810430/flink,tony810430/flink,wwjiang007/flink,lincoln-lil/flink,rmetzger/flink,xccui/flink,tillrohrmann/flink,StephanEwen/incubator-flink,tillrohrmann/flink,rmetzger/flink,lincoln-lil/flink,xccui/flink,gyfora/flink,sunjincheng121/flink,zjureel/flink,xccui/flink,darionyaphet/flink,StephanEwen/incubator-flink,tzulitai/flink,rmetzger/flink,kl0u/flink,tillrohrmann/flink,darionyaphet/flink,gyfora/flink,zentol/flink,tony810430/flink,zjureel/flink,zentol/flink,wwjiang007/flink,rmetzger/flink,wwjiang007/flink,tillrohrmann/flink,rmetzger/flink,wwjiang007/flink,apache/flink,aljoscha/flink,aljoscha/flink,aljoscha/flink,apache/flink,tillrohrmann/flink,darionyaphet/flink,twalthr/flink,apache/flink,zentol/flink,lincoln-lil/flink,lincoln-lil/flink,gyfora/flink,kl0u/flink,greghogan/flink,godfreyhe/flink,tzulitai/flink,tzulitai/flink,apache/flink,twalthr/flink,tzulitai/flink,tzulitai/flink,zentol/flink,tillrohrmann/flink,sunjincheng121/flink,apache/flink,darionyaphet/flink,zjureel/flink,tony810430/flink,xccui/flink,clarkyzl/flink,clarkyzl/flink,gyfora/flink,greghogan/flink,greghogan/flink,tzulitai/flink,kl0u/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.tests.util.hbase;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.tests.util.TestUtils;
import org.apache.flink.tests.util.cache.DownloadCache;
import org.apache.flink.tests.util.categories.PreCommit;
import org.apache.flink.tests.util.categories.TravisGroup1;
import org.apache.flink.tests.util.flink.ClusterController;
import org.apache.flink.tests.util.flink.FlinkResource;
import org.apache.flink.tests.util.flink.FlinkResourceSetup;
import org.apache.flink.tests.util.flink.LocalStandaloneFlinkResourceFactory;
import org.apache.flink.tests.util.flink.SQLJobSubmission;
import org.apache.flink.testutils.junit.FailsOnJava11;
import org.apache.flink.util.FileUtils;
import org.apache.flink.util.TestLogger;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
/**
* End-to-end test for the HBase connectors.
*/
@Category(value = {TravisGroup1.class, PreCommit.class, FailsOnJava11.class})
public class SQLClientHBaseITCase extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(SQLClientHBaseITCase.class);
private static final String HBASE_E2E_SQL = "hbase_e2e.sql";
@Rule
public final HBaseResource hbase;
@Rule
public final FlinkResource flink = new LocalStandaloneFlinkResourceFactory()
.create(FlinkResourceSetup.builder().build());
@Rule
public final TemporaryFolder tmp = new TemporaryFolder();
@ClassRule
public static final DownloadCache DOWNLOAD_CACHE = DownloadCache.get();
private static final Path sqlToolBoxJar = TestUtils.getResource(".*SqlToolbox.jar");
private static final Path sqlConnectorHBaseJar = TestUtils.getResource(".*hbase.jar");
private static final Path hadoopClasspath = TestUtils.getResource(".*hadoop.classpath");
private List<Path> hadoopClasspathJars;
public SQLClientHBaseITCase() {
this.hbase = HBaseResource.get();
}
@Before
public void before() throws Exception {
DOWNLOAD_CACHE.before();
Path tmpPath = tmp.getRoot().toPath();
LOG.info("The current temporary path: {}", tmpPath);
// Prepare all hadoop jars to mock HADOOP_CLASSPATH, use hadoop.classpath which contains all hadoop jars
File hadoopClasspathFile = new File(hadoopClasspath.toAbsolutePath().toString());
if (!hadoopClasspathFile.exists()) {
throw new FileNotFoundException("File that contains hadoop classpath " + hadoopClasspath.toString()
+ " does not exist.");
}
String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile);
hadoopClasspathJars = Arrays.stream(classPathContent.split(":"))
.map(jar -> Paths.get(jar))
.collect(Collectors.toList());
}
@Test
public void testHBase() throws Exception {
try (ClusterController clusterController = flink.startCluster(2)) {
// Create table and put data
hbase.createTable("source", "family1", "family2");
hbase.createTable("sink", "family1", "family2");
hbase.putData("source", "row1", "family1", "f1c1", "v1");
hbase.putData("source", "row1", "family2", "f2c1", "v2");
hbase.putData("source", "row1", "family2", "f2c2", "v3");
hbase.putData("source", "row2", "family1", "f1c1", "v4");
hbase.putData("source", "row2", "family2", "f2c1", "v5");
hbase.putData("source", "row2", "family2", "f2c2", "v6");
// Initialize the SQL statements from "hbase_e2e.sql" file
List<String> sqlLines = initializeSqlLines();
// Execute SQL statements in "hbase_e2e.sql" file
executeSqlStatements(clusterController, sqlLines);
LOG.info("Verify the sink table result.");
// Wait until all the results flushed to the HBase sink table.
checkHBaseSinkResult();
LOG.info("The HBase SQL client test run successfully.");
}
}
private void checkHBaseSinkResult() throws Exception {
boolean success = false;
final Deadline deadline = Deadline.fromNow(Duration.ofSeconds(120));
while (deadline.hasTimeLeft()) {
final List<String> lines = hbase.scanTable("sink");
if (lines.size() == 6) {
success = true;
assertThat(
lines.toArray(new String[0]),
arrayContainingInAnyOrder(
CoreMatchers.allOf(containsString("row1"), containsString("family1"),
containsString("f1c1"), containsString("value1")),
CoreMatchers.allOf(containsString("row1"), containsString("family2"),
containsString("f2c1"), containsString("v2")),
CoreMatchers.allOf(containsString("row1"), containsString("family2"),
containsString("f2c2"), containsString("v3")),
CoreMatchers.allOf(containsString("row2"), containsString("family1"),
containsString("f1c1"), containsString("value4")),
CoreMatchers.allOf(containsString("row2"), containsString("family2"),
containsString("f2c1"), containsString("v5")),
CoreMatchers.allOf(containsString("row2"), containsString("family2"),
containsString("f2c2"), containsString("v6"))
)
);
break;
} else {
LOG.info("The HBase sink table does not contain enough records, current {} records, left time: {}s",
lines.size(), deadline.timeLeft().getSeconds());
}
Thread.sleep(500);
}
Assert.assertTrue("Did not get expected results before timeout.", success);
}
private List<String> initializeSqlLines() throws IOException {
URL url = SQLClientHBaseITCase.class.getClassLoader().getResource(HBASE_E2E_SQL);
if (url == null) {
throw new FileNotFoundException(HBASE_E2E_SQL);
}
return Files.readAllLines(new File(url.getFile()).toPath());
}
private void executeSqlStatements(ClusterController clusterController, List<String> sqlLines) throws IOException {
LOG.info("Executing SQL: HBase source table -> HBase sink table");
clusterController.submitSQLJob(new SQLJobSubmission.SQLJobSubmissionBuilder(sqlLines)
.addJar(sqlToolBoxJar)
.addJar(sqlConnectorHBaseJar)
.addJars(hadoopClasspathJars)
.build());
}
}
|
flink-end-to-end-tests/flink-end-to-end-tests-hbase/src/test/java/org/apache/flink/tests/util/hbase/SQLClientHBaseITCase.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.tests.util.hbase;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.tests.util.TestUtils;
import org.apache.flink.tests.util.cache.DownloadCache;
import org.apache.flink.tests.util.categories.PreCommit;
import org.apache.flink.tests.util.categories.TravisGroup1;
import org.apache.flink.tests.util.flink.ClusterController;
import org.apache.flink.tests.util.flink.FlinkResource;
import org.apache.flink.tests.util.flink.FlinkResourceSetup;
import org.apache.flink.tests.util.flink.LocalStandaloneFlinkResourceFactory;
import org.apache.flink.tests.util.flink.SQLJobSubmission;
import org.apache.flink.util.FileUtils;
import org.apache.flink.util.TestLogger;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
/**
* End-to-end test for the HBase connectors.
*/
@Category(value = {TravisGroup1.class, PreCommit.class})
public class SQLClientHBaseITCase extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(SQLClientHBaseITCase.class);
private static final String HBASE_E2E_SQL = "hbase_e2e.sql";
@Rule
public final HBaseResource hbase;
@Rule
public final FlinkResource flink = new LocalStandaloneFlinkResourceFactory()
.create(FlinkResourceSetup.builder().build());
@Rule
public final TemporaryFolder tmp = new TemporaryFolder();
@ClassRule
public static final DownloadCache DOWNLOAD_CACHE = DownloadCache.get();
private static final Path sqlToolBoxJar = TestUtils.getResource(".*SqlToolbox.jar");
private static final Path sqlConnectorHBaseJar = TestUtils.getResource(".*hbase.jar");
private static final Path hadoopClasspath = TestUtils.getResource(".*hadoop.classpath");
private List<Path> hadoopClasspathJars;
public SQLClientHBaseITCase() {
this.hbase = HBaseResource.get();
}
@Before
public void before() throws Exception {
DOWNLOAD_CACHE.before();
Path tmpPath = tmp.getRoot().toPath();
LOG.info("The current temporary path: {}", tmpPath);
// Prepare all hadoop jars to mock HADOOP_CLASSPATH, use hadoop.classpath which contains all hadoop jars
File hadoopClasspathFile = new File(hadoopClasspath.toAbsolutePath().toString());
if (!hadoopClasspathFile.exists()) {
throw new FileNotFoundException("File that contains hadoop classpath " + hadoopClasspath.toString()
+ " does not exist.");
}
String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile);
hadoopClasspathJars = Arrays.stream(classPathContent.split(":"))
.map(jar -> Paths.get(jar))
.collect(Collectors.toList());
}
@Test
public void testHBase() throws Exception {
try (ClusterController clusterController = flink.startCluster(2)) {
// Create table and put data
hbase.createTable("source", "family1", "family2");
hbase.createTable("sink", "family1", "family2");
hbase.putData("source", "row1", "family1", "f1c1", "v1");
hbase.putData("source", "row1", "family2", "f2c1", "v2");
hbase.putData("source", "row1", "family2", "f2c2", "v3");
hbase.putData("source", "row2", "family1", "f1c1", "v4");
hbase.putData("source", "row2", "family2", "f2c1", "v5");
hbase.putData("source", "row2", "family2", "f2c2", "v6");
// Initialize the SQL statements from "hbase_e2e.sql" file
List<String> sqlLines = initializeSqlLines();
// Execute SQL statements in "hbase_e2e.sql" file
executeSqlStatements(clusterController, sqlLines);
LOG.info("Verify the sink table result.");
// Wait until all the results flushed to the HBase sink table.
checkHBaseSinkResult();
LOG.info("The HBase SQL client test run successfully.");
}
}
private void checkHBaseSinkResult() throws Exception {
boolean success = false;
final Deadline deadline = Deadline.fromNow(Duration.ofSeconds(120));
while (deadline.hasTimeLeft()) {
final List<String> lines = hbase.scanTable("sink");
if (lines.size() == 6) {
success = true;
assertThat(
lines.toArray(new String[0]),
arrayContainingInAnyOrder(
CoreMatchers.allOf(containsString("row1"), containsString("family1"),
containsString("f1c1"), containsString("value1")),
CoreMatchers.allOf(containsString("row1"), containsString("family2"),
containsString("f2c1"), containsString("v2")),
CoreMatchers.allOf(containsString("row1"), containsString("family2"),
containsString("f2c2"), containsString("v3")),
CoreMatchers.allOf(containsString("row2"), containsString("family1"),
containsString("f1c1"), containsString("value4")),
CoreMatchers.allOf(containsString("row2"), containsString("family2"),
containsString("f2c1"), containsString("v5")),
CoreMatchers.allOf(containsString("row2"), containsString("family2"),
containsString("f2c2"), containsString("v6"))
)
);
break;
} else {
LOG.info("The HBase sink table does not contain enough records, current {} records, left time: {}s",
lines.size(), deadline.timeLeft().getSeconds());
}
Thread.sleep(500);
}
Assert.assertTrue("Did not get expected results before timeout.", success);
}
private List<String> initializeSqlLines() throws IOException {
URL url = SQLClientHBaseITCase.class.getClassLoader().getResource(HBASE_E2E_SQL);
if (url == null) {
throw new FileNotFoundException(HBASE_E2E_SQL);
}
return Files.readAllLines(new File(url.getFile()).toPath());
}
private void executeSqlStatements(ClusterController clusterController, List<String> sqlLines) throws IOException {
LOG.info("Executing SQL: HBase source table -> HBase sink table");
clusterController.submitSQLJob(new SQLJobSubmission.SQLJobSubmissionBuilder(sqlLines)
.addJar(sqlToolBoxJar)
.addJar(sqlConnectorHBaseJar)
.addJars(hadoopClasspathJars)
.build());
}
}
|
[FLINK-18420][tests] Disable failed test SQLClientHBaseITCase in java 11
This closes #12760
|
flink-end-to-end-tests/flink-end-to-end-tests-hbase/src/test/java/org/apache/flink/tests/util/hbase/SQLClientHBaseITCase.java
|
[FLINK-18420][tests] Disable failed test SQLClientHBaseITCase in java 11
|
|
Java
|
apache-2.0
|
4833d036a621cbdf7e762b0d82a7322284f6d713
| 0
|
jimengliu/cattle,kaos/cattle,cloudnautique/cattle,cloudnautique/cattle,cjellick/cattle,rancher/cattle,vincent99/cattle,kaos/cattle,cjellick/cattle,rancherio/cattle,vincent99/cattle,cloudnautique/cattle,vincent99/cattle,rancherio/cattle,cjellick/cattle,cjellick/cattle,wlan0/cattle,cloudnautique/cattle,rancherio/cattle,wlan0/cattle,jimengliu/cattle,wlan0/cattle,Cerfoglg/cattle,Cerfoglg/cattle,jimengliu/cattle,Cerfoglg/cattle,kaos/cattle,rancher/cattle,rancher/cattle
|
package io.cattle.platform.agent.instance.service.impl;
import static io.cattle.platform.core.model.tables.HealthcheckInstanceHostMapTable.HEALTHCHECK_INSTANCE_HOST_MAP;
import static io.cattle.platform.core.model.tables.HealthcheckInstanceTable.HEALTHCHECK_INSTANCE;
import static io.cattle.platform.core.model.tables.NicTable.NIC;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.model.HealthcheckInstanceHostMap;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.tables.records.NicRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import java.util.List;
public class HealthcheckInstanceHostMapNicLookup extends AbstractJooqDao implements InstanceNicLookup {
@Override
public List<? extends Nic> getNics(Object obj) {
if (!(obj instanceof HealthcheckInstanceHostMap)) {
return null;
}
HealthcheckInstanceHostMap hostMap = (HealthcheckInstanceHostMap) obj;
return create()
.select(NIC.fields())
.from(NIC)
.join(HEALTHCHECK_INSTANCE)
.on(HEALTHCHECK_INSTANCE.INSTANCE_ID.eq(NIC.INSTANCE_ID))
.join(HEALTHCHECK_INSTANCE_HOST_MAP)
.on(HEALTHCHECK_INSTANCE_HOST_MAP.HEALTHCHECK_INSTANCE_ID.eq(HEALTHCHECK_INSTANCE.ID))
.where(HEALTHCHECK_INSTANCE_HOST_MAP.HOST_ID.eq(hostMap.getHostId())
.and(NIC.REMOVED.isNull())
.and(HEALTHCHECK_INSTANCE_HOST_MAP.REMOVED.isNull())
.and(HEALTHCHECK_INSTANCE.REMOVED.isNull())).limit(1)
.fetchInto(NicRecord.class);
}
}
|
code/iaas/agent-instance/src/main/java/io/cattle/platform/agent/instance/service/impl/HealthcheckInstanceHostMapNicLookup.java
|
package io.cattle.platform.agent.instance.service.impl;
import static io.cattle.platform.core.model.tables.HealthcheckInstanceHostMapTable.HEALTHCHECK_INSTANCE_HOST_MAP;
import static io.cattle.platform.core.model.tables.HealthcheckInstanceTable.HEALTHCHECK_INSTANCE;
import static io.cattle.platform.core.model.tables.NicTable.NIC;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.model.HealthcheckInstanceHostMap;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.tables.records.NicRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import java.util.List;
public class HealthcheckInstanceHostMapNicLookup extends AbstractJooqDao implements InstanceNicLookup {
@Override
public List<? extends Nic> getNics(Object obj) {
if (!(obj instanceof HealthcheckInstanceHostMap)) {
return null;
}
HealthcheckInstanceHostMap hostMap = (HealthcheckInstanceHostMap) obj;
return create()
.select(NIC.fields())
.from(NIC)
.join(HEALTHCHECK_INSTANCE)
.on(HEALTHCHECK_INSTANCE.INSTANCE_ID.eq(NIC.INSTANCE_ID))
.join(HEALTHCHECK_INSTANCE_HOST_MAP)
.on(HEALTHCHECK_INSTANCE_HOST_MAP.HEALTHCHECK_INSTANCE_ID.eq(HEALTHCHECK_INSTANCE.ID))
.where(HEALTHCHECK_INSTANCE_HOST_MAP.HOST_ID.eq(hostMap.getHostId())
.and(NIC.REMOVED.isNull())
.and(HEALTHCHECK_INSTANCE_HOST_MAP.REMOVED.isNull())
.and(HEALTHCHECK_INSTANCE.REMOVED.isNull()))
.fetchInto(NicRecord.class);
}
}
|
healthhostmap.create config update: get only one nic from the host
as one nic is enough to trigger the config update
|
code/iaas/agent-instance/src/main/java/io/cattle/platform/agent/instance/service/impl/HealthcheckInstanceHostMapNicLookup.java
|
healthhostmap.create config update: get only one nic from the host
|
|
Java
|
bsd-2-clause
|
401fd29f0fc658220987838873692bce4abf7838
| 0
|
forkch/scrabble_ar,forkch/scrabble_ar,forkch/scrabble_ar,forkch/scrabble_ar,forkch/scrabble_ar,forkch/scrabble_ar
|
package ch.zuehlke.arscrabble.jmonkey;
import android.util.Log;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Quad;
import com.jme3.texture.Image;
import com.jme3.texture.Texture2D;
import com.qualcomm.vuforia.CameraDevice;
import com.qualcomm.vuforia.Frame;
import com.qualcomm.vuforia.PIXEL_FORMAT;
import com.qualcomm.vuforia.Renderer;
import com.qualcomm.vuforia.State;
import com.qualcomm.vuforia.Vec2I;
import com.qualcomm.vuforia.VideoBackgroundConfig;
import com.qualcomm.vuforia.VideoMode;
import com.qualcomm.vuforia.Vuforia;
import java.nio.ByteBuffer;
/**
* Created by ssh on 25.11.2014.
*/
public class JMonkeyApplication extends SimpleApplication implements Vuforia.UpdateCallbackInterface {
private Camera backgroundCamera;
private Material backgroundCameraMaterial;
private Texture2D backgroundCameraTexture;
private Spatial backgroundCameraGeometry;
private Image backgroundCameraImage;
private ByteBuffer backgroundImageBuffer;
private boolean hasBackgroundImage;
@Override
public void simpleInitApp() {
// We use custom viewports - so the main viewport does not need to contain the rootNode
viewPort.detachScene(rootNode);
initializeImageBuffer();
initBackground();
CameraDevice cameraDevice = CameraDevice.getInstance();
cameraDevice.init(CameraDevice.CAMERA.CAMERA_DEFAULT);
CameraDevice.getInstance().start();
VideoMode vm = cameraDevice.getVideoMode(CameraDevice.MODE.MODE_OPTIMIZE_SPEED);
VideoBackgroundConfig config = new VideoBackgroundConfig();
config.setEnabled(true);
config.setSynchronous(true);
config.setPosition(new Vec2I(0, 0));
int xSize = 0, ySize = 0;
if (false) {
xSize = (int) (vm.getHeight() * (settings.getHeight() / (float) vm.getWidth()));
ySize = settings.getHeight();
if (xSize < settings.getWidth()) {
xSize = settings.getWidth();
ySize = (int) (settings.getWidth() * (vm.getWidth() / (float) vm.getHeight()));
}
} else {
xSize = settings.getWidth();
ySize = (int) (vm.getHeight() * (settings.getWidth() / (float) vm.getWidth()));
if (ySize < settings.getHeight()) {
xSize = (int) (settings.getHeight() * (vm.getWidth() / (float) vm.getHeight()));
ySize = settings.getHeight();
}
}
config.setSize(new Vec2I(xSize, ySize));
Renderer.getInstance().setVideoBackgroundConfig(config);
Vuforia.setFrameFormat(PIXEL_FORMAT.RGB888, true);
Vuforia.registerCallback(this);
}
@Override
public void simpleUpdate(float tpf) {
if (hasBackgroundImage) {
backgroundCameraTexture.setImage(backgroundCameraImage);
backgroundCameraMaterial.setTexture("ColorMap", backgroundCameraTexture);
}
// TODO: WTF? Why we need this method? Crash without...
backgroundCameraGeometry.updateLogicalState(tpf);
backgroundCameraGeometry.updateGeometricState();
}
private void initBackground() {
int width = settings.getWidth();
int height = settings.getHeight();
// Create a Quad shape.
Quad videoBGQuad = new Quad(1, 1, true);
// Create a Geometry with the Quad shape
backgroundCameraGeometry = new Geometry("quad", videoBGQuad);
float newWidth = 1.f * width / height;
// Center the Geometry in the middle of the screen.
backgroundCameraGeometry.setLocalTranslation(-0.5f * newWidth, -0.5f, 0.f);
// Scale (stretch) the width of the Geometry to cover the whole screen
// width.
backgroundCameraGeometry.setLocalScale(1.f * newWidth, 1.f, 1);
// Apply a unshaded material which we will use for texturing.
backgroundCameraMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
backgroundCameraGeometry.setMaterial(backgroundCameraMaterial);
// Create a new texture which will hold the Android camera preview frame
// pixels.
backgroundCameraTexture = new Texture2D();
// Create a custom virtual camera with orthographic projection
backgroundCamera = new Camera(width, height);
backgroundCamera.setViewPort(0.0f, 1.0f, 0.f, 1.0f);
backgroundCamera.setLocation(new Vector3f(0f, 0f, 1.f));
backgroundCamera.setAxes(new Vector3f(-1f, 0f, 0f), new Vector3f(0f, 1f, 0f), new Vector3f(0f, 0f, -1f));
backgroundCamera.setParallelProjection(true);
// Also create a custom viewport.
ViewPort videoBackgroundViewPort = renderManager.createMainView("VideoBGView", backgroundCamera);
// Attach the geometry representing the video background to the viewport.
videoBackgroundViewPort.attachScene(backgroundCameraGeometry);
//videoBGVP.setClearFlags(true, false, false);
//videoBGVP.setBackgroundColor(new ColorRGBA(1,0,0,1));
}
public void initializeImageBuffer() {
int width = settings.getWidth();
int height = settings.getHeight();
int bufferSizeR = 640 * 480 * 24;
byte[] previewBufferSize = null;
previewBufferSize = new byte[bufferSizeR];
backgroundImageBuffer = ByteBuffer.allocateDirect(previewBufferSize.length);
backgroundCameraImage = new Image(Image.Format.RGB8, 640, 480, backgroundImageBuffer);
backgroundImageBuffer.clear();
}
@Override
public void QCAR_onUpdate(State state) {
com.qualcomm.vuforia.Image image = null;
Frame frame = state.getFrame();
for (int tIdx = 0; tIdx < frame.getNumImages(); tIdx++) {
com.qualcomm.vuforia.Image vuforiaImage = frame.getImage(tIdx);
if (vuforiaImage.getFormat() == PIXEL_FORMAT.RGB888) {
image = vuforiaImage;
break;
}
}
if (image != null && !alreadyDone) {
ByteBuffer pixels = image.getPixels();
byte[] pixelArray = new byte[pixels.remaining()];
pixels.get(pixelArray, 0, pixelArray.length);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
int stride = image.getStride();
Log.i("Image", "Image width: " + imageWidth);
Log.i("Image", "Image height: " + imageHeight);
Log.i("Image", "Image height: " + imageHeight);
Log.i("Image", "Image stride: " + stride);
Log.i("Image", "First pixel byte: " + pixelArray[0]);
backgroundImageBuffer.clear();
backgroundImageBuffer.put(pixelArray);
backgroundCameraImage.setData(backgroundImageBuffer);
hasBackgroundImage = true;
}
}
private boolean alreadyDone = false;
}
|
ArScrabble/app/src/main/java/ch/zuehlke/arscrabble/jmonkey/JMonkeyApplication.java
|
package ch.zuehlke.arscrabble.jmonkey;
import android.util.Log;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Quad;
import com.jme3.texture.Image;
import com.jme3.texture.Texture2D;
import com.qualcomm.QCAR.QCAR;
import com.qualcomm.vuforia.CameraDevice;
import com.qualcomm.vuforia.Frame;
import com.qualcomm.vuforia.PIXEL_FORMAT;
import com.qualcomm.vuforia.Renderer;
import com.qualcomm.vuforia.State;
import com.qualcomm.vuforia.Vec2I;
import com.qualcomm.vuforia.VideoBackgroundConfig;
import com.qualcomm.vuforia.VideoMode;
import com.qualcomm.vuforia.Vuforia;
import java.nio.ByteBuffer;
/**
* Created by ssh on 25.11.2014.
*/
public class JMonkeyApplication extends SimpleApplication implements Vuforia.UpdateCallbackInterface {
private Camera backgroundCamera;
private Material backgroundCameraMaterial;
private Texture2D backgroundCameraTexture;
private Spatial backgroundCameraGeometry;
private Image backgroundCameraImage;
private ByteBuffer backgroundImageBuffer;
private boolean hasBackgroundImage;
@Override
public void simpleInitApp() {
// We use custom viewports - so the main viewport does not need to contain the rootNode
viewPort.detachScene(rootNode);
initializeImageBuffer();
initBackground();
CameraDevice cameraDevice = CameraDevice.getInstance();
cameraDevice.init(CameraDevice.CAMERA.CAMERA_DEFAULT);
CameraDevice.getInstance().start();
VideoMode vm = cameraDevice.getVideoMode(CameraDevice.MODE.MODE_DEFAULT);
VideoBackgroundConfig config = new VideoBackgroundConfig();
config.setEnabled(true);
config.setSynchronous(true);
config.setPosition(new Vec2I(0, 0));
int xSize = 0, ySize = 0;
if (false) {
xSize = (int) (vm.getHeight() * (settings.getHeight() / (float) vm.getWidth()));
ySize = settings.getHeight();
if (xSize < settings.getWidth()) {
xSize = settings.getWidth();
ySize = (int) (settings.getWidth() * (vm.getWidth() / (float) vm.getHeight()));
}
} else {
xSize = settings.getWidth();
ySize = (int) (vm.getHeight() * (settings.getWidth() / (float) vm.getWidth()));
if (ySize < settings.getHeight()) {
xSize = (int) (settings.getHeight() * (vm.getWidth() / (float) vm.getHeight()));
ySize = settings.getHeight();
}
}
config.setSize(new Vec2I(xSize, ySize));
Renderer.getInstance().setVideoBackgroundConfig(config);
Vuforia.setFrameFormat(PIXEL_FORMAT.RGB888, true);
Vuforia.registerCallback(this);
}
@Override
public void simpleUpdate(float tpf) {
if (hasBackgroundImage) {
backgroundCameraTexture.setImage(backgroundCameraImage);
backgroundCameraMaterial.setTexture("ColorMap", backgroundCameraTexture);
}
// TODO: WTF? Why we need this method? Crash without...
backgroundCameraGeometry.updateLogicalState(tpf);
backgroundCameraGeometry.updateGeometricState();
}
private void initBackground() {
int width = settings.getWidth();
int height = settings.getHeight();
// Create a Quad shape.
Quad videoBGQuad = new Quad(1, 1, true);
// Create a Geometry with the Quad shape
backgroundCameraGeometry = new Geometry("quad", videoBGQuad);
float newWidth = 1.f * width / height;
// Center the Geometry in the middle of the screen.
backgroundCameraGeometry.setLocalTranslation(-0.5f * newWidth, -0.5f, 0.f);
// Scale (stretch) the width of the Geometry to cover the whole screen
// width.
backgroundCameraGeometry.setLocalScale(1.f * newWidth, 1.f, 1);
// Apply a unshaded material which we will use for texturing.
backgroundCameraMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
backgroundCameraGeometry.setMaterial(backgroundCameraMaterial);
// Create a new texture which will hold the Android camera preview frame
// pixels.
backgroundCameraTexture = new Texture2D();
// Create a custom virtual camera with orthographic projection
backgroundCamera = new Camera(width, height);
backgroundCamera.setViewPort(0.0f, 1.0f, 0.f, 1.0f);
backgroundCamera.setLocation(new Vector3f(0f, 0f, 1.f));
backgroundCamera.setAxes(new Vector3f(-1f, 0f, 0f), new Vector3f(0f, 1f, 0f), new Vector3f(0f, 0f, -1f));
backgroundCamera.setParallelProjection(true);
// Also create a custom viewport.
ViewPort videoBackgroundViewPort = renderManager.createMainView("VideoBGView", backgroundCamera);
// Attach the geometry representing the video background to the viewport.
videoBackgroundViewPort.attachScene(backgroundCameraGeometry);
//videoBGVP.setClearFlags(true, false, false);
//videoBGVP.setBackgroundColor(new ColorRGBA(1,0,0,1));
}
public void initializeImageBuffer() {
int width = settings.getWidth();
int height = settings.getHeight();
int bufferSizeRGB565 = width * height * 2 + 4096;
byte[] mPreviewBufferRGB656 = null;
mPreviewBufferRGB656 = new byte[bufferSizeRGB565];
backgroundImageBuffer = ByteBuffer.allocateDirect(mPreviewBufferRGB656.length);
backgroundCameraImage = new Image(Image.Format.RGB8, width, height, backgroundImageBuffer);
backgroundImageBuffer.clear();
}
@Override
public void QCAR_onUpdate(State state) {
com.qualcomm.vuforia.Image imageRGB565 = null;
Frame frame = state.getFrame();
for (int tIdx = 0; tIdx < frame.getNumImages(); tIdx++) {
com.qualcomm.vuforia.Image image = frame.getImage(tIdx);
if (image.getFormat() == PIXEL_FORMAT.RGB888) {
imageRGB565 = image;
break;
}
}
if (imageRGB565 != null && !alreadyDone) {
ByteBuffer pixels = imageRGB565.getPixels();
byte[] pixelArray = new byte[pixels.remaining()];
pixels.get(pixelArray, 0, pixelArray.length);
int imageWidth = imageRGB565.getWidth();
int imageHeight = imageRGB565.getHeight();
int stride = imageRGB565.getStride();
Log.i("Image", "Image width: " + imageWidth);
Log.i("Image", "Image height: " + imageHeight);
Log.i("Image", "Image stride: " + stride);
Log.i("Image", "First pixel byte: " + pixelArray[0]);
backgroundImageBuffer.clear();
backgroundImageBuffer.put(pixelArray);
backgroundCameraImage.setData(backgroundImageBuffer);
hasBackgroundImage = true;
}
}
private boolean alreadyDone = false;
}
|
Show camera in JME view
|
ArScrabble/app/src/main/java/ch/zuehlke/arscrabble/jmonkey/JMonkeyApplication.java
|
Show camera in JME view
|
|
Java
|
bsd-2-clause
|
39983deec322cb78076fe0b521eb92db1588a1d0
| 0
|
octavianiLocator/g3m,AeroGlass/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m,octavianiLocator/g3m
|
package org.glob3.mobile.generated;
//
// LayerTilesRenderParameters.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/25/13.
//
//
//
// LayerTilesRenderParameters.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/25/13.
//
//
public class LayerTilesRenderParameters
{
public final Sector _topSector ;
public final int _topSectorSplitsByLatitude;
public final int _topSectorSplitsByLongitude;
public final int _firstLevel;
public final int _maxLevel;
public final int _maxLevelForPoles;
public final Vector2I _tileTextureResolution;
public final Vector2I _tileMeshResolution;
public final boolean _mercator;
public LayerTilesRenderParameters(Sector topSector, int topSectorSplitsByLatitude, int topSectorSplitsByLongitude, int firstLevel, int maxLevel, Vector2I tileTextureResolution, Vector2I tileMeshResolution, boolean mercator)
{
_topSector = new Sector(topSector);
_topSectorSplitsByLatitude = topSectorSplitsByLatitude;
_topSectorSplitsByLongitude = topSectorSplitsByLongitude;
_firstLevel = firstLevel;
_maxLevel = maxLevel;
_maxLevelForPoles = 4;
_tileTextureResolution = tileTextureResolution;
_tileMeshResolution = tileMeshResolution;
_mercator = mercator;
}
public static Vector2I defaultTileMeshResolution()
{
return new Vector2I(16, 16);
}
public static Vector2I defaultTileTextureResolution ()
{
return new Vector2I(256, 256);
}
public static LayerTilesRenderParameters createDefaultNonMercator(Sector topSector)
{
final int topSectorSplitsByLatitude = 2;
final int topSectorSplitsByLongitude = 4;
final int firstLevel = 0;
final int maxLevel = 17;
final boolean mercator = false;
return new LayerTilesRenderParameters(topSector, topSectorSplitsByLatitude, topSectorSplitsByLongitude, firstLevel, maxLevel, LayerTilesRenderParameters.defaultTileTextureResolution(), LayerTilesRenderParameters.defaultTileMeshResolution(), mercator);
}
public static LayerTilesRenderParameters createDefaultMercator(int firstLevel, int maxLevel)
{
final Sector topSector = Sector.fullSphere();
final int topSectorSplitsByLatitude = 1;
final int topSectorSplitsByLongitude = 1;
final boolean mercator = true;
return new LayerTilesRenderParameters(topSector, topSectorSplitsByLatitude, topSectorSplitsByLongitude, firstLevel, maxLevel, LayerTilesRenderParameters.defaultTileTextureResolution(), LayerTilesRenderParameters.defaultTileMeshResolution(), mercator);
}
public void dispose()
{
}
}
|
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/LayerTilesRenderParameters.java
|
package org.glob3.mobile.generated;
//
// LayerTilesRenderParameters.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/25/13.
//
//
//
// LayerTilesRenderParameters.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 2/25/13.
//
//
public class LayerTilesRenderParameters
{
public final Sector _topSector ;
public final int _topSectorSplitsByLatitude;
public final int _topSectorSplitsByLongitude;
public final int _firstLevel;
public final int _maxLevel;
public final int _maxLevelForPoles;
public final Vector2I _tileTextureResolution;
public final Vector2I _tileMeshResolution;
public final boolean _mercator;
public LayerTilesRenderParameters(Sector topSector, int topSectorSplitsByLatitude, int topSectorSplitsByLongitude, int firstLevel, int maxLevel, Vector2I tileTextureResolution, Vector2I tileMeshResolution, boolean mercator)
{
_topSector = new Sector(topSector);
_topSectorSplitsByLatitude = topSectorSplitsByLatitude;
_topSectorSplitsByLongitude = topSectorSplitsByLongitude;
_firstLevel = firstLevel;
_maxLevel = maxLevel;
_maxLevelForPoles = 4;
_tileTextureResolution = tileTextureResolution;
_tileMeshResolution = tileMeshResolution;
_mercator = mercator;
}
public static Vector2I defaultTileMeshResolution()
{
return new Vector2I(20, 20);
}
public static Vector2I defaultTileTextureResolution ()
{
return new Vector2I(256, 256);
}
public static LayerTilesRenderParameters createDefaultNonMercator(Sector topSector)
{
final int topSectorSplitsByLatitude = 2;
final int topSectorSplitsByLongitude = 4;
final int firstLevel = 0;
final int maxLevel = 17;
final boolean mercator = false;
return new LayerTilesRenderParameters(topSector, topSectorSplitsByLatitude, topSectorSplitsByLongitude, firstLevel, maxLevel, LayerTilesRenderParameters.defaultTileTextureResolution(), LayerTilesRenderParameters.defaultTileMeshResolution(), mercator);
}
public static LayerTilesRenderParameters createDefaultMercator(int firstLevel, int maxLevel)
{
final Sector topSector = Sector.fullSphere();
final int topSectorSplitsByLatitude = 1;
final int topSectorSplitsByLongitude = 1;
final boolean mercator = true;
return new LayerTilesRenderParameters(topSector, topSectorSplitsByLatitude, topSectorSplitsByLongitude, firstLevel, maxLevel, LayerTilesRenderParameters.defaultTileTextureResolution(), LayerTilesRenderParameters.defaultTileMeshResolution(), mercator);
}
public void dispose()
{
}
}
|
Generated
|
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/LayerTilesRenderParameters.java
|
Generated
|
|
Java
|
bsd-3-clause
|
e58a1d35bc4b380fef3a6dcfcad0872c7513a102
| 0
|
mattunderscorechampion/tcProxy
|
/* Copyright © 2015 Matthew Champion
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 mattunderscore.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 MATTHEW CHAMPION 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.mattunderscore.tcproxy.proxy.selector;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.ClosedChannelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mattunderscore.tcproxy.io.data.CircularBuffer;
import com.mattunderscore.tcproxy.io.socket.IOSocketChannel;
import com.mattunderscore.tcproxy.proxy.ConnectionImpl;
import com.mattunderscore.tcproxy.proxy.action.Close;
import com.mattunderscore.tcproxy.proxy.action.Write;
import com.mattunderscore.tcproxy.proxy.action.queue.ActionQueue;
import com.mattunderscore.tcproxy.proxy.connection.Connection;
import com.mattunderscore.tcproxy.proxy.direction.Direction;
import com.mattunderscore.tcproxy.selector.SelectionRunnable;
import com.mattunderscore.tcproxy.selector.general.RegistrationHandle;
/**
* Proxy read task.
* @author Matt Champion on 18/11/2015
*/
public final class ReadSelectionRunnable implements SelectionRunnable<IOSocketChannel> {
private static final Logger DATA_LOG = LoggerFactory.getLogger("proxy-data-read");
private static final Logger LOG = LoggerFactory.getLogger("reader");
private final Direction direction;
private final Connection connection;
private final CircularBuffer readBuffer;
public ReadSelectionRunnable(Direction direction, Connection connection, CircularBuffer readBuffer) {
this.direction = direction;
this.connection = connection;
this.readBuffer = readBuffer;
}
@Override
public void run(IOSocketChannel socket, RegistrationHandle handle) {
if (!handle.isValid()) {
LOG.warn("{} : Selected key no longer valid, closing connection", this);
try {
connection.close();
}
catch (IOException e) {
LOG.warn("{} : Error closing connection", this, e);
}
}
else if (handle.isReadable()) {
final ActionQueue queue = direction.getQueue();
if (!queue.queueFull()) {
final ByteChannel channel = direction.getFrom();
try {
assert readBuffer.usedCapacity() == 0 : "The read buffer should be empty";
// Read data in
final int bytes = direction.read(readBuffer);
if (bytes > 0) {
// Copy the data read to a write buffer and prepare for the next read
final ByteBuffer writeBuffer = ByteBuffer.allocate(readBuffer.usedCapacity());
readBuffer.get(writeBuffer);
writeBuffer.flip();
if (DATA_LOG.isInfoEnabled()) {
final int position = writeBuffer.position();
writeBuffer.position(0);
// Read data into byte array
final byte[] readBytes = new byte[writeBuffer.remaining()];
writeBuffer.get(readBytes);
// Log read data
DATA_LOG.trace("{} data: {}", direction, new String(readBytes));
// Return to initial position
writeBuffer.position(position);
}
direction.getProcessor().process(new Write(direction, writeBuffer));
assert readBuffer.usedCapacity() == 0 : "The read buffer should have been completely drained";
}
else if (bytes == -1) {
// Close the connection
handle.cancel();
direction.getProcessor().process(new Close(direction));
final ConnectionImpl conn = (ConnectionImpl) connection;
final Direction otherDirection = conn.otherDirection(direction);
LOG.debug("{} : Closed {} ", this, otherDirection);
otherDirection.close();
}
}
catch (final ClosedChannelException e) {
LOG.debug("{} : Channel {} already closed", this, channel);
handle.cancel();
}
catch (final IOException e) {
LOG.debug("{} : Error on channel {}, {}", this, channel, handle, e);
}
}
}
else {
LOG.warn("{} : Unexpected key state {}", this, handle);
}
}
}
|
tcProxy-proxy/src/main/java/com/mattunderscore/tcproxy/proxy/selector/ReadSelectionRunnable.java
|
/* Copyright © 2015 Matthew Champion
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 mattunderscore.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 MATTHEW CHAMPION 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.mattunderscore.tcproxy.proxy.selector;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.ClosedChannelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mattunderscore.tcproxy.io.data.CircularBuffer;
import com.mattunderscore.tcproxy.io.socket.IOSocketChannel;
import com.mattunderscore.tcproxy.proxy.ConnectionImpl;
import com.mattunderscore.tcproxy.proxy.action.Close;
import com.mattunderscore.tcproxy.proxy.action.Write;
import com.mattunderscore.tcproxy.proxy.action.queue.ActionQueue;
import com.mattunderscore.tcproxy.proxy.connection.Connection;
import com.mattunderscore.tcproxy.proxy.direction.Direction;
import com.mattunderscore.tcproxy.selector.SelectionRunnable;
import com.mattunderscore.tcproxy.selector.general.RegistrationHandle;
/**
* Proxy read task.
* @author Matt Champion on 18/11/2015
*/
public final class ReadSelectionRunnable implements SelectionRunnable<IOSocketChannel> {
private static final Logger DATA_LOG = LoggerFactory.getLogger("proxy-data-read");
private static final Logger LOG = LoggerFactory.getLogger("reader");
private final Direction direction;
private final Connection connection;
private final CircularBuffer readBuffer;
public ReadSelectionRunnable(Direction direction, Connection connection, CircularBuffer readBuffer) {
this.direction = direction;
this.connection = connection;
this.readBuffer = readBuffer;
}
@Override
public void run(IOSocketChannel socket, RegistrationHandle handle) {
if (!handle.isValid()) {
LOG.warn("{} : Selected key no longer valid, closing connection", this);
try {
connection.close();
}
catch (IOException e) {
LOG.warn("{} : Error closing connection", this, e);
}
}
else if (handle.isReadable()) {
final ActionQueue queue = direction.getQueue();
if (!queue.queueFull()) {
final ByteChannel channel = direction.getFrom();
try {
// Read data in
final int bytes = direction.read(readBuffer);
if (bytes > 0) {
// Copy the data read to a write buffer and prepare for the next read
final ByteBuffer writeBuffer = ByteBuffer.allocate(readBuffer.usedCapacity());
readBuffer.get(writeBuffer);
writeBuffer.flip();
if (DATA_LOG.isInfoEnabled()) {
final int position = writeBuffer.position();
writeBuffer.position(0);
// Read data into byte array
final byte[] readBytes = new byte[writeBuffer.remaining()];
writeBuffer.get(readBytes);
// Log read data
DATA_LOG.trace("{} data: {}", direction, new String(readBytes));
// Return to initial position
writeBuffer.position(position);
}
direction.getProcessor().process(new Write(direction, writeBuffer));
}
else if (bytes == -1) {
// Close the connection
handle.cancel();
direction.getProcessor().process(new Close(direction));
final ConnectionImpl conn = (ConnectionImpl) connection;
final Direction otherDirection = conn.otherDirection(direction);
LOG.debug("{} : Closed {} ", this, otherDirection);
otherDirection.close();
}
}
catch (final ClosedChannelException e) {
LOG.debug("{} : Channel {} already closed", this, channel);
handle.cancel();
}
catch (final IOException e) {
LOG.debug("{} : Error on channel {}, {}", this, channel, handle, e);
}
}
}
else {
LOG.warn("{} : Unexpected key state {}", this, handle);
}
}
}
|
Added assertions around the read buffer.
|
tcProxy-proxy/src/main/java/com/mattunderscore/tcproxy/proxy/selector/ReadSelectionRunnable.java
|
Added assertions around the read buffer.
|
|
Java
|
mit
|
e9135cf85baf5a65a1844685b8b1afe93fa9bf91
| 0
|
roblabla/BungeeBan
|
package net.craftminecraft.bungee.bungeeban.listener;
import com.google.common.eventbus.Subscribe;
import net.craftminecraft.bungee.bungeeban.BanManager;
import net.craftminecraft.bungee.bungeeban.BungeeBan;
import net.craftminecraft.bungee.bungeeban.banstore.BanEntry;
import net.craftminecraft.bungee.bungeeban.util.Utils;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.plugin.Listener;
public class ProxiedPlayerListener implements Listener {
private BungeeBan plugin;
public ProxiedPlayerListener(BungeeBan plugin) {
this.plugin = plugin;
}
@Subscribe
public void onPlayerJoin(final LoginEvent e) {
e.registerIntent(plugin);
plugin.getProxy().getScheduler().runAsync(plugin, new Runnable() {
@Override
public void run() {
BanEntry ban = BanManager.getBan(e.getConnection().getName(), "(GLOBAL)");
if (ban != null) {
e.setCancelled(true);
e.setCancelReason(Utils.formatMessage(ban.getReason(), ban));
}
ban = BanManager.getBan(e.getConnection().getAddress().getAddress().getHostAddress(), "(GLOBAL)");
if (ban != null) {
e.setCancelled(true);
e.setCancelReason(Utils.formatMessage(ban.getReason(), ban));
}
e.completeIntent(plugin);
}
});
}
@Subscribe
public void onServerConnect(ServerConnectEvent e) {
BanEntry ban = BanManager.getBan(e.getPlayer().getName(), e.getTarget().getName());
if (ban != null) {
// Ugly workaround the player joined... player left messages
Server srv = e.getPlayer().getServer();
if (srv != null)
e.setTarget(srv.getInfo());
e.getPlayer().disconnect(Utils.formatMessage(ban.getReason(), ban));
return;
}
ban = BanManager.getBan(e.getPlayer().getAddress().getAddress().getHostAddress(), e.getTarget().getName());
if (ban != null) {
// Ugly workaround the player joined... player left messages
Server srv = e.getPlayer().getServer();
if (srv != null)
e.setTarget(srv.getInfo());
e.getPlayer().disconnect(Utils.formatMessage(ban.getReason(), ban));
}
return;
}
}
|
src/main/java/net/craftminecraft/bungee/bungeeban/listener/ProxiedPlayerListener.java
|
package net.craftminecraft.bungee.bungeeban.listener;
import com.google.common.eventbus.Subscribe;
import net.craftminecraft.bungee.bungeeban.BanManager;
import net.craftminecraft.bungee.bungeeban.BungeeBan;
import net.craftminecraft.bungee.bungeeban.banstore.BanEntry;
import net.craftminecraft.bungee.bungeeban.util.Utils;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.plugin.Listener;
public class ProxiedPlayerListener implements Listener {
private BungeeBan plugin;
public ProxiedPlayerListener(BungeeBan plugin) {
this.plugin = plugin;
}
@Subscribe
public void onPlayerJoin(final LoginEvent e) {
e.registerIntent(plugin);
plugin.getProxy().getScheduler().runAsync(plugin, new Runnable() {
@Override
public void run() {
BanEntry ban = BanManager.getBan(e.getConnection().getName(), "(GLOBAL)");
if (ban != null) {
e.completeIntent(plugin);
e.setCancelled(true);
e.setCancelReason(Utils.formatMessage(ban.getReason(), ban));
}
ban = BanManager.getBan(e.getConnection().getAddress().getAddress().getHostAddress(), "(GLOBAL)");
if (ban != null) {
e.setCancelled(true);
e.setCancelReason(Utils.formatMessage(ban.getReason(), ban));
}
e.completeIntent(plugin);
}
});
}
@Subscribe
public void onServerConnect(ServerConnectEvent e) {
BanEntry ban = BanManager.getBan(e.getPlayer().getName(), e.getTarget().getName());
if (ban != null) {
// Ugly workaround the player joined... player left messages
Server srv = e.getPlayer().getServer();
if (srv != null)
e.setTarget(srv.getInfo());
e.getPlayer().disconnect(Utils.formatMessage(ban.getReason(), ban));
return;
}
ban = BanManager.getBan(e.getPlayer().getAddress().getAddress().getHostAddress(), e.getTarget().getName());
if (ban != null) {
// Ugly workaround the player joined... player left messages
Server srv = e.getPlayer().getServer();
if (srv != null)
e.setTarget(srv.getInfo());
e.getPlayer().disconnect(Utils.formatMessage(ban.getReason(), ban));
}
return;
}
}
|
Fix completeIntent being called at the wrong place
|
src/main/java/net/craftminecraft/bungee/bungeeban/listener/ProxiedPlayerListener.java
|
Fix completeIntent being called at the wrong place
|
|
Java
|
mit
|
5b5dff6ab4913a32de7f8f8e95ff70a775e1984e
| 0
|
ececilla/WorizonJsonRpc
|
package com.worizon.jsonrpc;
/**
* Constants for JSONRPC low level code errors. The error object contains two fields: code and message.
* JSONRPC spec has several code numbers reserved to signal different transport errors and
* server implementations which honors JSONRPC 2.0 SPEC must use these error codes.
*
*
* @see <a href="http://www.jsonrpc.org/specification#error_object">jsonrpc error codes</a>
* @author Enric Cecilla
*/
public final class Consts {
private Consts(){}
public static final int INVALID_REQUEST_CODE = -32600;
public static final int METHOD_NOT_FOUND_CODE = -32601;
public static final int INVALID_PARAMS_CODE = -32602;
public static final int INTERNAL_ERROR_CODE = -32603;
public static final int PARSE_ERROR_CODE = -32700;
}
|
src/com/worizon/jsonrpc/Consts.java
|
package com.worizon.jsonrpc;
public final class Consts {
private Consts(){}
public static final int INVALID_REQUEST_CODE = -32600;
public static final int METHOD_NOT_FOUND_CODE = -32601;
public static final int INVALID_PARAMS_CODE = -32602;
public static final int INTERNAL_ERROR_CODE = -32603;
public static final int PARSE_ERROR_CODE = -32700;
}
|
Class level comments added.
|
src/com/worizon/jsonrpc/Consts.java
|
Class level comments added.
|
|
Java
|
mit
|
2557f5751d2f68edd881a2332ca35fef4cf1a5cd
| 0
|
kowshik/big-o,kowshik/big-o,guitilangyin0000/big-o,guitilangyin0000/big-o
|
package collections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* An iterator that hops specified number of times and then returns the next
* element after the hop. Note: the iterator always returns the first element as
* it is, and starts hopping only after the first element.
*
* Examples:
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 3, 5] in order when the hop value is 1.
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 4] in order when the hop value is 2.
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 5] in order when the hop value is 3.
*/
public class HoppingIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
private T nextItem;
private final int numHops;
private boolean first;
public HoppingIterator(Iterator<T> iterator, int numHops) {
if (numHops < 0) {
throw new IllegalArgumentException(String.format(
"numHops needs to be >= 0. You passed: %d", numHops));
}
this.numHops = numHops;
this.iterator = iterator;
nextItem = null;
first = true;
}
@Override
public boolean hasNext() {
if (nextItem != null) {
return true;
}
if (!first) {
for (int hop = 0; hop < numHops && iterator.hasNext(); hop++) {
iterator.next();
}
}
if (iterator.hasNext()) {
nextItem = iterator.next();
first = false;
}
return nextItem != null ? true : false;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T toReturn = nextItem;
nextItem = null;
return toReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
HoppingIterator<Integer> hi = new HoppingIterator<Integer>(
list.iterator(), 2);
System.out.println(hi.next());
System.out.println(hi.next());
System.out.println(hi.hasNext());
}
}
|
java/src/collections/HoppingIterator.java
|
package collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An iterator that hops specified number of times and then returns the next
* element after the hop.
*
* Examples:
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 3, 5] in order when the hop value is 1.
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 4] in order when the hop value is 2.
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 5] in order when the hop value is 3.
*/
public class HoppingIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
private T nextItem;
private final int numHops;
public HoppingIterator(Iterator<T> iterator, int numHops) {
if (numHops < 0) {
throw new IllegalArgumentException(String.format(
"numHops needs to be >= 0. You passed: %d", numHops));
}
this.numHops = numHops;
this.iterator = iterator;
nextItem = null;
}
@Override
public boolean hasNext() {
if (nextItem != null) {
return true;
}
for (int hop = 0; hop < numHops && iterator.hasNext(); hop++) {
iterator.next();
}
if (iterator.hasNext()) {
nextItem = iterator.next();
}
return nextItem != null ? true : false;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T toReturn = nextItem;
nextItem = null;
return toReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
[Java] Hopping iterator
|
java/src/collections/HoppingIterator.java
|
[Java] Hopping iterator
|
|
Java
|
mit
|
9ee47c95d89231c64110b939b42cc20dfa03342a
| 0
|
keski/rsp-spin,keski/rsp-spin
|
package org.rspspin.demo;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.XSD;
import org.rspspin.lang.rspql.ParserRSPQL;
import org.rspspin.util.ArgumentConstraintException;
import org.rspspin.util.TemplateManager;
import org.rspspin.util.Utils;
import org.topbraid.spin.arq.ARQ2SPIN;
import org.topbraid.spin.arq.ARQFactory;
import org.topbraid.spin.model.Module;
import org.topbraid.spin.model.Template;
import org.topbraid.spin.system.SPINArgumentChecker;
import org.topbraid.spin.system.SPINModuleRegistry;
import org.topbraid.spin.vocabulary.ARG;
import org.topbraid.spin.vocabulary.SPIN;
import org.topbraid.spin.vocabulary.SPL;
/**
* Demonstrate RSP-SPIN API.
*/
public class Example {
public static void main(String[] args) throws ArgumentConstraintException {
new Example().test1();
//new Example().test2();
}
/**
* Create template, validate query bindings, and instantiate query using
* the TemplateManager.
* @throws ArgumentConstraintException
*/
public void test1() throws ArgumentConstraintException{
String queryString = ""
+ "PREFIX : <http://debs2015.org/streams/> "
+ "PREFIX debs: <http://debs2015.org/onto#> "
+ "REGISTER STREAM ?rideCount AS "
+ "SELECT ISTREAM (count(?ride) AS ?rideCount) "
+ "FROM NAMED WINDOW :wind ON ?inputStream [RANGE PT1H STEP PT1H] "
+ "WHERE { "
+ " WINDOW :win { "
+ " ?ride debs:distance ?distance "
+ " FILTER ( ?distance > ?limit ) "
+ " }"
+ "}";
// Create template manager
TemplateManager tm = TemplateManager.get();
Template template = tm.createTemplate("http://example.org/template/1", queryString);
// Add template argument. Also tests that the argument is a variable.
tm.addArgumentConstraint("limit", XSD.integer, ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger),
true, template);
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("limit", ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger));
// Check that bindings are valid
tm.check(template, bindings);
// Get query from template and bindings
Query query = tm.getQuery(template, bindings);
query.setPrefix("", "http://debs2015.org/streams/");
query.setPrefix("onto", "http://debs2015.org/onto#");
System.out.println(query);
// Print model
tm.getModel().write(System.out, "TTL");
}
/**
* Create template, validate query bindings, and instantiate query using
* standard SPIN API commands.
* @throws ArgumentConstraintException
*/
public void test2() throws ArgumentConstraintException{
String queryString = ""
+ "PREFIX : <http://debs2015.org/streams/> "
+ "PREFIX debs: <http://debs2015.org/onto#> "
+ "REGISTER STREAM :rideCount AS "
+ "SELECT ISTREAM (count(?ride) AS ?rideCount) "
+ "FROM NAMED WINDOW :wind ON :trips [RANGE PT1H STEP PT1H] "
+ "WHERE { "
+ " WINDOW :win { "
+ " ?ride debs:distance ?distance "
+ " FILTER ( ?distance > ?limit ) "
+ " }"
+ "}";
// Register the RSP-QL syntax
ParserRSPQL.register();
ARQFactory.setSyntax(ParserRSPQL.syntax);
SPINModuleRegistry.get().init();
// Install the extended argument checker or one of your choice
SPINArgumentChecker.set(new SPINArgumentChecker() {
@Override
public void handleErrors(Module module, QuerySolutionMap bindings, List<String> errors)
throws ArgumentConstraintException {
throw new ArgumentConstraintException(errors);
}
});
// Create template
Model model = Utils.createDefaultModel();
ARQ2SPIN arq2spin = new ARQ2SPIN(model);
Query arqQuery = QueryFactory.create(queryString, ParserRSPQL.syntax);
org.topbraid.spin.model.Query spinQuery = arq2spin.createQuery(arqQuery, null);
Template template = model.createResource(null, SPIN.SelectTemplate).as(Template.class);
template.addProperty(SPIN.body, spinQuery);
// Add template argument
Resource arg = model.createResource(SPL.Argument);
arg.addProperty(SPL.predicate, model.createResource(ARG.NS + "limit"));
arg.addProperty(SPL.valueType, XSD.integer);
arg.addProperty(SPL.defaultValue, model.createTypedLiteral("2", XSDDatatype.XSDinteger));
arg.addProperty(SPL.optional, model.createTypedLiteral(true));
template.addProperty(SPIN.constraint, arg);
// Check binding
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("limit", ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger));
SPINArgumentChecker.get().check(template, bindings);
// Get ARQ query from template
Query arq = ARQFactory.get().createQuery((org.topbraid.spin.model.Query) template.getBody());
ParameterizedSparqlString p = new ParameterizedSparqlString(arq.toString(), bindings);
System.out.println(p);
// Print model
model.write(System.out, "TTL");
}
}
|
src/main/java/org/rspspin/demo/Example.java
|
package org.rspspin.demo;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.XSD;
import org.rspspin.lang.rspql.ParserRSPQL;
import org.rspspin.util.ArgumentConstraintException;
import org.rspspin.util.TemplateManager;
import org.rspspin.util.Utils;
import org.topbraid.spin.arq.ARQ2SPIN;
import org.topbraid.spin.arq.ARQFactory;
import org.topbraid.spin.model.Module;
import org.topbraid.spin.model.Template;
import org.topbraid.spin.system.SPINArgumentChecker;
import org.topbraid.spin.system.SPINModuleRegistry;
import org.topbraid.spin.vocabulary.ARG;
import org.topbraid.spin.vocabulary.SPIN;
import org.topbraid.spin.vocabulary.SPL;
/**
* Demonstrate RSP-SPIN API.
*/
public class Example {
public static void main(String[] args) throws ArgumentConstraintException {
new Example().test1();
new Example().test2();
}
/**
* Create template, validate query bindings, and instantiate query using
* the TemplateManager.
* @throws ArgumentConstraintException
*/
public void test1() throws ArgumentConstraintException{
String queryString = ""
+ "PREFIX : <http://debs2015.org/streams/> "
+ "PREFIX debs: <http://debs2015.org/onto#> "
+ "REGISTER STREAM :rideCount AS "
+ "SELECT ISTREAM (count(?ride) AS ?rideCount) "
+ "FROM NAMED WINDOW :wind ON :trips [RANGE PT1H STEP PT1H] "
+ "WHERE { "
+ " WINDOW :win { "
+ " ?ride debs:distance ?distance "
+ " FILTER ( ?distance > ?limit ) "
+ " }"
+ "}";
// Create template manager
TemplateManager tm = new TemplateManager();
Template template = tm.createTemplate("http://template", queryString);
// Add template argument. Also tests that the argument is a variable.
tm.addArgumentConstraint("limit", XSD.integer, ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger),
true, template);
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("limit", ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger));
// Check that bindings are valid
tm.check(template, bindings);
// Get query from template and bindings
Query query = tm.getQuery(template, bindings);
System.out.println(query);
// Print model
tm.getModel().write(System.out, "TTL");
}
/**
* Create template, validate query bindings, and instantiate query using
* standard SPIN API commands.
* @throws ArgumentConstraintException
*/
public void test2() throws ArgumentConstraintException{
String queryString = ""
+ "PREFIX : <http://debs2015.org/streams/> "
+ "PREFIX debs: <http://debs2015.org/onto#> "
+ "REGISTER STREAM :rideCount AS "
+ "SELECT ISTREAM (count(?ride) AS ?rideCount) "
+ "FROM NAMED WINDOW :wind ON :trips [RANGE PT1H STEP PT1H] "
+ "WHERE { "
+ " WINDOW :win { "
+ " ?ride debs:distance ?distance "
+ " FILTER ( ?distance > ?limit ) "
+ " }"
+ "}";
// Register the RSP-QL syntax
ParserRSPQL.register();
ARQFactory.setSyntax(ParserRSPQL.syntax);
SPINModuleRegistry.get().init();
// Install the extended argument checker or one of your choice
SPINArgumentChecker.set(new SPINArgumentChecker() {
@Override
public void handleErrors(Module module, QuerySolutionMap bindings, List<String> errors)
throws ArgumentConstraintException {
throw new ArgumentConstraintException(errors);
}
});
// Create template
Model model = Utils.createDefaultModel();
ARQ2SPIN arq2spin = new ARQ2SPIN(model);
Query arqQuery = QueryFactory.create(queryString, ParserRSPQL.syntax);
org.topbraid.spin.model.Query spinQuery = arq2spin.createQuery(arqQuery, null);
Template template = model.createResource(null, SPIN.SelectTemplate).as(Template.class);
template.addProperty(SPIN.body, spinQuery);
// Add template argument
Resource arg = model.createResource(SPL.Argument);
arg.addProperty(SPL.predicate, model.createResource(ARG.NS + "limit"));
arg.addProperty(SPL.valueType, XSD.integer);
arg.addProperty(SPL.defaultValue, model.createTypedLiteral("2", XSDDatatype.XSDinteger));
arg.addProperty(SPL.optional, model.createTypedLiteral(true));
template.addProperty(SPIN.constraint, arg);
// Check binding
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("limit", ResourceFactory.createTypedLiteral("2", XSDDatatype.XSDinteger));
SPINArgumentChecker.get().check(template, bindings);
// Get ARQ query from template
Query arq = ARQFactory.get().createQuery((org.topbraid.spin.model.Query) template.getBody());
ParameterizedSparqlString p = new ParameterizedSparqlString(arq.toString(), bindings);
System.out.println(p);
// Print model
model.write(System.out, "TTL");
}
}
|
minor change
|
src/main/java/org/rspspin/demo/Example.java
|
minor change
|
|
Java
|
mit
|
9cb40dbfd2355ca81bb726eb39fa53b665d6d3db
| 0
|
RamV13/Infection
|
/**
* Package for the users of the infection implementations for the Khan Academy
* interview
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ram Vellanki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
package com.ram.kainterview.user;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Represents an individual user of the software
* Total Infection Invariant: version number of this user and all coaches and
* students are equal
*/
public class User {
/**
* Version that this user sees (base version = 0)
*/
private int version;
/**
* Unique identifier for this user
*/
private String id;
/**
* Contains all of the coaches of this user.
* This List is empty if the user is not a student of any coaches.
*/
private List<User> coaches;
/**
* Contains all the students of this user.
* This List is empty if this user is not a coach of any students.
*/
private List<User> students;
/**
* Default constructor of a user with the base version and no students or
* coaches
*/
public User() {
version = 0;
id = UUID.randomUUID().toString();
coaches = new LinkedList<>();
students = new LinkedList<>();
}
/**
* Checks the total infection invariant of this class that the version
* numbers should be equal across all coaches and students of this user
* @return true of the invariant holds, false otherwise
*/
private boolean classInv() {
for (User coach : coaches)
if (this.version != coach.version)
return false;
for (User student : students)
if (this.version != student.version)
return false;
return true;
}
/**
* Adds a coach to this user
* @param coach the coach
*/
protected void addCoach(User coach) {
coaches.add(coach);
}
/**
* Adds a student to this user
* @param student the student
*/
protected void addStudent(User student) {
students.add(student);
}
/**
* Gets a read-only version of the list of coaches
* @return the list of coaches
*/
public List<User> coaches() {
return Collections.unmodifiableList(coaches);
}
/**
* Gets a read-only version of the list of students
* @return the list of students
*/
public List<User> students() {
return Collections.unmodifiableList(students);
}
/**
* Gets the number of coaches for this user
* @return the number of coaches
*/
protected int numCoaches() {
return coaches.size();
}
/**
* Gets the number of students for this user
* @return the number of students
*/
protected int numStudents() {
return students.size();
}
/**
* Gets the id of this user
* @return the id
*/
public String id() {
return id;
}
/**
* Gets the version that this user sees
* @return the version number
*/
public int version() {
return version;
}
/**
* Performs total infection from this user with the new version number
* @param version the new version number
*/
public void totalInfect(int version) {
this.version = version;
for (User coach : coaches)
if (coach.version != version)
coach.totalInfect(version);
for (User student : students)
if (student.version != version)
student.totalInfect(version);
assert classInv();
}
/**
* Performs limited infection on this user with the new version number
* @param version the new version number
* @param users the number of users to infect
* @return true if the users connected components are already on the same
* version (i.e. terminate infection), false otherwise
*/
public boolean limitedInfect(int version, int users) {
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
if (this.version != version) {
this.version = version;
users--;
}
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
boolean completed = true;
for (User student : students) {
if (student.version != version) {
// only change version if the number of users is not depleted
// OR the version change is an upgrade because we do not want
// students to be left out of upgrades (see README).
if (users > 0 || users <= 0 && version > student.version) {
student.version = version;
users--;
completed = false;
}
}
}
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
for (User coach : coaches) {
// only change version if the number of users is not depleted
if (coach.version != version && users > 0) {
coach.version = version;
users--;
completed = false;
}
}
// terminate infection if connected components are on the same version
if (completed)
return true;
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
// continue infection to students first
for (User student : students)
student.limitedInfect(version, users);
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
// ... then proceed to coaches
for (User coach : coaches)
coach.limitedInfect(version, users);
return false;
}
/**
* Determines the size of the graph of the users connected to this user as
* coaches or students with a depth-first traversal in each direction (both
* to coaches and to students)
* @return the size of the graph
*/
public int graphSize() {
int count = 1;
Map<String, User> users = new HashMap<String, User>();
users.put(this.id, this);
for (User student : students)
count+=student.graphSize(users);
for (User coach : coaches)
count+=coach.graphSize(users);
return count;
}
/**
* Determines the size of the graph of the users connected to this user as
* coaches or students with a depth-first traversal in each direction (both
* to coaches and to students)
* @param users map of users already processed for the graph size
* @return the size of the graph
*/
private int graphSize(Map<String,User> users) {
int count = 1;
users.put(this.id, this);
for (User student : students)
if (!users.containsKey(student.id))
count+=student.graphSize(users);
for (User coach : coaches)
if (!users.containsKey(coach.id))
count+=coach.graphSize(users);
return count;
}
}
|
src/com/ram/kainterview/user/User.java
|
/**
* Package for the users of the infection implementations for the Khan Academy
* interview
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ram Vellanki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
package com.ram.kainterview.user;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Represents an individual user of the software
* Total Infection Invariant: version number of this user and all coaches and
* students are equal
*/
public class User {
/**
* Version that this user sees (base version = 0)
*/
private int version;
/**
* Unique identifier for this user
*/
private String id;
/**
* Contains all of the coaches of this user.
* This List is empty if the user is not a student of any coaches.
*/
private List<User> coaches;
/**
* Contains all the students of this user.
* This List is empty if this user is not a coach of any students.
*/
private List<User> students;
/**
* Default constructor of a user with the base version and no students or
* coaches
*/
public User() {
version = 0;
id = UUID.randomUUID().toString();
coaches = new LinkedList<>();
students = new LinkedList<>();
}
/**
* Checks the total infection invariant of this class that the version
* numbers should be equal across all coaches and students of this user
* @return true of the invariant holds, false otherwise
*/
private boolean classInv() {
for (User coach : coaches)
if (this.version != coach.version)
return false;
for (User student : students)
if (this.version != student.version)
return false;
return true;
}
/**
* Adds a coach to this user
* @param coach the coach
*/
protected void addCoach(User coach) {
coaches.add(coach);
}
/**
* Adds a student to this user
* @param student the student
*/
protected void addStudent(User student) {
students.add(student);
}
/**
* Gets a read-only version of the list of coaches
* @return the list of coaches
*/
public List<User> coaches() {
return Collections.unmodifiableList(coaches);
}
/**
* Gets a read-only version of the list of students
* @return the list of students
*/
public List<User> students() {
return Collections.unmodifiableList(students);
}
/**
* Gets the number of coaches for this user
* @return the number of coaches
*/
protected int numCoaches() {
return coaches.size();
}
/**
* Gets the number of students for this user
* @return the number of students
*/
protected int numStudents() {
return students.size();
}
/**
* Gets the id of this user
* @return the id
*/
public String id() {
return id;
}
/**
* Gets the version that this user sees
* @return the version number
*/
public int version() {
return version;
}
/**
* Performs total infection from this user with the new version number
* @param version the new version number
*/
public void totalInfect(int version) {
this.version = version;
for (User coach : coaches)
if (coach.version != version)
coach.totalInfect(version);
for (User student : students)
if (student.version != version)
student.totalInfect(version);
assert classInv();
}
/**
* Performs limited infection on this user with the new version number
* @param version the new version number
* @param users the number of users to infect
* @return true if the users connected components are already on the same
* version (=> terminate infection), false otherwise
*/
public boolean limitedInfect(int version, int users) {
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
if (this.version != version) {
this.version = version;
users--;
}
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
boolean completed = true;
for (User student : students) {
if (student.version != version) {
// only change version if the number of users is not depleted
// OR the version change is an upgrade because we do not want
// students to be left out of upgrades (see README).
if (users > 0 || users <= 0 && version > student.version) {
student.version = version;
users--;
completed = false;
}
}
}
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
for (User coach : coaches) {
// only change version if the number of users is not depleted
if (coach.version != version && users > 0) {
coach.version = version;
users--;
completed = false;
}
}
// terminate infection if connected components are on the same version
if (completed)
return true;
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
// continue infection to students first
for (User student : students)
student.limitedInfect(version, users);
// terminate infection at this point in graph if # of users is depleted
if (users <= 0)
return true;
// ... then proceed to coaches
for (User coach : coaches)
coach.limitedInfect(version, users);
return false;
}
/**
* Determines the size of the graph of the users connected to this user as
* coaches or students with a depth-first traversal in each direction (both
* to coaches and to students)
* @return the size of the graph
*/
public int graphSize() {
int count = 1;
Map<String, User> users = new HashMap<String, User>();
users.put(this.id, this);
for (User student : students)
count+=student.graphSize(users);
for (User coach : coaches)
count+=coach.graphSize(users);
return count;
}
/**
* Determines the size of the graph of the users connected to this user as
* coaches or students with a depth-first traversal in each direction (both
* to coaches and to students)
* @param users map of users already processed for the graph size
* @return the size of the graph
*/
private int graphSize(Map<String,User> users) {
int count = 1;
users.put(this.id, this);
for (User student : students)
if (!users.containsKey(student.id))
count+=student.graphSize(users);
for (User coach : coaches)
if (!users.containsKey(coach.id))
count+=coach.graphSize(users);
return count;
}
}
|
Fixed javadoc
|
src/com/ram/kainterview/user/User.java
|
Fixed javadoc
|
|
Java
|
mit
|
bf1fe64e8e1c2f0bed4b72f807ef52eb3c7475be
| 0
|
psjava/psjava,psjava/psjava
|
package org.psjava.util;
import java.util.Iterator;
public class ConvertedDataIterable {
public static <T1, T2> Iterable<T2> create(final Iterable<T1> outerIterable, final DataConverter<T1, T2> converter) {
return new Iterable<T2>() {
@Override
public Iterator<T2> iterator() {
return ConvertedDataIterator.create(outerIterable.iterator(), converter);
}
@Override
public String toString() {
return IterableToString.toString(this);
}
};
}
private ConvertedDataIterable() {
}
}
|
src/main/java/org/psjava/util/ConvertedDataIterable.java
|
package org.psjava.util;
import java.util.Iterator;
public class ConvertedDataIterable {
public static <T1, T2> Iterable<T2> create(final Iterable<T1> outerIterable, final DataConverter<T1, T2> converter) {
return new Iterable<T2>() {
@Override
public Iterator<T2> iterator() {
return ConvertedDataIterator.create(outerIterable.iterator(), converter);
}
};
}
private ConvertedDataIterable() {
}
}
|
add simple tostring
|
src/main/java/org/psjava/util/ConvertedDataIterable.java
|
add simple tostring
|
|
Java
|
mit
|
2c9c2b732d990ac23717e65e860e4abcc78b6c77
| 0
|
frustra/Feather
|
package org.frustra.feather.server.commands;
import org.frustra.feather.server.Bootstrap;
import org.frustra.feather.server.Command;
import org.frustra.feather.server.CommandException;
import org.frustra.feather.server.CommandUsageException;
import org.frustra.feather.server.Entity;
import org.frustra.feather.server.Player;
public class OpUpCommand extends Command {
public String getName() {
return "opup";
}
public void execute(Entity source, String[] arguments) {
if (arguments.length == 0) {
Command.execute("op " + source.getName());
source.sendMessage("You now have op");
} else if (arguments.length == 1) {
Player target = Bootstrap.server.fetchPlayer(arguments[0]);
if (target == null) {
throw new CommandException(arguments[0] + " hasn't played here");
} else {
if (target.isAllowedOperator()) {
throw new CommandException(target + " is already allowed to /opup");
} else {
target.makeAllowedOperator();
target.sendMessage("You now have access to /opup");
source.sendMessage(target + " now has access to /opup");
}
}
} else throw new CommandUsageException(this);
}
public boolean hasPermission(Entity source) {
Player p = source.getPlayer();
return p == null || p.isAllowedOperator() || p.isOperator();
}
public String getUsage(Entity source) {
return "/opup [player]";
}
}
|
src/org/frustra/feather/server/commands/OpUpCommand.java
|
package org.frustra.feather.server.commands;
import org.frustra.feather.server.Bootstrap;
import org.frustra.feather.server.Command;
import org.frustra.feather.server.CommandException;
import org.frustra.feather.server.CommandUsageException;
import org.frustra.feather.server.Entity;
import org.frustra.feather.server.Player;
public class OpUpCommand extends Command {
public String getName() {
return "opup";
}
public void execute(Entity source, String[] arguments) {
if (arguments.length == 0) {
Command.execute("op " + source.getName());
source.sendMessage("You now have op");
} else if (arguments.length == 1) {
Player target = Bootstrap.server.fetchPlayer(arguments[0]);
if (target == null) {
throw new CommandException(target + " hasn't played here");
} else {
if (target.isAllowedOperator() || target.isOperator()) {
throw new CommandException(target + " is already allowed to /opup");
} else {
target.makeAllowedOperator();
target.sendMessage("You now have access to /opup");
source.sendMessage(target + " now has access to /opup");
}
}
} else throw new CommandUsageException(this);
}
public boolean hasPermission(Entity source) {
Player p = source.getPlayer();
return p == null || p.isAllowedOperator() || p.isOperator();
}
public String getUsage(Entity source) {
return "/opup [player]";
}
}
|
Fix more opup things
|
src/org/frustra/feather/server/commands/OpUpCommand.java
|
Fix more opup things
|
|
Java
|
mit
|
c4ff4f98b1342ba9633d8c04279d086bd7300959
| 0
|
APCS-SHS/Schedule-Manager,APCS-SHS/Schedule-Manager
|
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
/**
* Write a description of class ScheduleGUI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ScheduleGUI extends JFrame implements ActionListener
{
private MySchedule schedule;
private JButton newTask,newEvent,confirm;
private static JMenuBar menuBar;
private JTextField teName,teStart;//te= event/task
private JPanel teButtons,tForm,eForm;
private int taskEventStatus=0;
//private TaskEventListener teListener=new TaskEventListener();
private Task task;
private Event event;
private JTextField nameField;
private JTextArea descriptionField;
private JButton confirmTE,cancelTE,repeating;
public ScheduleGUI(String name){
super(name);
}
public static void run(){
ScheduleGUI frame=new ScheduleGUI("Schdule Manager");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);//Exit when quit;
frame.initMenuBar();//Create Menu Bar
frame.setJMenuBar(menuBar);//Add Menu Bar
frame.createNewTaskEventButtons();//Create and Add Buttons
//Display the GUI
frame.pack();
frame.setVisible(true);
}
private void initMenuBar(){
menuBar=new JMenuBar();//Create JMenuBar MenuBar
JMenu teNew=new JMenu("New");// Create Menu "New"
JMenuItem nEvent=new JMenuItem("New Event");
nEvent.addActionListener(this);
JMenuItem nTask=new JMenuItem("New Task");
nTask.addActionListener(this);
teNew.add(nTask);
teNew.add(nEvent);
menuBar.add(teNew);
}
private void createNewTaskEventButtons(){
newTask=new JButton("New Task");
newTask.setToolTipText("Create a new task.");
newTask.addActionListener(this);
newEvent=new JButton("New Event");
newEvent.setToolTipText("Create a new event.");
newEvent.addActionListener(this);
teButtons=new JPanel();
teButtons.add(newTask);//Add newTask to teButtons
teButtons.add(newEvent);//Add newEvent to teButtons
changeVisibility(0);
}
private void changeVisibility(int visibility){
if (visibility==0){
getContentPane().removeAll();
getContentPane().add(teButtons,BorderLayout.PAGE_END);//Add teButtons
}
if(visibility>0){
getContentPane().remove(teButtons);
}
if(visibility==1){
//getContentPane().add(TaskForm);
}
if(visibility==2){
//getContentPane().add(EventForm);
}
repaint();
}
private void tForm(){
nameField=new JTextField("Name");
nameField.addActionListener(this);
}
private void eForm(){}
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("New Task")){
taskEventStatus=1;
changeVisibility(taskEventStatus);
}
if(ae.getActionCommand().equals("New Event")){
taskEventStatus=2;
changeVisibility(taskEventStatus);
}
if(ae.getActionCommand().equals("Confirm")){
if(taskEventStatus==1){
//MySchedule.addTask(task);
}
}
}
}
|
ScheduleGUI.java
|
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* Write a description of class ScheduleGUI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ScheduleGUI extends JFrame implements ActionListener
{
private MySchedule schedule;
private JButton newTask,newEvent,confirm;
private static JMenuBar menuBar;
private JTextField teName,teStart;//te= event/task
private JPanel teButtons,tForm,eForm;
//private TaskEventListener teListener=new TaskEventListener();
public ScheduleGUI(String name){
super(name);
}
public static void run(){
ScheduleGUI frame=new ScheduleGUI("Schdule Manager");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);//Exit when quit;
frame.initMenuBar();//Create Menu Bar
frame.setJMenuBar(menuBar);//Add Menu Bar
frame.createNewTaskEventButtons();//Create and Add Buttons
//Display the GUI
frame.pack();
frame.setVisible(true);
}
private void initMenuBar(){
menuBar=new JMenuBar();//Create JMenuBar MenuBar
JMenu teNew=new JMenu("New");// Create Menu "New"
JMenuItem nEvent=new JMenuItem("New Event");
nEvent.addActionListener(this);
JMenuItem nTask=new JMenuItem("New Task");
nTask.addActionListener(this);
teNew.add(nTask);
teNew.add(nEvent);
menuBar.add(teNew);
}
private void createNewTaskEventButtons(){
newTask=new JButton("New Task");
newTask.setToolTipText("Create a new task.");
newTask.addActionListener(this);
newEvent=new JButton("New Event");
newEvent.setToolTipText("Create a new event.");
newEvent.addActionListener(this);
teButtons=new JPanel();
teButtons.add(newTask);//Add newTask to teButtons
teButtons.add(newEvent);//Add newEvent to teButtons
changeVisibility(0);
}
private void changeVisibility(int visibility){
if (visibility==0){
getContentPane().removeAll();
getContentPane().add(teButtons,BorderLayout.PAGE_END);//Add teButtons
}
if(visibility>0){
getContentPane().remove(teButtons);
}
if(visibility==1){
//getContentPane().add(TaskForm);
}
if(visibility==2){
//getContentPane().add(EventForm);
}
repaint();
}
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("New Task")){
changeVisibility(1);
}
if(ae.getActionCommand().equals("New Event")){
changeVisibility(2);
}
}
}
|
ScheduleGUI modified with placeholders to create forms for Tasks/Events...
|
ScheduleGUI.java
|
ScheduleGUI modified with placeholders to create forms for Tasks/Events...
|
|
Java
|
mit
|
51adc118a2c70b0a890e159527d7b9b889dc6a4c
| 0
|
ovr/phpinspectionsea-mirror,ovr/phpinspectionsea-mirror,ovr/phpinspectionsea-mirror
|
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictOperators;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Function;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.kalessil.phpStorm.phpInspectionsEA.utils.ExpressionSemanticUtil;
import com.kalessil.phpStorm.phpInspectionsEA.utils.TypeFromPsiResolvingUtil;
import com.kalessil.phpStorm.phpInspectionsEA.utils.Types;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.HashSet;
public class PhpExpressionTypes {
private final HashSet<String> types = new HashSet<String>();
private boolean isMixed;
private final PhpIndex objIndex;
final static private String strTypeObject = "object";
final static private String strTypeStatic = "static";
final static private String strTypeTrue = "true";
final static private String strTypeFalse = "false";
final static private String strTypeNumber = "number";
final static private String strTypeArrayAccess = "\\ArrayAccess";
public PhpExpressionTypes(final PsiElement expr, @NotNull final ProblemsHolder holder) {
objIndex = PhpIndex.getInstance(holder.getProject());
if (expr != null) {
final Function objScope = ExpressionSemanticUtil.getScope(expr);
TypeFromPsiResolvingUtil.resolveExpressionType(expr, objScope, objIndex, types);
}
types.remove(Types.strResolvingAbortedOnPsiLevel);
types.remove(Types.strClassNotResolved);
checkTypes();
}
public PhpExpressionTypes(@NotNull final String strTypes, @NotNull final ProblemsHolder holder) {
objIndex = PhpIndex.getInstance(holder.getProject());
if ((strTypes.indexOf('?') >= 0) || (strTypes.indexOf('#') >= 0)) {
types.add(Types.strMixed);
} else {
for (final String str : strTypes.split("\\|")) {
if (!str.isEmpty()) {
types.add(Types.getType(str));
}
}
}
checkTypes();
}
private void checkTypes() {
if (types.contains(Types.strCallable)) {
types.add(Types.strString);
}
if (types.contains(strTypeStatic)) {
types.add(strTypeObject);
}
if (types.contains(strTypeTrue) || types.contains(strTypeFalse)) {
types.add(Types.strBoolean);
}
if (types.contains(strTypeNumber)) {
types.add(Types.strInteger);
types.add(Types.strFloat);
}
if (types.isEmpty()) {
types.add(Types.strMixed);
}
isMixed = types.contains(Types.strMixed);
}
public boolean equals(@NotNull final PhpExpressionTypes another) {
// skip if one of expressions has "mixed" type
// (otherwise many false-positives are generated)
// @todo remove if type deduction will be improved in next PhpStorm version
if (isMixed || another.isMixed) {
return true;
}
final HashSet<String> copy = new HashSet<String>(types);
copy.retainAll(another.types);
return !copy.isEmpty();
}
public String toString() {
switch (types.size()) {
case 0:
return "unknown";
case 1:
return types.iterator().next();
default:
final StringBuilder sb = new StringBuilder();
for (final String s : types) {
sb.append(s);
sb.append('|');
}
return sb.delete(sb.length() - 1, sb.length()).toString();
}
}
public boolean contains(final String type) {
return types.contains(type);
}
public boolean instanceOf(final PhpExpressionTypes base) {
final boolean instanceOfObject = base.types.contains(strTypeObject);
for (final String type1 : types) {
if (type1.charAt(0) == '\\') {
if (instanceOfObject) {
return true;
}
final HashSet<String> extendslist = new HashSet<String>();
getParentsList(type1, extendslist);
for (final String type2 : base.types) {
if (type2.charAt(0) == '\\') {
if (extendslist.contains(type2)) {
return true;
}
}
}
}
}
return false;
}
public boolean isInt() {
return isMixed || types.contains(Types.strInteger);
}
public boolean isFloat() {
return isMixed || types.contains(Types.strFloat);
}
public boolean isNumeric() {
return isMixed || types.contains(Types.strInteger) || types.contains(Types.strFloat);
}
public boolean isString() {
return isMixed || types.contains(Types.strString);
}
public boolean isBoolean() {
return isMixed || types.contains(Types.strBoolean);
}
public boolean isArray() {
return isMixed || types.contains(Types.strArray);
}
public boolean isNull() {
return isMixed || types.contains(Types.strNull);
}
public boolean isMixed() {
return isMixed;
}
public boolean isObject() {
for (final String type : types) {
if (type.charAt(0) == '\\') {
return true;
}
}
return false;
}
public boolean isArrayAccess() {
for (final String type1 : types) {
if (type1.charAt(0) == '\\') {
final HashSet<String> extendslist = new HashSet<String>();
getParentsList(type1, extendslist);
if (extendslist.contains(strTypeArrayAccess)) {
return true;
}
}
}
return false;
}
private void getParentsList(final String className, final HashSet<String> extendslist) {
for (PhpClass typeclass : objIndex.getAnyByFQN(className)) {
while (typeclass != null) {
extendslist.add(typeclass.getFQN());
String[] interfaceNames = typeclass.getInterfaceNames();
for (final String interfaceName : interfaceNames) {
if (!extendslist.contains(interfaceName)) {
extendslist.add(interfaceName);
getParentsList(interfaceName, extendslist);
}
}
extendslist.addAll(Arrays.asList(typeclass.getTraitNames()));
extendslist.addAll(Arrays.asList(typeclass.getMixinNames()));
typeclass = typeclass.getSuperClass();
}
}
}
}
|
src/com/kalessil/phpStorm/phpInspectionsEA/inspectors/strictOperators/PhpExpressionTypes.java
|
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictOperators;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.psi.elements.Function;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.kalessil.phpStorm.phpInspectionsEA.utils.ExpressionSemanticUtil;
import com.kalessil.phpStorm.phpInspectionsEA.utils.TypeFromPsiResolvingUtil;
import com.kalessil.phpStorm.phpInspectionsEA.utils.Types;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.HashSet;
public class PhpExpressionTypes {
private final HashSet<String> types = new HashSet<String>();
private boolean isMixed;
private final PhpIndex objIndex;
final static private String strTypeObject = "object";
final static private String strTypeStatic = "static";
final static private String strTypeArrayAccess = "\\ArrayAccess";
public PhpExpressionTypes(final PsiElement expr, @NotNull final ProblemsHolder holder) {
objIndex = PhpIndex.getInstance(holder.getProject());
if (expr != null) {
final Function objScope = ExpressionSemanticUtil.getScope(expr);
TypeFromPsiResolvingUtil.resolveExpressionType(expr, objScope, objIndex, types);
}
types.remove(Types.strResolvingAbortedOnPsiLevel);
types.remove(Types.strClassNotResolved);
checkTypes();
}
public PhpExpressionTypes(@NotNull final String strTypes, @NotNull final ProblemsHolder holder) {
objIndex = PhpIndex.getInstance(holder.getProject());
if ((strTypes.indexOf('?') >= 0) || (strTypes.indexOf('#') >= 0)) {
types.add(Types.strMixed);
} else {
for (final String str : strTypes.split("\\|")) {
if (!str.isEmpty()) {
types.add(Types.getType(str));
}
}
}
checkTypes();
}
private void checkTypes() {
if (types.contains(Types.strCallable)) {
types.add(Types.strString);
}
if (types.contains(strTypeStatic)) {
types.add(strTypeObject);
}
if (types.isEmpty()) {
types.add(Types.strMixed);
}
isMixed = types.contains(Types.strMixed);
}
public boolean equals(@NotNull final PhpExpressionTypes another) {
// skip if one of expressions has "mixed" type
// (otherwise many false-positives are generated)
// @todo remove if type deduction will be improved in next PhpStorm version
if (isMixed || another.isMixed) {
return true;
}
final HashSet<String> copy = new HashSet<String>(types);
copy.retainAll(another.types);
return !copy.isEmpty();
}
public String toString() {
switch (types.size()) {
case 0:
return "unknown";
case 1:
return types.iterator().next();
default:
final StringBuilder sb = new StringBuilder();
for (final String s : types) {
sb.append(s);
sb.append('|');
}
return sb.delete(sb.length() - 1, sb.length()).toString();
}
}
public boolean contains(final String type) {
return types.contains(type);
}
public boolean instanceOf(final PhpExpressionTypes base) {
final boolean instanceOfObject = base.types.contains(strTypeObject);
for (final String type1 : types) {
if (type1.charAt(0) == '\\') {
if (instanceOfObject) {
return true;
}
final HashSet<String> extendslist = new HashSet<String>();
getParentsList(type1, extendslist);
for (final String type2 : base.types) {
if (type2.charAt(0) == '\\') {
if (extendslist.contains(type2)) {
return true;
}
}
}
}
}
return false;
}
public boolean isInt() {
return isMixed || types.contains(Types.strInteger);
}
public boolean isFloat() {
return isMixed || types.contains(Types.strFloat);
}
public boolean isNumeric() {
return isMixed || types.contains(Types.strInteger) || types.contains(Types.strFloat);
}
public boolean isString() {
return isMixed || types.contains(Types.strString);
}
public boolean isBoolean() {
return isMixed || types.contains(Types.strBoolean);
}
public boolean isArray() {
return isMixed || types.contains(Types.strArray);
}
public boolean isNull() {
return isMixed || types.contains(Types.strNull);
}
public boolean isMixed() {
return isMixed;
}
public boolean isObject() {
for (final String type : types) {
if (type.charAt(0) == '\\') {
return true;
}
}
return false;
}
public boolean isArrayAccess() {
for (final String type1 : types) {
if (type1.charAt(0) == '\\') {
final HashSet<String> extendslist = new HashSet<String>();
getParentsList(type1, extendslist);
if (extendslist.contains(strTypeArrayAccess)) {
return true;
}
}
}
return false;
}
private void getParentsList(final String className, final HashSet<String> extendslist) {
for (PhpClass typeclass : objIndex.getAnyByFQN(className)) {
while (typeclass != null) {
extendslist.add(typeclass.getFQN());
String[] interfaceNames = typeclass.getInterfaceNames();
for (final String interfaceName : interfaceNames) {
if (!extendslist.contains(interfaceName)) {
extendslist.add(interfaceName);
getParentsList(interfaceName, extendslist);
}
}
extendslist.addAll(Arrays.asList(typeclass.getTraitNames()));
extendslist.addAll(Arrays.asList(typeclass.getMixinNames()));
typeclass = typeclass.getSuperClass();
}
}
}
}
|
support true|false|number types (used in php stub files)
|
src/com/kalessil/phpStorm/phpInspectionsEA/inspectors/strictOperators/PhpExpressionTypes.java
|
support true|false|number types (used in php stub files)
|
|
Java
|
agpl-3.0
|
e3c75091555652e8ebd738d0f1a3c0fdea1abd8a
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
19c7afb8-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
19c2405a-2e60-11e5-9284-b827eb9e62be
|
19c7afb8-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
19c7afb8-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
lgpl-2.1
|
ee47e15488db4cd652f2654903f3d45b942c8d29
| 0
|
SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
|
/*
* CypressFX3Biasgen.java
*
* Created on 23 Jan 2008
*/
package net.sf.jaer.hardwareinterface.usb.cypressfx3libusb;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Arrays;
import org.usb4java.Device;
import eu.seebetter.ini.chips.DavisChip;
import eu.seebetter.ini.chips.davis.DavisConfig;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
/**
* Adds functionality of apsDVS sensors to based CypressFX3Biasgen class. The
* key method is translateEvents that parses
* the data from the sensor to construct jAER raw events.
*
* @author Christian/Tobi
*/
public class DAViSFX3HardwareInterface extends CypressFX3Biasgen {
protected DAViSFX3HardwareInterface(final Device device) {
super(device);
}
@Override
synchronized public void sendConfiguration(final net.sf.jaer.biasgen.Biasgen biasgen) throws HardwareInterfaceException {
if ((biasgen != null) && (biasgen instanceof DavisConfig)) {
((DavisConfig) biasgen).sendConfiguration();
}
}
/** The USB product ID of this device */
static public final short PID_FX3 = (short) 0x841A;
static public final short PID_FX2 = (short) 0x841B;
static public final int REQUIRED_FIRMWARE_VERSION_FX3 = 4;
static public final int REQUIRED_FIRMWARE_VERSION_FX2 = 4;
static public final int REQUIRED_LOGIC_REVISION_FX3 = 16;
static public final int REQUIRED_LOGIC_REVISION_FX2 = 16;
private boolean updatedRealClockValues = false;
public float logicClockFreq = 90.0f;
public float adcClockFreq = 30.0f;
public float usbClockFreq = 30.0f;
/**
* Starts reader buffer pool thread and enables in endpoints for AEs. This
* method is overridden to construct
* our own reader with its translateEvents method
*/
@Override
public void startAEReader() throws HardwareInterfaceException {
setAeReader(new RetinaAEReader(this));
allocateAEBuffers();
getAeReader().startThread(); // arg is number of errors before giving up
HardwareInterfaceException.clearException();
}
private void getRealClockValues() {
try {
final int logicFreq = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 3);
final int adcFreq = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 4);
final int usbFreq = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 5);
final int clockDeviation = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 6);
logicClockFreq = (float) (logicFreq * (clockDeviation / 1000.0));
adcClockFreq = (float) (adcFreq * (clockDeviation / 1000.0));
usbClockFreq = (float) (usbFreq * (clockDeviation / 1000.0));
}
catch (final HardwareInterfaceException e) {
// No clock update on failure.
}
CypressFX3.log
.info(String.format("Device clock frequencies - Logic: %f, ADC: %f, USB: %f.", logicClockFreq, adcClockFreq, usbClockFreq));
}
@Override
protected int adjustHWParam(final short moduleAddr, final short paramAddr, final int param) {
if (!updatedRealClockValues) {
getRealClockValues();
updatedRealClockValues = true;
}
if ((moduleAddr == CypressFX3.FPGA_APS) && (paramAddr == 12)) {
// Exposure multiplied by clock.
return (int) (param * adcClockFreq);
}
if ((moduleAddr == CypressFX3.FPGA_APS) && (paramAddr == 13)) {
// FrameInterval multiplied by clock.
return (int) (param * adcClockFreq);
}
if ((moduleAddr == CypressFX3.FPGA_USB) && (paramAddr == 1)) {
// Early packet delay is 125µs slices on host, but in cycles
// @ USB_CLOCK_FREQ on FPGA, so we must multiply here.
return (int) (param * (125.0f * usbClockFreq));
}
// No change by default.
return (param);
}
public static final int CHIP_DAVIS240A = 0;
public static final int CHIP_DAVIS240B = 1;
public static final int CHIP_DAVIS240C = 2;
public static final int CHIP_DAVIS128 = 3;
public static final int CHIP_DAVIS346A = 4;
public static final int CHIP_DAVIS346B = 5;
public static final int CHIP_DAVIS640 = 6;
public static final int CHIP_DAVISRGB = 7;
public static final int CHIP_DAVIS208 = 8;
public static final int CHIP_DAVIS346C = 9;
/**
* This reader understands the format of raw USB data and translates to the
* AEPacketRaw
*/
public class RetinaAEReader extends CypressFX3.AEReader implements PropertyChangeListener {
private final int chipID;
private int wrapAdd;
private int lastTimestamp;
private int currentTimestamp;
private int dvsLastY;
private final boolean dvsInvertXY;
private final int dvsSizeX;
private final int dvsSizeY;
private static final int APS_READOUT_TYPES_NUM = 2;
private static final int APS_READOUT_RESET = 0;
private static final int APS_READOUT_SIGNAL = 1;
private int apsCurrentReadoutType;
private int apsRGBPixelOffset;
private boolean apsRGBPixelOffsetDirection;
private final short[] apsCountX;
private final short[] apsCountY;
private final boolean apsInvertXY;
private final boolean apsFlipX;
private final boolean apsFlipY;
private final int apsSizeX;
private final int apsSizeY;
private static final int IMU_DATA_LENGTH = 7;
private static final int IMU_TYPE_TEMP = 0x01;
private static final int IMU_TYPE_GYRO = 0x02;
private static final int IMU_TYPE_ACCEL = 0x04;
private final short[] imuEvents;
private final boolean imuFlipX;
private final boolean imuFlipY;
private final boolean imuFlipZ;
private int imuType;
private int imuCount;
private byte imuTmpData;
public RetinaAEReader(final CypressFX3 cypress) throws HardwareInterfaceException {
super(cypress);
if (getPID() == DAViSFX3HardwareInterface.PID_FX2) {
// FX2 firmware now emulates the same interface as FX3 firmware, so we support it here too.
checkFirmwareLogic(DAViSFX3HardwareInterface.REQUIRED_FIRMWARE_VERSION_FX2,
DAViSFX3HardwareInterface.REQUIRED_LOGIC_REVISION_FX2);
}
else {
checkFirmwareLogic(DAViSFX3HardwareInterface.REQUIRED_FIRMWARE_VERSION_FX3,
DAViSFX3HardwareInterface.REQUIRED_LOGIC_REVISION_FX3);
}
apsCountX = new short[RetinaAEReader.APS_READOUT_TYPES_NUM];
apsCountY = new short[RetinaAEReader.APS_READOUT_TYPES_NUM];
initFrame();
imuEvents = new short[RetinaAEReader.IMU_DATA_LENGTH];
chipID = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 1);
apsSizeX = spiConfigReceive(CypressFX3.FPGA_APS, (short) 0);
apsSizeY = spiConfigReceive(CypressFX3.FPGA_APS, (short) 1);
final int chipAPSStreamStart = spiConfigReceive(CypressFX3.FPGA_APS, (short) 2);
apsInvertXY = (chipAPSStreamStart & 0x04) != 0;
apsFlipX = (chipAPSStreamStart & 0x02) != 0;
apsFlipY = (chipAPSStreamStart & 0x01) != 0;
dvsSizeX = spiConfigReceive(CypressFX3.FPGA_DVS, (short) 0);
dvsSizeY = spiConfigReceive(CypressFX3.FPGA_DVS, (short) 1);
dvsInvertXY = (spiConfigReceive(CypressFX3.FPGA_DVS, (short) 2) & 0x04) != 0;
final int imuOrientation = spiConfigReceive(CypressFX3.FPGA_IMU, (short) 1);
imuFlipX = (imuOrientation & 0x04) != 0;
imuFlipY = (imuOrientation & 0x02) != 0;
imuFlipZ = (imuOrientation & 0x01) != 0;
updateTimestampMasterStatus();
}
private void checkMonotonicTimestamp() {
if (currentTimestamp <= lastTimestamp) {
CypressFX3.log.severe(toString() + ": non strictly-monotonic timestamp detected: lastTimestamp=" + lastTimestamp
+ ", currentTimestamp=" + currentTimestamp + ", difference=" + (lastTimestamp - currentTimestamp) + ".");
}
}
private void initFrame() {
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_RESET;
Arrays.fill(apsCountX, 0, RetinaAEReader.APS_READOUT_TYPES_NUM, (short) 0);
Arrays.fill(apsCountY, 0, RetinaAEReader.APS_READOUT_TYPES_NUM, (short) 0);
}
private boolean ensureCapacity(final AEPacketRaw buffer, final int capacity) {
if (buffer.getCapacity() > getAEBufferSize()) {
if (buffer.overrunOccuredFlag || (capacity > buffer.getCapacity())) {
buffer.overrunOccuredFlag = true;
return (false);
}
return (true);
}
buffer.ensureCapacity(capacity);
return (true);
}
@Override
protected void translateEvents(final ByteBuffer b) {
synchronized (aePacketRawPool) {
final AEPacketRaw buffer = aePacketRawPool.writeBuffer();
// Truncate off any extra partial event.
if ((b.limit() & 0x01) != 0) {
CypressFX3.log.severe(b.limit() + " bytes received via USB, which is not a multiple of two.");
b.limit(b.limit() & ~0x01);
}
buffer.lastCaptureIndex = eventCounter;
final ShortBuffer sBuf = b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
for (int i = 0; i < sBuf.limit(); i++) {
final short event = sBuf.get(i);
// Check if timestamp
if ((event & 0x8000) != 0) {
// Is a timestamp! Expand to 32 bits. (Tick is 1us already.)
lastTimestamp = currentTimestamp;
currentTimestamp = wrapAdd + (event & 0x7FFF);
// Check monotonicity of timestamps.
checkMonotonicTimestamp();
}
else {
// Look at the code, to determine event and data
// type
final byte code = (byte) ((event & 0x7000) >>> 12);
final short data = (short) (event & 0x0FFF);
switch (code) {
case 0: // Special event
switch (data) {
case 0: // Ignore this, but log it.
CypressFX3.log.severe("Caught special reserved event!");
break;
case 1: // Timetamp reset
wrapAdd = 0;
lastTimestamp = 0;
currentTimestamp = 0;
updateTimestampMasterStatus();
CypressFX3.log.info("Timestamp reset event received on " + super.toString()
+ " at System.currentTimeMillis()=" + System.currentTimeMillis());
break;
case 2: // External input (falling edge)
case 3: // External input (rising edge)
case 4: // External input (pulse)
CypressFX3.log.fine("External input event received.");
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
// tobi added data to pass thru rising falling and pulse events
buffer.getAddresses()[eventCounter] = DavisChip.EXTERNAL_INPUT_EVENT_ADDR + data;
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
break;
case 5: // IMU Start (6 axes)
CypressFX3.log.fine("IMU6 Start event received.");
imuCount = 0;
imuType = 0;
break;
case 7: // IMU End
CypressFX3.log.fine("IMU End event received.");
if (imuCount == (2 * RetinaAEReader.IMU_DATA_LENGTH)) {
if (ensureCapacity(buffer, eventCounter + IMUSample.SIZE_EVENTS)) {
// Check for buffer space is also done inside writeToPacket().
final IMUSample imuSample = new IMUSample(currentTimestamp, imuEvents);
eventCounter += imuSample.writeToPacket(buffer, eventCounter);
}
}
else {
CypressFX3.log.info(
"IMU End: failed to validate IMU sample count (" + imuCount + "), discarding samples.");
}
break;
case 8: // APS Global Shutter Frame Start
CypressFX3.log.fine("APS GS Frame Start event received.");
initFrame();
break;
case 9: // APS Rolling Shutter Frame Start
CypressFX3.log.fine("APS RS Frame Start event received.");
initFrame();
break;
case 10: // APS Frame End
CypressFX3.log.fine("APS Frame End event received.");
for (int j = 0; j < RetinaAEReader.APS_READOUT_TYPES_NUM; j++) {
if (apsCountX[j] != apsSizeX) {
CypressFX3.log.severe("APS Frame End: wrong column count [" + j + " - " + apsCountX[j]
+ "] detected. You might want to enable 'Ensure APS data transfer' under 'HW Configuration -> Chip Configuration' to improve this.");
}
}
break;
case 11: // APS Reset Column Start
CypressFX3.log.fine("APS Reset Column Start event received.");
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_RESET;
apsCountY[apsCurrentReadoutType] = 0;
apsRGBPixelOffsetDirection = false;
apsRGBPixelOffset = 1; // RGB support, first pixel of row always even.
break;
case 12: // APS Signal Column Start
CypressFX3.log.fine("APS Signal Column Start event received.");
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_SIGNAL;
apsCountY[apsCurrentReadoutType] = 0;
apsRGBPixelOffsetDirection = false;
apsRGBPixelOffset = 1; // RGB support, first pixel of row always even.
break;
case 13: // APS Column End
CypressFX3.log.fine("APS Column End event received.");
if (apsCountY[apsCurrentReadoutType] != apsSizeY) {
CypressFX3.log.severe("APS Column End: wrong row count [" + apsCurrentReadoutType + " - "
+ apsCountY[apsCurrentReadoutType]
+ "] detected. You might want to enable 'Ensure APS data transfer' under 'HW Configuration -> Chip Configuration' to improve this.");
}
apsCountX[apsCurrentReadoutType]++;
break;
case 14: // APS Exposure Start
// Ignore, exposure is calculated from frame timings.
break;
case 15: // APS Exposure End
// Ignore, exposure is calculated from frame timings.
break;
case 16: // External generator (falling edge)
// Ignore, not supported.
break;
case 17: // External generator (rising edge)
// Ignore, not supported.
break;
default:
CypressFX3.log.severe("Caught special event that can't be handled.");
break;
}
break;
case 1: // Y address
// Check range conformity.
if (data >= dvsSizeY) {
CypressFX3.log.severe("DVS: Y address out of range (0-" + (dvsSizeY - 1) + "): " + data + ".");
break; // Skip invalid Y address (don't update lastY).
}
dvsLastY = data;
break;
case 2: // X address, Polarity OFF
case 3: // X address, Polarity ON
// Check range conformity.
if (data >= dvsSizeX) {
CypressFX3.log.severe("DVS: X address out of range (0-" + (dvsSizeX - 1) + "): " + data + ".");
break; // Skip invalid event.
}
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
// The X address comes out of the new logic such that the (0, 0) address
// is, as expected by most, in the lower left corner. Since the DAVIS240
// chip class data format assumes that this is still flipped, as in the
// old logic, we have to flip it here, so that the chip class extractor
// can flip it back. Backwards compatibility with recordings is the main
// motivation to do this hack.
// NOTE 09.2017: logic now uses upper left (CG format) as output.
// Invert polarity for PixelParade high gain pixels (DavisSense), because of
// negative gain from pre-amplifier.
final byte polarity = ((chipID == DAViSFX3HardwareInterface.CHIP_DAVIS208) && (data < 192))
? ((byte) (~code))
: (code);
if (dvsInvertXY) {
buffer
.getAddresses()[eventCounter] = (((dvsSizeX - 1 - data) << DavisChip.YSHIFT) & DavisChip.YMASK)
| (((dvsSizeY - 1 - dvsLastY) << DavisChip.XSHIFT) & DavisChip.XMASK)
| (((polarity & 0x01) << DavisChip.POLSHIFT) & DavisChip.POLMASK);
}
else {
buffer.getAddresses()[eventCounter] = (((dvsSizeY - 1 - dvsLastY) << DavisChip.YSHIFT)
& DavisChip.YMASK) | (((dvsSizeX - 1 - data) << DavisChip.XSHIFT) & DavisChip.XMASK)
| (((polarity & 0x01) << DavisChip.POLSHIFT) & DavisChip.POLMASK);
}
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
break;
case 4: // APS ADC sample
// Let's check that apsCountY is not above the maximum. This could happen
// if start/end of column events are discarded (no wait on transfer stall).
if ((apsCountY[apsCurrentReadoutType] >= apsSizeY) || (apsCountX[apsCurrentReadoutType] >= apsSizeX)) {
CypressFX3.log.fine("APS ADC sample: row or column count is at maximum, discarding further samples.");
break;
}
// The DAVIS240c chip is flipped along the X axis. This means it's first reading
// out the leftmost columns, and not the rightmost ones as in all the other chips.
// So, if a 240c is detected, we don't do the artificial sign flip here.
int xPos;
int yPos;
if (apsFlipX) {
xPos = apsSizeX - 1 - apsCountX[apsCurrentReadoutType];
}
else {
xPos = apsCountX[apsCurrentReadoutType];
}
if (apsFlipY) {
yPos = apsSizeY - 1 - apsCountY[apsCurrentReadoutType];
}
else {
yPos = apsCountY[apsCurrentReadoutType];
}
if (chipID == DAViSFX3HardwareInterface.CHIP_DAVISRGB) {
yPos += apsRGBPixelOffset;
}
if (apsInvertXY) {
final int temp = xPos;
xPos = yPos;
yPos = temp;
}
// NOTE 09.2017: logic now uses upper left (CG format) as output.
yPos = (apsInvertXY) ? (apsSizeX - 1 - yPos) : (apsSizeY - 1 - yPos);
apsCountY[apsCurrentReadoutType]++;
// RGB support: first 320 pixels are even, then odd.
if (!apsRGBPixelOffsetDirection) { // Increasing
apsRGBPixelOffset++;
if (apsRGBPixelOffset == 321) {
// Switch to decreasing after last even pixel.
apsRGBPixelOffsetDirection = true;
apsRGBPixelOffset = 318;
}
}
else { // Decreasing
apsRGBPixelOffset -= 3;
}
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
buffer.getAddresses()[eventCounter] = DavisChip.ADDRESS_TYPE_APS
| ((yPos << DavisChip.YSHIFT) & DavisChip.YMASK) | ((xPos << DavisChip.XSHIFT) & DavisChip.XMASK)
| ((apsCurrentReadoutType << DavisChip.ADC_READCYCLE_SHIFT) & DavisChip.ADC_READCYCLE_MASK)
| (data & DavisChip.ADC_DATA_MASK);
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
break;
case 5: // Misc 8bit data.
final byte misc8Code = (byte) ((data & 0x0F00) >>> 8);
final byte misc8Data = (byte) (data & 0x00FF);
switch (misc8Code) {
case 0:
// IMU data event.
switch (imuCount) {
case 0:
case 2:
case 4:
case 6:
case 8:
case 10:
case 12:
imuTmpData = misc8Data;
break;
case 1: // Accel X
imuEvents[0] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipX) {
imuEvents[0] = (short) -imuEvents[0];
}
break;
case 3: // Accel Y
imuEvents[1] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipY) {
imuEvents[1] = (short) -imuEvents[1];
}
break;
case 5: // Accel Z
imuEvents[2] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipZ) {
imuEvents[2] = (short) -imuEvents[2];
}
// IMU parser count depends on which data is present.
if ((imuType & RetinaAEReader.IMU_TYPE_TEMP) == 0) {
if ((imuType & RetinaAEReader.IMU_TYPE_GYRO) != 0) {
// No temperature, but gyro.
imuCount += 2;
}
else {
// No others enabled.
imuCount += 8;
}
}
break;
case 7: // Temperature
imuEvents[3] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
// IMU parser count depends on which data is present.
if ((imuType & RetinaAEReader.IMU_TYPE_GYRO) == 0) {
// No others enabled.
imuCount += 6;
}
break;
case 9: // Gyro X
imuEvents[4] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipX) {
imuEvents[4] = (short) -imuEvents[4];
}
break;
case 11: // Gyro Y
imuEvents[5] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipY) {
imuEvents[5] = (short) -imuEvents[5];
}
break;
case 13: // Gyro Z
imuEvents[6] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipZ) {
imuEvents[6] = (short) -imuEvents[6];
}
break;
}
imuCount++;
break;
case 1: // APS ROI Size Part 1 (bits 15-8).
case 2: // APS ROI Size Part 2 (bits 7-0).
// Ignore ROI events, not supported.
break;
case 3:
// Scale for accel/gyro come from its configuration directly.
// Set expected type of data to come from IMU (accel, gyro, temp).
imuType = (data >> 5) & 0x07;
// IMU parser start count depends on which data is present.
if ((imuType & RetinaAEReader.IMU_TYPE_ACCEL) != 0) {
// Accelerometer.
imuCount = 0;
}
else if ((imuType & RetinaAEReader.IMU_TYPE_TEMP) != 0) {
// Temperature
imuCount = 6;
}
else if ((imuType & RetinaAEReader.IMU_TYPE_GYRO) != 0) {
// Gyroscope.
imuCount = 8;
}
else {
// Nothing, should never happen.
imuCount = 14;
}
break;
default:
CypressFX3.log.severe("Caught Misc8 event that can't be handled.");
break;
}
break;
case 6: // Misc 10bit data.
final byte misc10Code = (byte) ((data & 0x0C00) >>> 10);
switch (misc10Code) {
case 0:
// APS Exposure Information, ignore for now.
break;
default:
CypressFX3.log.severe("Caught Misc10 event that can't be handled.");
break;
}
break;
case 7: // Timestamp wrap
// Each wrap is 2^15 us (~32ms), and we have
// to multiply it with the wrap counter,
// which is located in the data part of this
// event.
wrapAdd += (0x8000L * data);
lastTimestamp = currentTimestamp;
currentTimestamp = wrapAdd;
// Check monotonicity of timestamps.
checkMonotonicTimestamp();
CypressFX3.log.fine(
String.format("Timestamp wrap event received on %s with multiplier of %d.", super.toString(), data));
break;
default:
CypressFX3.log.severe("Caught event that can't be handled.");
break;
}
}
} // end loop over usb data buffer
buffer.setNumEvents(eventCounter);
// write capture size
buffer.lastCaptureLength = eventCounter - buffer.lastCaptureIndex;
} // sync on aePacketRawPool
}
@Override
public void propertyChange(final PropertyChangeEvent arg0) {
// Do nothing here, IMU comes directly via event-stream.
}
}
}
|
src/net/sf/jaer/hardwareinterface/usb/cypressfx3libusb/DAViSFX3HardwareInterface.java
|
/*
* CypressFX3Biasgen.java
*
* Created on 23 Jan 2008
*/
package net.sf.jaer.hardwareinterface.usb.cypressfx3libusb;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Arrays;
import org.usb4java.Device;
import eu.seebetter.ini.chips.DavisChip;
import eu.seebetter.ini.chips.davis.DavisConfig;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
/**
* Adds functionality of apsDVS sensors to based CypressFX3Biasgen class. The
* key method is translateEvents that parses
* the data from the sensor to construct jAER raw events.
*
* @author Christian/Tobi
*/
public class DAViSFX3HardwareInterface extends CypressFX3Biasgen {
protected DAViSFX3HardwareInterface(final Device device) {
super(device);
}
@Override
synchronized public void sendConfiguration(final net.sf.jaer.biasgen.Biasgen biasgen) throws HardwareInterfaceException {
if ((biasgen != null) && (biasgen instanceof DavisConfig)) {
((DavisConfig) biasgen).sendConfiguration();
}
}
/** The USB product ID of this device */
static public final short PID_FX3 = (short) 0x841A;
static public final short PID_FX2 = (short) 0x841B;
static public final int REQUIRED_FIRMWARE_VERSION_FX3 = 4;
static public final int REQUIRED_FIRMWARE_VERSION_FX2 = 4;
static public final int REQUIRED_LOGIC_REVISION_FX3 = 9912;
static public final int REQUIRED_LOGIC_REVISION_FX2 = 9912;
static public final float FX2_USB_CLOCK_FREQ = 30.0f;
static public final float FX3_CLOCK_CORRECTION = 1.008f;
static public final float FX3_USB_CLOCK_FREQ = 80.0f * FX3_CLOCK_CORRECTION;
public float adcClockFreq = 30.0f;
/**
* Starts reader buffer pool thread and enables in endpoints for AEs. This
* method is overridden to construct
* our own reader with its translateEvents method
*/
@Override
public void startAEReader() throws HardwareInterfaceException {
setAeReader(new RetinaAEReader(this));
allocateAEBuffers();
// Update ADC clock frequency information.
if (getPID() == PID_FX2) {
adcClockFreq = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 4);
}
else {
adcClockFreq = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 4) * FX3_CLOCK_CORRECTION;
}
getAeReader().startThread(); // arg is number of errors before giving up
HardwareInterfaceException.clearException();
}
@Override
protected int adjustHWParam(final short moduleAddr, final short paramAddr, int param) {
if ((moduleAddr == FPGA_APS) && (paramAddr == 13)) {
// Exposure multiplied by clock.
return (int) (param * adcClockFreq);
}
if ((moduleAddr == FPGA_APS) && (paramAddr == 14)) {
// FrameDelay multiplied by clock.
return (int) (param * adcClockFreq);
}
if ((moduleAddr == FPGA_USB) && (paramAddr == 1)) {
// Early packet delay is 125µs slices on host, but in cycles
// @ USB_CLOCK_FREQ on FPGA, so we must multiply here.
if (getPID() == PID_FX2) {
return (int) (param * (125.0f * FX2_USB_CLOCK_FREQ));
}
return (int) (param * (125.0f * FX3_USB_CLOCK_FREQ));
}
// No change by default.
return (param);
}
public static final int CHIP_DAVIS240A = 0;
public static final int CHIP_DAVIS240B = 1;
public static final int CHIP_DAVIS240C = 2;
public static final int CHIP_DAVIS128 = 3;
public static final int CHIP_DAVIS346A = 4;
public static final int CHIP_DAVIS346B = 5;
public static final int CHIP_DAVIS640 = 6;
public static final int CHIP_DAVISRGB = 7;
public static final int CHIP_DAVIS208 = 8;
public static final int CHIP_DAVIS346C = 9;
/**
* This reader understands the format of raw USB data and translates to the
* AEPacketRaw
*/
public class RetinaAEReader extends CypressFX3.AEReader implements PropertyChangeListener {
private final int chipID;
private int wrapAdd;
private int lastTimestamp;
private int currentTimestamp;
private int dvsLastY;
private boolean dvsGotY;
private final boolean dvsInvertXY;
private final int dvsSizeX;
private final int dvsSizeY;
private static final int APS_READOUT_TYPES_NUM = 2;
private static final int APS_READOUT_RESET = 0;
private static final int APS_READOUT_SIGNAL = 1;
private boolean apsResetRead;
private int apsCurrentReadoutType;
private int apsRGBPixelOffset;
private boolean apsRGBPixelOffsetDirection;
private final short[] apsCountX;
private final short[] apsCountY;
private final boolean apsInvertXY;
private final boolean apsFlipX;
private final boolean apsFlipY;
private final int apsSizeX;
private final int apsSizeY;
private static final int IMU_DATA_LENGTH = 7;
private final short[] imuEvents;
private final boolean imuFlipX;
private final boolean imuFlipY;
private final boolean imuFlipZ;
private int imuCount;
private byte imuTmpData;
public RetinaAEReader(final CypressFX3 cypress) throws HardwareInterfaceException {
super(cypress);
if (getPID() == PID_FX2) {
// FX2 firmware now emulates the same interface as FX3 firmware, so we support it here too.
checkFirmwareLogic(DAViSFX3HardwareInterface.REQUIRED_FIRMWARE_VERSION_FX2,
DAViSFX3HardwareInterface.REQUIRED_LOGIC_REVISION_FX2);
}
else {
checkFirmwareLogic(DAViSFX3HardwareInterface.REQUIRED_FIRMWARE_VERSION_FX3,
DAViSFX3HardwareInterface.REQUIRED_LOGIC_REVISION_FX3);
}
apsCountX = new short[RetinaAEReader.APS_READOUT_TYPES_NUM];
apsCountY = new short[RetinaAEReader.APS_READOUT_TYPES_NUM];
initFrame();
imuEvents = new short[RetinaAEReader.IMU_DATA_LENGTH];
chipID = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 1);
apsSizeX = spiConfigReceive(CypressFX3.FPGA_APS, (short) 0);
apsSizeY = spiConfigReceive(CypressFX3.FPGA_APS, (short) 1);
final int chipAPSStreamStart = spiConfigReceive(CypressFX3.FPGA_APS, (short) 2);
apsInvertXY = (chipAPSStreamStart & 0x04) != 0;
apsFlipX = (chipAPSStreamStart & 0x02) != 0;
apsFlipY = (chipAPSStreamStart & 0x01) != 0;
dvsSizeX = spiConfigReceive(CypressFX3.FPGA_DVS, (short) 0);
dvsSizeY = spiConfigReceive(CypressFX3.FPGA_DVS, (short) 1);
dvsInvertXY = (spiConfigReceive(CypressFX3.FPGA_DVS, (short) 2) & 0x04) != 0;
final int imuOrientation = spiConfigReceive(CypressFX3.FPGA_IMU, (short) 10);
imuFlipX = (imuOrientation & 0x04) != 0;
imuFlipY = (imuOrientation & 0x02) != 0;
imuFlipZ = (imuOrientation & 0x01) != 0;
updateTimestampMasterStatus();
}
private void checkMonotonicTimestamp() {
if (currentTimestamp <= lastTimestamp) {
CypressFX3.log.severe(toString() + ": non strictly-monotonic timestamp detected: lastTimestamp=" + lastTimestamp
+ ", currentTimestamp=" + currentTimestamp + ", difference=" + (lastTimestamp - currentTimestamp) + ".");
}
}
private void initFrame() {
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_RESET;
Arrays.fill(apsCountX, 0, RetinaAEReader.APS_READOUT_TYPES_NUM, (short) 0);
Arrays.fill(apsCountY, 0, RetinaAEReader.APS_READOUT_TYPES_NUM, (short) 0);
}
private boolean ensureCapacity(final AEPacketRaw buffer, final int capacity) {
if (buffer.getCapacity() > getAEBufferSize()) {
if (buffer.overrunOccuredFlag || (capacity > buffer.getCapacity())) {
buffer.overrunOccuredFlag = true;
return (false);
}
return (true);
}
buffer.ensureCapacity(capacity);
return (true);
}
@Override
protected void translateEvents(final ByteBuffer b) {
synchronized (aePacketRawPool) {
final AEPacketRaw buffer = aePacketRawPool.writeBuffer();
// Truncate off any extra partial event.
if ((b.limit() & 0x01) != 0) {
CypressFX3.log.severe(b.limit() + " bytes received via USB, which is not a multiple of two.");
b.limit(b.limit() & ~0x01);
}
buffer.lastCaptureIndex = eventCounter;
final ShortBuffer sBuf = b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
for (int i = 0; i < sBuf.limit(); i++) {
final short event = sBuf.get(i);
// Check if timestamp
if ((event & 0x8000) != 0) {
// Is a timestamp! Expand to 32 bits. (Tick is 1us already.)
lastTimestamp = currentTimestamp;
currentTimestamp = wrapAdd + (event & 0x7FFF);
// Check monotonicity of timestamps.
checkMonotonicTimestamp();
}
else {
// Look at the code, to determine event and data
// type
final byte code = (byte) ((event & 0x7000) >>> 12);
final short data = (short) (event & 0x0FFF);
switch (code) {
case 0: // Special event
switch (data) {
case 0: // Ignore this, but log it.
CypressFX3.log.severe("Caught special reserved event!");
break;
case 1: // Timetamp reset
wrapAdd = 0;
lastTimestamp = 0;
currentTimestamp = 0;
updateTimestampMasterStatus();
CypressFX3.log.info("Timestamp reset event received on " + super.toString()
+ " at System.currentTimeMillis()=" + System.currentTimeMillis());
break;
case 2: // External input (falling edge)
case 3: // External input (rising edge)
case 4: // External input (pulse)
CypressFX3.log.fine("External input event received.");
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
// tobi added data to pass thru rising falling and pulse events
buffer.getAddresses()[eventCounter] = DavisChip.EXTERNAL_INPUT_EVENT_ADDR + data;
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
break;
case 5: // IMU Start (6 axes)
CypressFX3.log.fine("IMU6 Start event received.");
imuCount = 0;
break;
case 7: // IMU End
CypressFX3.log.fine("IMU End event received.");
if (imuCount == ((2 * RetinaAEReader.IMU_DATA_LENGTH) + 1)) {
if (ensureCapacity(buffer, eventCounter + IMUSample.SIZE_EVENTS)) {
// Check for buffer space is also done inside writeToPacket().
final IMUSample imuSample = new IMUSample(currentTimestamp, imuEvents);
eventCounter += imuSample.writeToPacket(buffer, eventCounter);
}
}
else {
CypressFX3.log.info(
"IMU End: failed to validate IMU sample count (" + imuCount + "), discarding samples.");
}
break;
case 8: // APS Global Shutter Frame Start
CypressFX3.log.fine("APS GS Frame Start event received.");
apsResetRead = true;
initFrame();
break;
case 9: // APS Rolling Shutter Frame Start
CypressFX3.log.fine("APS RS Frame Start event received.");
apsResetRead = true;
initFrame();
break;
case 10: // APS Frame End
CypressFX3.log.fine("APS Frame End event received.");
for (int j = 0; j < RetinaAEReader.APS_READOUT_TYPES_NUM; j++) {
int checkValue = apsSizeX;
// Check reset read against zero if
// disabled.
if ((j == RetinaAEReader.APS_READOUT_RESET) && !apsResetRead) {
checkValue = 0;
}
if (apsCountX[j] != checkValue) {
CypressFX3.log.severe("APS Frame End: wrong column count [" + j + " - " + apsCountX[j]
+ "] detected. You might want to enable 'Ensure APS data transfer' under 'HW Configuration -> Chip Configuration' to improve this.");
}
}
break;
case 11: // APS Reset Column Start
CypressFX3.log.fine("APS Reset Column Start event received.");
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_RESET;
apsCountY[apsCurrentReadoutType] = 0;
apsRGBPixelOffsetDirection = false;
apsRGBPixelOffset = 1; // RGB support, first pixel of row always even.
break;
case 12: // APS Signal Column Start
CypressFX3.log.fine("APS Signal Column Start event received.");
apsCurrentReadoutType = RetinaAEReader.APS_READOUT_SIGNAL;
apsCountY[apsCurrentReadoutType] = 0;
apsRGBPixelOffsetDirection = false;
apsRGBPixelOffset = 1; // RGB support, first pixel of row always even.
break;
case 13: // APS Column End
CypressFX3.log.fine("APS Column End event received.");
if (apsCountY[apsCurrentReadoutType] != apsSizeY) {
CypressFX3.log.severe("APS Column End: wrong row count [" + apsCurrentReadoutType + " - "
+ apsCountY[apsCurrentReadoutType]
+ "] detected. You might want to enable 'Ensure APS data transfer' under 'HW Configuration -> Chip Configuration' to improve this.");
}
apsCountX[apsCurrentReadoutType]++;
break;
case 14: // APS Global Shutter Frame Start with no Reset Read
CypressFX3.log.fine("APS GS NORST Frame Start event received.");
apsResetRead = false;
initFrame();
break;
case 15: // APS Rolling Shutter Frame Start with no Reset Read
CypressFX3.log.fine("APS RS NORST Frame Start event received.");
apsResetRead = false;
initFrame();
break;
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
CypressFX3.log.fine("IMU Scale Config event (" + data + ") received.");
// At this point the IMU event count should be zero (reset by start).
if (imuCount != 0) {
CypressFX3.log.info("IMU Scale Config: previous IMU start event missed, attempting recovery.");
}
// Increase IMU count by one, to a total of one (0+1=1).
// This way we can recover from the above error of missing start, and we can
// later discover if the IMU Scale Config event actually arrived itself.
imuCount = 1;
break;
case 32:
case 33:
case 34:
case 35:
// TODO: ROI OFF not exposed, so just ignore events.
break;
case 48:
// TODO: APS Exposure Information, ignore for now.
break;
case 49:
case 50:
case 51:
case 52:
// TODO: ROI ON not exposed, so just ignore events.
break;
default:
CypressFX3.log.severe("Caught special event that can't be handled.");
break;
}
break;
case 1: // Y address
// Check range conformity.
if (data >= dvsSizeY) {
CypressFX3.log.severe("DVS: Y address out of range (0-" + (dvsSizeY - 1) + "): " + data + ".");
break; // Skip invalid Y address (don't update lastY).
}
if (dvsGotY) {
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
buffer.getAddresses()[eventCounter] = ((dvsLastY << DavisChip.YSHIFT) & DavisChip.YMASK);
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
CypressFX3.log.fine("DVS: row-only event received for address Y=" + dvsLastY + ".");
}
dvsLastY = data;
dvsGotY = true;
break;
case 2: // X address, Polarity OFF
case 3: // X address, Polarity ON
// Check range conformity.
if (data >= dvsSizeX) {
CypressFX3.log.severe("DVS: X address out of range (0-" + (dvsSizeX - 1) + "): " + data + ".");
break; // Skip invalid event.
}
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
// The X address comes out of the new logic such that the (0, 0) address
// is, as expected by most, in the lower left corner. Since the DAVIS240
// chip class data format assumes that this is still flipped, as in the
// old logic, we have to flip it here, so that the chip class extractor
// can flip it back. Backwards compatibility with recordings is the main
// motivation to do this hack.
// NOTE 09.2017: logic now uses upper left (CG format) as output.
// Invert polarity for PixelParade high gain pixels (DavisSense), because of
// negative gain from pre-amplifier.
final byte polarity = ((chipID == DAViSFX3HardwareInterface.CHIP_DAVIS208) && (data < 192))
? ((byte) (~code)) : (code);
if (dvsInvertXY) {
buffer.getAddresses()[eventCounter] = (((dvsSizeX - 1 - data) << DavisChip.YSHIFT) & DavisChip.YMASK)
| (((dvsSizeY - 1 - dvsLastY) << DavisChip.XSHIFT) & DavisChip.XMASK)
| (((polarity & 0x01) << DavisChip.POLSHIFT) & DavisChip.POLMASK);
}
else {
buffer.getAddresses()[eventCounter] = (((dvsSizeY - 1 - dvsLastY) << DavisChip.YSHIFT) & DavisChip.YMASK)
| (((dvsSizeX - 1 - data) << DavisChip.XSHIFT) & DavisChip.XMASK)
| (((polarity & 0x01) << DavisChip.POLSHIFT) & DavisChip.POLMASK);
}
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
dvsGotY = false;
break;
case 4: // APS ADC sample
// Let's check that apsCountY is not above the maximum. This could happen
// if start/end of column events are discarded (no wait on transfer stall).
if (apsCountY[apsCurrentReadoutType] >= apsSizeY) {
CypressFX3.log.fine("APS ADC sample: row count is at maximum, discarding further samples.");
break;
}
// The DAVIS240c chip is flipped along the X axis. This means it's first reading
// out the leftmost columns, and not the rightmost ones as in all the other chips.
// So, if a 240c is detected, we don't do the artificial sign flip here.
int xPos;
int yPos;
if (apsFlipX) {
xPos = apsSizeX - 1 - apsCountX[apsCurrentReadoutType];
}
else {
xPos = apsCountX[apsCurrentReadoutType];
}
if (apsFlipY) {
yPos = apsSizeY - 1 - apsCountY[apsCurrentReadoutType];
}
else {
yPos = apsCountY[apsCurrentReadoutType];
}
if (chipID == DAViSFX3HardwareInterface.CHIP_DAVISRGB) {
yPos += apsRGBPixelOffset;
}
if (apsInvertXY) {
final int temp = xPos;
xPos = yPos;
yPos = temp;
}
// NOTE 09.2017: logic now uses upper left (CG format) as output.
yPos = (apsInvertXY) ? (apsSizeX - 1 - yPos) : (apsSizeY - 1 - yPos);
apsCountY[apsCurrentReadoutType]++;
// RGB support: first 320 pixels are even, then odd.
if (!apsRGBPixelOffsetDirection) { // Increasing
apsRGBPixelOffset++;
if (apsRGBPixelOffset == 321) {
// Switch to decreasing after last even pixel.
apsRGBPixelOffsetDirection = true;
apsRGBPixelOffset = 318;
}
}
else { // Decreasing
apsRGBPixelOffset -= 3;
}
// Check that the buffer has space for this event. Enlarge if needed.
if (ensureCapacity(buffer, eventCounter + 1)) {
buffer.getAddresses()[eventCounter] = DavisChip.ADDRESS_TYPE_APS
| ((yPos << DavisChip.YSHIFT) & DavisChip.YMASK) | ((xPos << DavisChip.XSHIFT) & DavisChip.XMASK)
| ((apsCurrentReadoutType << DavisChip.ADC_READCYCLE_SHIFT) & DavisChip.ADC_READCYCLE_MASK)
| (data & DavisChip.ADC_DATA_MASK);
buffer.getTimestamps()[eventCounter++] = currentTimestamp;
}
break;
case 5: // Misc 8bit data.
final byte misc8Code = (byte) ((data & 0x0F00) >>> 8);
final byte misc8Data = (byte) (data & 0x00FF);
switch (misc8Code) {
case 0:
// Detect missing IMU end events.
if (imuCount >= ((2 * RetinaAEReader.IMU_DATA_LENGTH) + 1)) {
CypressFX3.log.info("IMU data: IMU samples count is at maximum, discarding further samples.");
break;
}
// IMU data event.
switch (imuCount) {
case 0:
CypressFX3.log.severe(
"IMU data: missing IMU Scale Config event. Parsing of IMU events will still be attempted, but be aware that Accel/Gyro scale conversions may be inaccurate.");
imuCount = 1;
// Fall through to next case, as if imuCount was equal to 1.
case 1:
case 3:
case 5:
case 7:
case 9:
case 11:
case 13:
imuTmpData = misc8Data;
break;
case 2: // Accel X
imuEvents[0] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipX) {
imuEvents[0] = (short) -imuEvents[0];
}
break;
case 4: // Accel Y
imuEvents[1] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipY) {
imuEvents[1] = (short) -imuEvents[1];
}
break;
case 6: // Accel Z
imuEvents[2] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipZ) {
imuEvents[2] = (short) -imuEvents[2];
}
break;
case 8: // Temperature
imuEvents[3] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
break;
case 10: // Gyro X
imuEvents[4] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipX) {
imuEvents[4] = (short) -imuEvents[4];
}
break;
case 12: // Gyro Y
imuEvents[5] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipY) {
imuEvents[5] = (short) -imuEvents[5];
}
break;
case 14: // Gyro Z
imuEvents[6] = (short) (((imuTmpData & 0x00FF) << 8) | (misc8Data & 0x00FF));
if (imuFlipZ) {
imuEvents[6] = (short) -imuEvents[6];
}
break;
}
imuCount++;
break;
case 1:
case 2:
// Ignore ROI events.
break;
default:
CypressFX3.log.severe("Caught Misc8 event that can't be handled.");
break;
}
break;
case 6: // Misc 10bit data.
final byte misc10Code = (byte) ((data & 0x0C00) >>> 10);
final short misc10Data = (short) (data & 0x03FF);
switch (misc10Code) {
case 0:
// TODO: APS Exposure Information, ignore for now.
break;
default:
CypressFX3.log.severe("Caught Misc10 event that can't be handled.");
break;
}
break;
case 7: // Timestamp wrap
// Each wrap is 2^15 us (~32ms), and we have
// to multiply it with the wrap counter,
// which is located in the data part of this
// event.
wrapAdd += (0x8000L * data);
lastTimestamp = currentTimestamp;
currentTimestamp = wrapAdd;
// Check monotonicity of timestamps.
checkMonotonicTimestamp();
CypressFX3.log.fine(
String.format("Timestamp wrap event received on %s with multiplier of %d.", super.toString(), data));
break;
default:
CypressFX3.log.severe("Caught event that can't be handled.");
break;
}
}
} // end loop over usb data buffer
buffer.setNumEvents(eventCounter);
// write capture size
buffer.lastCaptureLength = eventCounter - buffer.lastCaptureIndex;
} // sync on aePacketRawPool
}
@Override
public void propertyChange(final PropertyChangeEvent arg0) {
// Do nothing here, IMU comes directly via event-stream.
}
}
}
|
DAVISFX3HardwareInterface: update for logic version 16.
|
src/net/sf/jaer/hardwareinterface/usb/cypressfx3libusb/DAViSFX3HardwareInterface.java
|
DAVISFX3HardwareInterface: update for logic version 16.
|
|
Java
|
lgpl-2.1
|
5884037d7db00539965fff6240d0f6ed70d83e2a
| 0
|
zear/fled
|
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.filechooser.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
enum EditMode
{
MODE_NONE,
MODE_TILE_EDIT,
MODE_OBJECT_EDIT,
MODE_LEVEL_EDIT
}
class Data
{
private static String dataDirectory = ".."; // default location
public static String getDataDirectory()
{
return dataDirectory;
}
public static void setDataDirectory(String dataDirectory)
{
Data.dataDirectory = dataDirectory;
}
}
class NewLevelSetup extends JDialog implements ActionListener
{
private GridLayout windowLayout = new GridLayout(3, 1);
private JPanel windowContainer = new JPanel(windowLayout);
private JPanel fieldContainer = new JPanel(new GridLayout(1, 4));
private JPanel buttonContainer = new JPanel(new GridLayout(1, 2));
private JLabel labelSize = new JLabel("New level size:");
private JLabel labelSizeX = new JLabel("x:");
private JLabel labelSizeY = new JLabel("y:");
private JFormattedTextField fieldSizeX;
private JFormattedTextField fieldSizeY;
private JButton buttonCancel = new JButton("Cancel");
private JButton buttonCreate = new JButton("Create");
private Menu menu = null;
private boolean choice;
public NewLevelSetup(String caption, Menu newMenu)
{
this.setTitle(caption);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
this.menu = newMenu;
this.fieldSizeX = new JFormattedTextField(this.menu.getSizeX());
this.fieldSizeY = new JFormattedTextField(this.menu.getSizeY());
this.fieldSizeX.setColumns(3);
this.fieldSizeY.setColumns(3);
this.labelSize.setHorizontalAlignment(JLabel.CENTER);
this.labelSizeX.setHorizontalAlignment(JLabel.CENTER);
this.labelSizeY.setHorizontalAlignment(JLabel.CENTER);
fieldSizeX.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
int value = ((Number)fieldSizeX.getValue()).intValue();
if (value < 20)
{
value = 20;
fieldSizeX.setValue(value);
}
else if (value > 500)
{
value = 500;
fieldSizeX.setValue(value);
}
}
});
fieldSizeY.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
int value = ((Number)fieldSizeY.getValue()).intValue();
if (value < 20)
{
value = 20;
fieldSizeY.setValue(value);
}
else if (value > 500)
{
value = 500;
fieldSizeY.setValue(value);
}
}
});
buttonCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
choice = false;
setVisible(false);
dispose();
}
});
buttonCreate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
menu.setSizeX(((Number)fieldSizeX.getValue()).intValue());
menu.setSizeY(((Number)fieldSizeY.getValue()).intValue());
choice = true;
setVisible(false);
dispose();
}
});
fieldContainer.add(labelSizeX);
fieldContainer.add(fieldSizeX);
fieldContainer.add(labelSizeY);
fieldContainer.add(fieldSizeY);
buttonContainer.add(buttonCancel);
buttonContainer.add(buttonCreate);
windowLayout.setVgap(5);
windowContainer.add(labelSize);
windowContainer.add(fieldContainer);
windowContainer.add(buttonContainer);
this.add(windowContainer);
// this.pack();
// this.setVisible(true);
}
public boolean getChoice()
{
return this.choice;
}
public void actionPerformed(ActionEvent e)
{
this.choice = false;
setVisible(false);
dispose();
}
}
class Menu extends JMenuBar
{
private JMenu fileMenu = new JMenu("File");
private JMenuItem fileNew = new JMenuItem("New level");
private JMenuItem fileOpen = new JMenuItem("Open level");
private JMenuItem fileSave = new JMenuItem("Save level");
private JMenuItem fileSaveAs = new JMenuItem("Save level as...");
private JMenuItem fileQuit = new JMenuItem("Quit editor");
private JMenu runMenu = new JMenu("Run");
private JMenuItem runSetExec = new JMenuItem("Set executable location");
private JMenuItem runRunLevel = new JMenuItem("Run level");
private JMenu helpMenu = new JMenu("Help");
private JMenuItem helpAbout = new JMenuItem("About");
private JFileChooser fileChooser = new JFileChooser(Data.getDataDirectory());
private MapPanel mapPanel = null;
private TilesetPanel tilesetPanel = null;
private ToolbarPanel toolbarPanel = null;
private ObjectPanel objectPanel = null;
private int newSizeX = 20;
private int newSizeY = 20;
public Menu()
{
this.add(fileMenu);
fileMenu.add(fileNew);
fileMenu.add(fileOpen);
fileMenu.add(fileSave);
fileMenu.add(fileSaveAs);
fileMenu.add(fileQuit);
this.add(runMenu);
runMenu.add(runSetExec);
runMenu.add(runRunLevel);
this.add(helpMenu);
helpMenu.add(helpAbout);
fileNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// create new level
if(showNewLevelSetup())
{
mapPanel.level = new Level(newSizeX, newSizeY);
tilesetPanel.setImage(0, mapPanel.level.getLayer(1).getImg());
tilesetPanel.showLayer[0] = true;
tilesetPanel.defaultSettings();
for(int i = 0; i < mapPanel.level.getNumOfLayers(); i++)
{
BufferedImage defMapImg = new BufferedImage(mapPanel.level.getLayer(i).getWidth() * 16, mapPanel.level.getLayer(i).getHeight() * 16, BufferedImage.TYPE_INT_ARGB);
mapPanel.setImage(i, defMapImg);
mapPanel.showLayer[i] = true;
}
if(mapPanel.drawAreaLayers.size() >= 1)
mapPanel.paintOnLayer = 1; // We assume that layer 1 is the "walkable" layer
int levelWidth;
int levelHeight;
int tile = 0;
for(int n = 0; n < mapPanel.drawAreaLayers.size(); n++)
{
levelWidth = mapPanel.level.getLayer(n).getWidth() * 16;
levelHeight = mapPanel.level.getLayer(n).getHeight() * 16;
for(int i = 0, x = 0; i < levelWidth; i+=16, x++)
{
for(int j = 0, y = 0; j < levelHeight; j+=16, y++)
{
tile = mapPanel.level.getLayer(n).getTile(x, y);
mapPanel.paintTile(n, tile, i, j, false);
}
}
}
toolbarPanel.defaultSettings();
if(mapPanel.drawAreaLayers.size() > 0)
{
mapPanel.setPreferredSize(new Dimension(mapPanel.drawAreaLayers.get(0).getWidth(),mapPanel.drawAreaLayers.get(0).getHeight()));
mapPanel.revalidate();
}
objectPanel.loadObjects();
}
}
});
fileOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// open existing level
int choice = fileChooser.showOpenDialog(fileChooser);
//fileChooser.setFileFilter(new FileFilter(""));
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level = new Level(file);
// Set tileset panel image
tilesetPanel.setImage(0, mapPanel.level.getLayer(1).getImg());
tilesetPanel.showLayer[0] = true;
tilesetPanel.defaultSettings();
// Set map panel images
for(int n = 0; n < mapPanel.level.getNumOfLayers(); n++)
{
BufferedImage defMapImg = new BufferedImage(mapPanel.level.getLayer(n).getWidth() * 16, mapPanel.level.getLayer(n).getHeight() * 16, BufferedImage.TYPE_INT_ARGB);
mapPanel.setImage(n, defMapImg);
mapPanel.showLayer[n] = true;
}
if(mapPanel.drawAreaLayers.size() >= 1)
mapPanel.paintOnLayer = 1; // We assume that layer 1 is the "walkable" layer
int levelWidth;
int levelHeight;
int tile = 0;
for(int n = 0; n < mapPanel.drawAreaLayers.size(); n++)
{
levelWidth = mapPanel.level.getLayer(n).getWidth() * 16;
levelHeight = mapPanel.level.getLayer(n).getHeight() * 16;
for(int i = 0, x = 0; i < levelWidth; i+=16, x++)
{
for(int j = 0, y = 0; j < levelHeight; j+=16, y++)
{
tile = mapPanel.level.getLayer(n).getTile(x, y);
mapPanel.paintTile(n, tile, i, j, false);
}
}
}
toolbarPanel.defaultSettings();
if(mapPanel.drawAreaLayers.size() > 0)
{
mapPanel.setPreferredSize(new Dimension(mapPanel.drawAreaLayers.get(0).getWidth(),mapPanel.drawAreaLayers.get(0).getHeight()));
mapPanel.revalidate();
}
objectPanel.loadObjects();
}
}
});
fileSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// save current level
if(mapPanel.level != null)
{
if(mapPanel.level.getFilePath() != null)
{
mapPanel.level.write(mapPanel.level.getFilePath());
}
else
{
// ask for the file name
int choice = fileChooser.showSaveDialog(fileChooser);
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level.setFilePath(file);
mapPanel.level.write(mapPanel.level.getFilePath());
}
}
}
}
});
fileSaveAs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(mapPanel.level != null)
{
// save current level under a different name
int choice = fileChooser.showSaveDialog(fileChooser);
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level.setFilePath(file);
mapPanel.level.write(mapPanel.level.getFilePath());
}
}
}
});
fileQuit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// quit program
System.out.printf("Pressed Quit\n"); // TODO
}
});
runRunLevel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(mapPanel.level != null)
{
boolean playerObjPresent = false;
ListIterator<GameObject> objsli = mapPanel.level.getObjectList().listIterator();
while (objsli.hasNext())
{
if(objsli.next().getName().equals("player"))
playerObjPresent = true;
}
if(!playerObjPresent) // Don't launch the level if player object is missing.
{
JOptionPane.showMessageDialog(runRunLevel, "Add a player object first.");
return;
}
File path = new File(Data.getDataDirectory() + "/frog.jar");
if(!path.exists() || path.isDirectory())
{
JOptionPane.showMessageDialog(runRunLevel, "ERROR: Missing game executable at location:\n" + path.getAbsolutePath(), "Game launch issue", JOptionPane.ERROR_MESSAGE);
}
// save current level to a temporary file
mapPanel.level.write(new File(Data.getDataDirectory() + "/lvl.tmp"));
// run level
ProcessBuilder builder = new ProcessBuilder("java", "-jar", path.getAbsolutePath(), "-l", "./lvl.tmp", "-nojoy");
builder.environment().put("LD_LIBRARY_PATH","lib");
builder.directory(new File(Data.getDataDirectory()).getAbsoluteFile());
builder.redirectErrorStream(true);
File log = new File("runlog.tmp");
builder.redirectOutput(ProcessBuilder.Redirect.to(log));
Process proc;
try
{
System.out.printf("Launching game... (log: %s)\n", log.getAbsolutePath());
proc = builder.start();
assert builder.redirectInput() == ProcessBuilder.Redirect.PIPE;
assert builder.redirectOutput().file() == log;
assert proc.getInputStream().read() == -1;
}
catch (IOException ioe)
{
System.out.printf("Failed to launch the game:\n%s\n", ioe.getMessage());
JOptionPane.showMessageDialog(runRunLevel, "ERROR: " + ioe.getMessage(), "Game launch issue", JOptionPane.ERROR_MESSAGE);
}
}
}
});
helpAbout.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(helpAbout,
"\nFROG Level Editor version 0.0.1\n\n" +
"Copyright © 2014 Artur Rojek\n" +
"Licensed under LGPL v2 +", "About", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("./data/about.png"));
}
});
}
public void setPanels(MapPanel newMapPanel, TilesetPanel newTilesetPanel, ToolbarPanel newToolbarPanel, ObjectPanel newObjectPanel)
{
this.mapPanel = newMapPanel;
this.tilesetPanel = newTilesetPanel;
this.toolbarPanel = newToolbarPanel;
this.objectPanel = newObjectPanel;
}
public void setSizeX(int size)
{
this.newSizeX = size;
}
public void setSizeY(int size)
{
this.newSizeY = size;
}
public int getSizeX()
{
return this.newSizeX;
}
public int getSizeY()
{
return this.newSizeY;
}
public boolean showNewLevelSetup()
{
NewLevelSetup dialog = new NewLevelSetup("Create level", this);
//dialog.setPreferredSize(new Dimension(320, 240));
dialog.setLocationRelativeTo(this);
dialog.pack();
dialog.setVisible(true);
return dialog.getChoice();
}
}
class MapPanel extends DrawPanel implements MouseInputListener
{
public Level level = null;
private TilesetPanel tileset = null;
private TileInfoPanel tileInfoPanel = null;
private ObjectPanel objectPanel = null;
private EditMode editMode = EditMode.MODE_TILE_EDIT;
private boolean canPaint = false;
private int paintX = 0;
private int paintY = 0;
private int lastPaintOnLayer = 1;
private int lastTile = 0;
private GameObject selectedObject = null;
private boolean draggingObject = false;
protected boolean showGrid = true;
public EditMode getEditMode()
{
return this.editMode;
}
public void setEditMode(EditMode newEditMode)
{
this.editMode = newEditMode;
}
public void paintTile(int layer, int num, int x, int y, boolean repaint)
{
if (this.tileset == null)
{
System.out.printf("Tileset is empty!\n");
return;
}
if (this.level == null)
{
System.out.printf("No level loaded!\n");
return;
}
if (layer >= this.drawAreaLayers.size())
{
System.out.printf("No such layer: %d!\n", layer);
return;
}
int tileX = num%16;
int tileY = num/16;
super.blit(layer, this.tileset.getImage(0), x, y, x + 16, y + 16, tileX * 16, tileY * 16, tileX * 16 + 16, tileY * 16 + 16);
if(repaint)
{
super.repaint();
}
}
public void paintTile(int x, int y)
{
if (this.tileset == null)
{
System.out.printf("Tileset is empty!\n");
return;
}
int tileNum = tileset.getSelY() * 16 + tileset.getSelX();
this.level.getLayer(super.paintOnLayer).setTile(x/16, y/16, tileNum);
super.blit(super.paintOnLayer, this.tileset.getImage(0), x, y, x + 16, y + 16, this.tileset.getSelX() * 16, this.tileset.getSelY() * 16, this.tileset.getSelX() * 16 + 16, this.tileset.getSelY() * 16 + 16);
super.repaint();
}
public void setPanels(TilesetPanel newTileset, TileInfoPanel newTileInfoPanel, ObjectPanel newObjectPanel)
{
this.tileset = newTileset;
this.tileInfoPanel = newTileInfoPanel;
this.objectPanel = newObjectPanel;
}
private boolean isInMapArea(int x, int y)
{
if(super.drawAreaLayers.size() < 1)
return false;
if(super.drawAreaLayers.get(0) == null)
return false;
if (x < 0)
return false;
else if (x >= super.drawAreaLayers.get(0).getWidth())
return false;
else if (y < 0)
return false;
else if (y >= super.drawAreaLayers.get(0).getHeight())
return false;
else
{
return true;
}
}
public void setSelectedObject(GameObject selectedObject)
{
this.selectedObject = selectedObject;
this.repaint();
}
// mouse listener
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
this.canPaint = false;
break;
default:
break;
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
if(this.draggingObject)
this.draggingObject = false;
}
break;
default:
break;
}
}
}
public void mousePressed(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
if(this.level != null && this.level.getNumOfLayers() > 0 && this.tileset != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
this.canPaint = true;
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
int curTile = this.tileset.getSelY() * 16 + this.tileset.getSelX();
if(this.paintX != curX || this.paintY != curY || this.lastPaintOnLayer != super.paintOnLayer || this.lastTile != curTile)
{
if((this.canPaint) && (this.isInMapArea(e.getX(), e.getY())))
{
this.paintX = e.getX()/16*16;
this.paintY = e.getY()/16*16;
this.lastPaintOnLayer = super.paintOnLayer;
this.lastTile = curTile;
this.paintTile(this.paintX, this.paintY);
}
}
}
break;
case InputEvent.BUTTON3_MASK:
{
int tile = this.level.getLayer(super.paintOnLayer).getTile(e.getX()/16, e.getY()/16);
int x = tile % 16;
int y = tile / 16;
this.tileset.setSelX(x);
this.tileset.setSelY(y);
this.tileset.repaint();
if(this.tileInfoPanel != null)
this.tileInfoPanel.updateInfo(x, y);
}
break;
default:
break;
}
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null && this.objectPanel != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
int objX;
int objY;
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
if(!this.draggingObject)
{
for(GameObject curObj : this.level.getObjectList())
{
if(curObj.getX()/16*16 == curX && curObj.getY()/16*16 == curY)
{
this.selectedObject = curObj;
this.draggingObject = true;
this.objectPanel.setSelectedObject(curObj);
this.repaint();
break;
}
}
}
}
break;
case InputEvent.BUTTON3_MASK:
break;
default:
break;
}
}
}
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
int curTile = this.tileset.getSelY() * 16 + this.tileset.getSelX();
if(this.paintX != curX || this.paintY != curY || this.lastPaintOnLayer != super.paintOnLayer || this.lastTile != curTile)
{
if((this.canPaint) && (this.isInMapArea(e.getX(), e.getY())))
{
this.paintX = curX;
this.paintY = curY;
this.lastPaintOnLayer = super.paintOnLayer;
this.lastTile = curTile;
this.paintTile(this.paintX, this.paintY);
}
}
}
break;
default:
break;
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null && this.objectPanel != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
if(this.selectedObject != null && this.draggingObject)
{
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
this.selectedObject.setX(curX);
this.selectedObject.setY(curY);
this.repaint();
}
}
break;
case InputEvent.BUTTON3_MASK:
break;
default:
break;
}
}
}
}
protected void draw(Graphics g)
{
// draw the level grid
if(this.showGrid)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(new Color(0, 0 ,0, 100));
if(this.level != null && this.level.getNumOfLayers() > 0)
{
for(int i = 0; i <= this.level.getLayer(0).getWidth(); i++)
{
// vertical
g2d.drawLine(i * 16, 0, i * 16, this.level.getLayer(0).getHeight() * 16);
}
for(int j = 0; j <= this.level.getLayer(0).getHeight(); j++)
{
// horizontal
g2d.drawLine(0, j * 16, this.level.getLayer(0).getWidth() * 16, j * 16);
}
}
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.draw(g);
// temp
if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null)
{
for(GameObject curObj : this.level.getObjectList())
{
Graphics2D g2d = (Graphics2D)g;
if(curObj == this.selectedObject)
g2d.setColor(Color.GREEN);
else
g2d.setColor(Color.RED);
// draw rectangle
g2d.drawLine(curObj.getX(), curObj.getY(), curObj.getX() + 16, curObj.getY());
g2d.drawLine(curObj.getX(), curObj.getY() + 16, curObj.getX() + 16, curObj.getY() + 16);
g2d.drawLine(curObj.getX(), curObj.getY(), curObj.getX(), curObj.getY() + 16);
g2d.drawLine(curObj.getX() + 16, curObj.getY(), curObj.getX() + 16, curObj.getY() + 16);
// draw diagonal line
if(curObj.getDirection())
g2d.drawLine(curObj.getX(), curObj.getY(), curObj.getX() + 16, curObj.getY() + 16);
else
g2d.drawLine(curObj.getX() + 16, curObj.getY(), curObj.getX(), curObj.getY() + 16);
}
}
}
}
}
class TilesetPanel extends DrawPanel implements MouseInputListener
{
private TileInfoPanel tileInfoPanel = null;
private int selX = 0;
private int selY = 0;
public int getSelX()
{
return this.selX;
}
public int getSelY()
{
return this.selY;
}
public void setSelX(int value)
{
this.selX = value;
}
public void setSelY(int value)
{
this.selY = value;
}
// mouse listener
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
if(super.drawAreaLayers.size() > 0 && super.drawAreaLayers.get(0) != null)
{
if(e.getX() > 0 && e.getX() < super.drawAreaLayers.get(0).getWidth() && e.getY() > 0 && e.getY() < super.drawAreaLayers.get(0).getHeight())
{
this.selX = e.getX()/16;
this.selY = e.getY()/16;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
super.repaint();
}
}
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
if(super.drawAreaLayers.size() > 0 && super.drawAreaLayers.get(0) != null)
{
if(e.getX() > 0 && e.getX() < super.drawAreaLayers.get(0).getWidth() && e.getY() > 0 && e.getY() < super.drawAreaLayers.get(0).getHeight())
{
this.selX = e.getX()/16;
this.selY = e.getY()/16;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
super.repaint();
}
}
}
protected void draw(Graphics g)
{
if(super.drawAreaLayers.size() > 0)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.yellow);
// top
g2d.drawLine(this.selX * 16, this.selY * 16, this.selX * 16 + 16, this.selY * 16);
// bottom
g2d.drawLine(this.selX * 16, this.selY * 16 + 16, this.selX * 16 + 16, this.selY * 16 + 16);
// left
g2d.drawLine(this.selX * 16, this.selY * 16, this.selX * 16, this.selY * 16 + 16);
// right
g2d.drawLine(this.selX * 16 + 16, this.selY * 16, this.selX * 16 + 16, this.selY * 16 + 16);
}
}
public void setTileInfoPanel(TileInfoPanel newInfoPanel)
{
this.tileInfoPanel = newInfoPanel;
}
public void defaultSettings()
{
this.selX = 0;
this.selY = 0;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.draw(g);
}
}
class DrawPanel extends JPanel
{
//protected BufferedImage drawArea = null;
protected LinkedList<BufferedImage> drawAreaLayers = new LinkedList<BufferedImage>();
protected boolean [] showLayer = new boolean[10]; // Let's hardcode the max number of layers to display for now.
protected int paintOnLayer = 0;
public LinkedList<BufferedImage> getLayers()
{
return this.drawAreaLayers;
}
public BufferedImage getImage(int layer)
{
return this.drawAreaLayers.get(layer);
}
public void setImage(int layer, BufferedImage src)
{
if(layer >= this.drawAreaLayers.size())
{
this.drawAreaLayers.push(src);
}
else
{
this.drawAreaLayers.set(layer, src);
}
super.repaint();
}
public void loadImage(int layer, String fileName)
{
if(fileName.equals(""))
return;
try
{
this.drawAreaLayers.set(layer, ImageIO.read(this.getClass().getResource("./data/" + fileName)));
}
catch (IOException e)
{
System.out.printf("ERROR: Failed to load image!");
}
}
public void blit(int layer, BufferedImage src, int destx1, int desty1, int destx2, int desty2, int srcx1, int srcy1, int srcx2, int srcy2)
{
if(this.drawAreaLayers.get(layer) != null && src != null)
{
BufferedImage dest = this.drawAreaLayers.get(layer);
dest.createGraphics().drawImage(src, destx1, desty1, destx2, desty2, srcx1, srcy1, srcx2, srcy2, null);
WritableRaster raster = dest.getRaster();
for(int j = desty1; j < desty2; j++)
{
for(int i = destx1; i < destx2; i++)
{
int [] pixels = raster.getPixel(i, j, (int[]) null);
if(pixels[0] == 255 && pixels[1] == 0 && pixels[2] == 255) // magenta
{
pixels[3] = 0;
raster.setPixel(i, j, pixels);
}
}
}
}
}
protected void draw(int layer, Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
if(layer < this.drawAreaLayers.size() && this.drawAreaLayers.get(layer) != null)
{
g2d.drawImage(drawAreaLayers.get(layer), 0, 0, null);
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < this.drawAreaLayers.size(); i++)
{
if(this.showLayer[this.drawAreaLayers.size() - 1 - i])
{
this.draw(this.drawAreaLayers.size() - 1 - i, g);
}
}
}
}
class TileInfoPanel extends JPanel
{
private JLabel infoLabel = new JLabel();
private String infoText;
TileInfoPanel()
{
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.infoLabel.setHorizontalAlignment(JLabel.LEFT);
this.defaultInfo();
this.add(infoLabel);
this.setVisible(true);
}
public void defaultInfo()
{
infoText = " ";
this.infoLabel.setText(this.infoText);
}
public void updateInfo(int tileX, int tileY)
{
int tile = tileY * 16 + tileX;
this.infoText = " Tile #" + tile + " (" + tileX + "," + tileY + ")";
this.infoLabel.setText(this.infoText);
}
}
class ToolbarPanel extends JPanel
{
private MapPanel mapPanel = null;
private TilesetPanel tilesetPanel = null;
private ButtonGroup radioLayers = new ButtonGroup();
private JRadioButton drawOnBackground = new JRadioButton("BGD");
private JRadioButton drawOnMiddleground = new JRadioButton("MGD");
private JRadioButton drawOnForeground = new JRadioButton("FGD");
private JCheckBox showBackground = new JCheckBox("BGD");
private JCheckBox showMiddleground = new JCheckBox("MGD");
private JCheckBox showForeground = new JCheckBox("FGD");
private JCheckBox showGrid = new JCheckBox("Tile grid");
private JLabel paintLabel = new JLabel("Draw on:");
private JLabel showLabel = new JLabel("Show:");
public ToolbarPanel()
{
this.setLayout(new GridLayout(6, 2));
this.radioLayers.add(drawOnBackground);
this.radioLayers.add(drawOnMiddleground);
this.radioLayers.add(drawOnForeground);
this.defaultSettings();
this.add(paintLabel);
this.add(showLabel);
this.add(drawOnBackground);
this.add(showBackground);
this.add(drawOnMiddleground);
this.add(showMiddleground);
this.add(drawOnForeground);
this.add(showForeground);
this.add(new JLabel("")); // add an empty cell
this.add(showGrid);
drawOnBackground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 2;
}
});
drawOnMiddleground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 1;
}
});
drawOnForeground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 0;
}
});
showBackground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnBackground.setEnabled(true);
mapPanel.showLayer[2] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnBackground.setEnabled(false);
if(drawOnBackground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[2] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showMiddleground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnMiddleground.setEnabled(true);
mapPanel.showLayer[1] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnMiddleground.setEnabled(false);
if(drawOnMiddleground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[1] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showForeground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnForeground.setEnabled(true);
mapPanel.showLayer[0] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnForeground.setEnabled(false);
if(drawOnForeground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[0] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showGrid.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
mapPanel.showGrid = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
mapPanel.showGrid = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
}
public void defaultSettings()
{
this.drawOnMiddleground.setSelected(true);
this.showBackground.setSelected(true);
this.showMiddleground.setSelected(true);
this.showForeground.setSelected(true);
this.showGrid.setSelected(true);
}
public void setPanels(MapPanel newMapPanel, TilesetPanel newTilesetPanel)
{
this.mapPanel = newMapPanel;
this.tilesetPanel = newTilesetPanel;
}
}
class ObjectPanel extends JPanel
{
private MapPanel mapPanel = null;
private ListCellRenderer<Object> renderer;
//private LinkedList<GameObject> availableObjectsList;
private LinkedList<GameObject> addedObjectsList;
private DefaultListModel<GameObject> availableListModel;
private DefaultListModel<GameObject> addedListModel;
private JList <GameObject> availableObjects;
private JList <GameObject> addedObjects;
private JScrollPane availablePane;
private JScrollPane addedPane;
private JButton buttonAdd = new JButton("Add");
private JButton buttonRemove = new JButton("Remove");
private ButtonGroup radioDirection = new ButtonGroup();
private JRadioButton directionLeft = new JRadioButton("left");
private JRadioButton directionRight = new JRadioButton("right");
class ObjectCellRenderer extends JLabel implements ListCellRenderer<Object>
{
public ObjectCellRenderer()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
if(value instanceof GameObject)
setText(((GameObject)value).getName() + " ["+((GameObject)value).getX()+","+((GameObject)value).getY()+"]");
else
setText(value.toString());
Color background;
Color foreground;
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null && !dropLocation.isInsert() && dropLocation.getIndex() == index)
{
background = Color.BLUE;
foreground = Color.WHITE;
// check if this cell is selected
}
else if (isSelected)
{
background = Color.BLUE;
foreground = Color.WHITE;
// unselected, and not the DnD drop location
}
else
{
background = Color.WHITE;
foreground = Color.BLACK;
}
setBackground(background);
setForeground(foreground);
return this;
}
}
public ObjectPanel()
{
this.renderer = new ObjectCellRenderer();
this.radioDirection.add(directionLeft);
this.radioDirection.add(directionRight);
buttonAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(availableListModel != null)
{
GameObject newObj = new GameObject();
int selectedIndex = availableObjects.getSelectedIndex();
if(selectedIndex != -1)
{
newObj.setName(availableListModel.get(selectedIndex).getName());
addedObjectsList.push(newObj);
addedListModel.addElement(newObj);
addedObjects.setSelectedValue(newObj, true);
}
mapPanel.repaint();
}
}
});
buttonRemove.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(addedListModel != null)
{
int selectedIndex = addedObjects.getSelectedIndex();
if(selectedIndex != -1)
{
GameObject objToRem = addedListModel.get(selectedIndex);
ListIterator<GameObject> objsli = addedObjectsList.listIterator();
while (objsli.hasNext())
{
if(objsli.next() == objToRem)
{
objsli.remove();
addedListModel.remove(selectedIndex);
addedObjects.setSelectedIndex(selectedIndex == 0 ? 0 : selectedIndex - 1);
break;
}
}
mapPanel.repaint();
}
}
}
});
directionLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(addedObjects != null && addedObjects.getSelectedIndex() != -1)
{
addedListModel.get(addedObjects.getSelectedIndex()).setDirection(false);
mapPanel.repaint();
}
}
});
directionRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(addedObjects != null && addedObjects.getSelectedIndex() != -1)
{
addedListModel.get(addedObjects.getSelectedIndex()).setDirection(true);
mapPanel.repaint();
}
}
});
}
void addListeners()
{
// if(availableObjects != null)
// {
// availableObjects.addListSelectionListener(new ListSelectionListener()
// {
// public void valueChanged(ListSelectionEvent e)
// {
// if(e.getValueIsAdjusting() == false)
// {
// if(availableObjects.getSelectedIndex() == -1)
// {
// //No selection
// }
// else
// {
// System.out.printf("Selected: %s [%d,%d]\n", availableListModel.get(availableObjects.getSelectedIndex()).getName(), availableListModel.get(availableObjects.getSelectedIndex()).getX(), availableListModel.get(availableObjects.getSelectedIndex()).getY());
// }
// }
// }
// });
// }
if(addedObjects != null)
{
addedObjects.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
if(e.getValueIsAdjusting() == false)
{
if(addedObjects.getSelectedIndex() == -1)
{
//No selection
}
else
{
GameObject selObj = addedListModel.get(addedObjects.getSelectedIndex());
mapPanel.setSelectedObject(selObj);
if(selObj.getDirection())
{
directionRight.setSelected(true);
}
else
{
directionLeft.setSelected(true);
}
}
}
}
});
}
}
void loadObjects()
{
this.availableListModel = new DefaultListModel<GameObject>();
this.addedListModel = new DefaultListModel<GameObject>();
// Check a directory for object files
File folder = new File(Data.getDataDirectory() + "/data/obj/");
File [] listOfFiles = folder.listFiles();
FileRead fp;
String line;
String [] words;
for(int i = 0; i < listOfFiles.length; i++)
{
if(listOfFiles[i].isFile())
{
fp = new FileRead((File)listOfFiles[i]);
while(fp.hasNext())
{
line = fp.getLine();
if(line == null)
break;
words = line.split("\\s");
if (words[0].equals("NAME"))
{
GameObject newObj = new GameObject();
this.availableListModel.addElement(newObj);
newObj.setName(words[1]);
break;
}
}
fp.close();
}
}
// Load objects present in the level file
this.addedObjectsList = this.mapPanel.level.getObjectList();
for(GameObject curObj : this.addedObjectsList)
{
this.addedListModel.addElement(curObj);
}
this.availableObjects = new JList<>(this.availableListModel);
this.availableObjects.setCellRenderer(this.renderer);
this.addedObjects = new JList<>(this.addedListModel);
this.addedObjects.setCellRenderer(this.renderer);
this.availableObjects.setLayoutOrientation(JList.VERTICAL);
this.availableObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addedObjects.setLayoutOrientation(JList.VERTICAL);
this.addedObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addListeners();
availablePane = new JScrollPane(availableObjects);
addedPane = new JScrollPane(addedObjects);
this.removeAll();
this.add(availablePane);
this.add(addedPane);
this.add(buttonAdd);
this.add(buttonRemove);
this.add(directionLeft);
this.add(directionRight);
this.repaint();
}
void setSelectedObject(GameObject selObj)
{
addedObjects.setSelectedValue(selObj, true);
}
void setPanels(MapPanel newMapPanel)
{
this.mapPanel = newMapPanel;
}
}
class ToolsetTabPane extends JTabbedPane
{
private MapPanel mapPanel = null;
public void setMapPanel(MapPanel newMapPanel)
{
this.mapPanel = newMapPanel;
this.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
switch(getSelectedIndex())
{
case 0:
mapPanel.setEditMode(EditMode.MODE_TILE_EDIT);
break;
case 1:
mapPanel.setEditMode(EditMode.MODE_OBJECT_EDIT);
break;
case 2:
mapPanel.setEditMode(EditMode.MODE_LEVEL_EDIT);
break;
default:
break;
}
mapPanel.repaint();
}
});
}
}
public class Editor
{
private static void createGui()
{
JFrame frame = new JFrame("FROG Level Editor");
ImageIcon icon = new ImageIcon("./data/icon.png");
frame.setIconImage(icon.getImage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel windowContainer = new JPanel(new BorderLayout());
windowContainer.setLayout(new BoxLayout(windowContainer, BoxLayout.LINE_AXIS));
MapPanel mapPanel = new MapPanel();
ToolsetTabPane toolsetTabPane = new ToolsetTabPane();
JPanel toolPanel = new JPanel();
ObjectPanel objectPanel = new ObjectPanel();
JPanel levelSettingsPanel = new JPanel();
TilesetPanel tilesetPanel = new TilesetPanel();
TileInfoPanel tileInfoPanel = new TileInfoPanel();
ToolbarPanel toolbarPanel = new ToolbarPanel();
objectPanel.setPanels(mapPanel);
tilesetPanel.setTileInfoPanel(tileInfoPanel);
toolbarPanel.setPanels(mapPanel, tilesetPanel);
toolsetTabPane.addTab("Tiles", null, toolPanel, "Tile edit mode");
toolsetTabPane.addTab("Objects", null, objectPanel, "Object edit mode");
toolsetTabPane.addTab("Level", null, levelSettingsPanel, "Level settings");
toolsetTabPane.setMapPanel(mapPanel);
toolPanel.setLayout(new BoxLayout(toolPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollFrame = new JScrollPane(mapPanel);
mapPanel.setAutoscrolls(true);
mapPanel.addMouseListener(mapPanel);
mapPanel.addMouseMotionListener(mapPanel);
tilesetPanel.addMouseListener(tilesetPanel);
tilesetPanel.addMouseMotionListener(tilesetPanel);
mapPanel.setPreferredSize(new Dimension(640,480));
tileInfoPanel.setMinimumSize(new Dimension(256,15));
tileInfoPanel.setMaximumSize(new Dimension(256,15));
toolsetTabPane.setPreferredSize(new Dimension(256,256));
toolsetTabPane.setMinimumSize(new Dimension(256,256));
toolsetTabPane.setMaximumSize(new Dimension(256,1200));
toolPanel.setPreferredSize(new Dimension(256,256));
toolPanel.setMinimumSize(new Dimension(256,256));
toolPanel.setMaximumSize(new Dimension(256,1200));
tilesetPanel.setPreferredSize(new Dimension(256,256));
tilesetPanel.setMinimumSize(new Dimension(256,256));
tilesetPanel.setMaximumSize(new Dimension(256,256));
toolbarPanel.setPreferredSize(new Dimension(256,150));
toolbarPanel.setMinimumSize(new Dimension(256,80));
toolbarPanel.setMaximumSize(new Dimension(256,150));
mapPanel.setPanels(tilesetPanel, tileInfoPanel, objectPanel);
toolPanel.add(tilesetPanel, BorderLayout.NORTH);
toolPanel.add(tileInfoPanel);
toolPanel.add(toolbarPanel, BorderLayout.NORTH);
windowContainer.add(scrollFrame);
windowContainer.add(toolsetTabPane);
//windowContainer.add(toolPanel);
mapPanel.setBorder(BorderFactory.createLineBorder(Color.black));
tilesetPanel.setBorder(BorderFactory.createLineBorder(Color.black));
//tileInfoPanel.setBorder(BorderFactory.createLineBorder(Color.black));
// menu
Menu menuBar = new Menu();
menuBar.setPanels(mapPanel, tilesetPanel, toolbarPanel, objectPanel);
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(windowContainer);
frame.setLocationRelativeTo(null);
// display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createGui();
}
});
}
}
|
Editor.java
|
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.filechooser.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
enum EditMode
{
MODE_NONE,
MODE_TILE_EDIT,
MODE_OBJECT_EDIT,
MODE_LEVEL_EDIT
}
class Data
{
private static String dataDirectory = ".."; // default location
public static String getDataDirectory()
{
return dataDirectory;
}
public static void setDataDirectory(String dataDirectory)
{
Data.dataDirectory = dataDirectory;
}
}
class NewLevelSetup extends JDialog implements ActionListener
{
private GridLayout windowLayout = new GridLayout(3, 1);
private JPanel windowContainer = new JPanel(windowLayout);
private JPanel fieldContainer = new JPanel(new GridLayout(1, 4));
private JPanel buttonContainer = new JPanel(new GridLayout(1, 2));
private JLabel labelSize = new JLabel("New level size:");
private JLabel labelSizeX = new JLabel("x:");
private JLabel labelSizeY = new JLabel("y:");
private JFormattedTextField fieldSizeX;
private JFormattedTextField fieldSizeY;
private JButton buttonCancel = new JButton("Cancel");
private JButton buttonCreate = new JButton("Create");
private Menu menu = null;
private boolean choice;
public NewLevelSetup(String caption, Menu newMenu)
{
this.setTitle(caption);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
this.menu = newMenu;
this.fieldSizeX = new JFormattedTextField(this.menu.getSizeX());
this.fieldSizeY = new JFormattedTextField(this.menu.getSizeY());
this.fieldSizeX.setColumns(3);
this.fieldSizeY.setColumns(3);
this.labelSize.setHorizontalAlignment(JLabel.CENTER);
this.labelSizeX.setHorizontalAlignment(JLabel.CENTER);
this.labelSizeY.setHorizontalAlignment(JLabel.CENTER);
fieldSizeX.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
int value = ((Number)fieldSizeX.getValue()).intValue();
if (value < 20)
{
value = 20;
fieldSizeX.setValue(value);
}
else if (value > 500)
{
value = 500;
fieldSizeX.setValue(value);
}
}
});
fieldSizeY.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent e)
{
int value = ((Number)fieldSizeY.getValue()).intValue();
if (value < 20)
{
value = 20;
fieldSizeY.setValue(value);
}
else if (value > 500)
{
value = 500;
fieldSizeY.setValue(value);
}
}
});
buttonCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
choice = false;
setVisible(false);
dispose();
}
});
buttonCreate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
menu.setSizeX(((Number)fieldSizeX.getValue()).intValue());
menu.setSizeY(((Number)fieldSizeY.getValue()).intValue());
choice = true;
setVisible(false);
dispose();
}
});
fieldContainer.add(labelSizeX);
fieldContainer.add(fieldSizeX);
fieldContainer.add(labelSizeY);
fieldContainer.add(fieldSizeY);
buttonContainer.add(buttonCancel);
buttonContainer.add(buttonCreate);
windowLayout.setVgap(5);
windowContainer.add(labelSize);
windowContainer.add(fieldContainer);
windowContainer.add(buttonContainer);
this.add(windowContainer);
// this.pack();
// this.setVisible(true);
}
public boolean getChoice()
{
return this.choice;
}
public void actionPerformed(ActionEvent e)
{
this.choice = false;
setVisible(false);
dispose();
}
}
class Menu extends JMenuBar
{
private JMenu fileMenu = new JMenu("File");
private JMenuItem fileNew = new JMenuItem("New level");
private JMenuItem fileOpen = new JMenuItem("Open level");
private JMenuItem fileSave = new JMenuItem("Save level");
private JMenuItem fileSaveAs = new JMenuItem("Save level as...");
private JMenuItem fileQuit = new JMenuItem("Quit editor");
private JMenu runMenu = new JMenu("Run");
private JMenuItem runSetExec = new JMenuItem("Set executable location");
private JMenuItem runRunLevel = new JMenuItem("Run level");
private JMenu helpMenu = new JMenu("Help");
private JMenuItem helpAbout = new JMenuItem("About");
private JFileChooser fileChooser = new JFileChooser(Data.getDataDirectory());
private MapPanel mapPanel = null;
private TilesetPanel tilesetPanel = null;
private ToolbarPanel toolbarPanel = null;
private ObjectPanel objectPanel = null;
private int newSizeX = 20;
private int newSizeY = 20;
public Menu()
{
this.add(fileMenu);
fileMenu.add(fileNew);
fileMenu.add(fileOpen);
fileMenu.add(fileSave);
fileMenu.add(fileSaveAs);
fileMenu.add(fileQuit);
this.add(runMenu);
runMenu.add(runSetExec);
runMenu.add(runRunLevel);
this.add(helpMenu);
helpMenu.add(helpAbout);
fileNew.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// create new level
if(showNewLevelSetup())
{
mapPanel.level = new Level(newSizeX, newSizeY);
tilesetPanel.setImage(0, mapPanel.level.getLayer(1).getImg());
tilesetPanel.showLayer[0] = true;
tilesetPanel.defaultSettings();
for(int i = 0; i < mapPanel.level.getNumOfLayers(); i++)
{
BufferedImage defMapImg = new BufferedImage(mapPanel.level.getLayer(i).getWidth() * 16, mapPanel.level.getLayer(i).getHeight() * 16, BufferedImage.TYPE_INT_ARGB);
mapPanel.setImage(i, defMapImg);
mapPanel.showLayer[i] = true;
}
if(mapPanel.drawAreaLayers.size() >= 1)
mapPanel.paintOnLayer = 1; // We assume that layer 1 is the "walkable" layer
int levelWidth;
int levelHeight;
int tile = 0;
for(int n = 0; n < mapPanel.drawAreaLayers.size(); n++)
{
levelWidth = mapPanel.level.getLayer(n).getWidth() * 16;
levelHeight = mapPanel.level.getLayer(n).getHeight() * 16;
for(int i = 0, x = 0; i < levelWidth; i+=16, x++)
{
for(int j = 0, y = 0; j < levelHeight; j+=16, y++)
{
tile = mapPanel.level.getLayer(n).getTile(x, y);
mapPanel.paintTile(n, tile, i, j, false);
}
}
}
toolbarPanel.defaultSettings();
if(mapPanel.drawAreaLayers.size() > 0)
{
mapPanel.setPreferredSize(new Dimension(mapPanel.drawAreaLayers.get(0).getWidth(),mapPanel.drawAreaLayers.get(0).getHeight()));
mapPanel.revalidate();
}
objectPanel.loadObjects();
}
}
});
fileOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// open existing level
int choice = fileChooser.showOpenDialog(fileChooser);
//fileChooser.setFileFilter(new FileFilter(""));
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level = new Level(file);
// Set tileset panel image
tilesetPanel.setImage(0, mapPanel.level.getLayer(1).getImg());
tilesetPanel.showLayer[0] = true;
tilesetPanel.defaultSettings();
// Set map panel images
for(int n = 0; n < mapPanel.level.getNumOfLayers(); n++)
{
BufferedImage defMapImg = new BufferedImage(mapPanel.level.getLayer(n).getWidth() * 16, mapPanel.level.getLayer(n).getHeight() * 16, BufferedImage.TYPE_INT_ARGB);
mapPanel.setImage(n, defMapImg);
mapPanel.showLayer[n] = true;
}
if(mapPanel.drawAreaLayers.size() >= 1)
mapPanel.paintOnLayer = 1; // We assume that layer 1 is the "walkable" layer
int levelWidth;
int levelHeight;
int tile = 0;
for(int n = 0; n < mapPanel.drawAreaLayers.size(); n++)
{
levelWidth = mapPanel.level.getLayer(n).getWidth() * 16;
levelHeight = mapPanel.level.getLayer(n).getHeight() * 16;
for(int i = 0, x = 0; i < levelWidth; i+=16, x++)
{
for(int j = 0, y = 0; j < levelHeight; j+=16, y++)
{
tile = mapPanel.level.getLayer(n).getTile(x, y);
mapPanel.paintTile(n, tile, i, j, false);
}
}
}
toolbarPanel.defaultSettings();
if(mapPanel.drawAreaLayers.size() > 0)
{
mapPanel.setPreferredSize(new Dimension(mapPanel.drawAreaLayers.get(0).getWidth(),mapPanel.drawAreaLayers.get(0).getHeight()));
mapPanel.revalidate();
}
objectPanel.loadObjects();
}
}
});
fileSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// save current level
if(mapPanel.level != null)
{
if(mapPanel.level.getFilePath() != null)
{
mapPanel.level.write(mapPanel.level.getFilePath());
}
else
{
// ask for the file name
int choice = fileChooser.showSaveDialog(fileChooser);
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level.setFilePath(file);
mapPanel.level.write(mapPanel.level.getFilePath());
}
}
}
}
});
fileSaveAs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(mapPanel.level != null)
{
// save current level under a different name
int choice = fileChooser.showSaveDialog(fileChooser);
if(choice == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
mapPanel.level.setFilePath(file);
mapPanel.level.write(mapPanel.level.getFilePath());
}
}
}
});
fileQuit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// quit program
System.out.printf("Pressed Quit\n"); // TODO
}
});
runRunLevel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(mapPanel.level != null)
{
boolean playerObjPresent = false;
ListIterator<GameObject> objsli = mapPanel.level.getObjectList().listIterator();
while (objsli.hasNext())
{
if(objsli.next().getName().equals("player"))
playerObjPresent = true;
}
if(!playerObjPresent) // Don't launch the level if player object is missing.
{
JOptionPane.showMessageDialog(runRunLevel, "Add a player object first.");
return;
}
File path = new File(Data.getDataDirectory() + "/frog.jar");
if(!path.exists() || path.isDirectory())
{
JOptionPane.showMessageDialog(runRunLevel, "ERROR: Missing game executable at location:\n" + path.getAbsolutePath(), "Game launch issue", JOptionPane.ERROR_MESSAGE);
}
// save current level to a temporary file
mapPanel.level.write(new File(Data.getDataDirectory() + "/lvl.tmp"));
// run level
ProcessBuilder builder = new ProcessBuilder("java", "-jar", path.getAbsolutePath(), "-l", "./lvl.tmp", "-nojoy");
builder.environment().put("LD_LIBRARY_PATH","lib");
builder.directory(new File(Data.getDataDirectory()).getAbsoluteFile());
builder.redirectErrorStream(true);
File log = new File("runlog.tmp");
builder.redirectOutput(ProcessBuilder.Redirect.to(log));
Process proc;
try
{
System.out.printf("Launching game... (log: %s)\n", log.getAbsolutePath());
proc = builder.start();
assert builder.redirectInput() == ProcessBuilder.Redirect.PIPE;
assert builder.redirectOutput().file() == log;
assert proc.getInputStream().read() == -1;
}
catch (IOException ioe)
{
System.out.printf("Failed to launch the game:\n%s\n", ioe.getMessage());
JOptionPane.showMessageDialog(runRunLevel, "ERROR: " + ioe.getMessage(), "Game launch issue", JOptionPane.ERROR_MESSAGE);
}
}
}
});
helpAbout.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(helpAbout,
"\nFROG Level Editor version 0.0.1\n\n" +
"Copyright © 2014 Artur Rojek\n" +
"Licensed under LGPL v2 +", "About", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("./data/about.png"));
}
});
}
public void setPanels(MapPanel newMapPanel, TilesetPanel newTilesetPanel, ToolbarPanel newToolbarPanel, ObjectPanel newObjectPanel)
{
this.mapPanel = newMapPanel;
this.tilesetPanel = newTilesetPanel;
this.toolbarPanel = newToolbarPanel;
this.objectPanel = newObjectPanel;
}
public void setSizeX(int size)
{
this.newSizeX = size;
}
public void setSizeY(int size)
{
this.newSizeY = size;
}
public int getSizeX()
{
return this.newSizeX;
}
public int getSizeY()
{
return this.newSizeY;
}
public boolean showNewLevelSetup()
{
NewLevelSetup dialog = new NewLevelSetup("Create level", this);
//dialog.setPreferredSize(new Dimension(320, 240));
dialog.setLocationRelativeTo(this);
dialog.pack();
dialog.setVisible(true);
return dialog.getChoice();
}
}
class MapPanel extends DrawPanel implements MouseInputListener
{
public Level level = null;
private TilesetPanel tileset = null;
private TileInfoPanel tileInfoPanel = null;
private ObjectPanel objectPanel = null;
private EditMode editMode = EditMode.MODE_TILE_EDIT;
private boolean canPaint = false;
private int paintX = 0;
private int paintY = 0;
private int lastPaintOnLayer = 1;
private int lastTile = 0;
private GameObject selectedObject = null;
private boolean draggingObject = false;
protected boolean showGrid = true;
public EditMode getEditMode()
{
return this.editMode;
}
public void setEditMode(EditMode newEditMode)
{
this.editMode = newEditMode;
}
public void paintTile(int layer, int num, int x, int y, boolean repaint)
{
if (this.tileset == null)
{
System.out.printf("Tileset is empty!\n");
return;
}
if (this.level == null)
{
System.out.printf("No level loaded!\n");
return;
}
if (layer >= this.drawAreaLayers.size())
{
System.out.printf("No such layer: %d!\n", layer);
return;
}
int tileX = num%16;
int tileY = num/16;
super.blit(layer, this.tileset.getImage(0), x, y, x + 16, y + 16, tileX * 16, tileY * 16, tileX * 16 + 16, tileY * 16 + 16);
if(repaint)
{
super.repaint();
}
}
public void paintTile(int x, int y)
{
if (this.tileset == null)
{
System.out.printf("Tileset is empty!\n");
return;
}
int tileNum = tileset.getSelY() * 16 + tileset.getSelX();
this.level.getLayer(super.paintOnLayer).setTile(x/16, y/16, tileNum);
super.blit(super.paintOnLayer, this.tileset.getImage(0), x, y, x + 16, y + 16, this.tileset.getSelX() * 16, this.tileset.getSelY() * 16, this.tileset.getSelX() * 16 + 16, this.tileset.getSelY() * 16 + 16);
super.repaint();
}
public void setPanels(TilesetPanel newTileset, TileInfoPanel newTileInfoPanel, ObjectPanel newObjectPanel)
{
this.tileset = newTileset;
this.tileInfoPanel = newTileInfoPanel;
this.objectPanel = newObjectPanel;
}
private boolean isInMapArea(int x, int y)
{
if(super.drawAreaLayers.size() < 1)
return false;
if(super.drawAreaLayers.get(0) == null)
return false;
if (x < 0)
return false;
else if (x >= super.drawAreaLayers.get(0).getWidth())
return false;
else if (y < 0)
return false;
else if (y >= super.drawAreaLayers.get(0).getHeight())
return false;
else
{
return true;
}
}
// mouse listener
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
this.canPaint = false;
break;
default:
break;
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
if(this.draggingObject)
this.draggingObject = false;
}
break;
default:
break;
}
}
}
public void mousePressed(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
if(this.level != null && this.level.getNumOfLayers() > 0 && this.tileset != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
this.canPaint = true;
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
int curTile = this.tileset.getSelY() * 16 + this.tileset.getSelX();
if(this.paintX != curX || this.paintY != curY || this.lastPaintOnLayer != super.paintOnLayer || this.lastTile != curTile)
{
if((this.canPaint) && (this.isInMapArea(e.getX(), e.getY())))
{
this.paintX = e.getX()/16*16;
this.paintY = e.getY()/16*16;
this.lastPaintOnLayer = super.paintOnLayer;
this.lastTile = curTile;
this.paintTile(this.paintX, this.paintY);
}
}
}
break;
case InputEvent.BUTTON3_MASK:
{
int tile = this.level.getLayer(super.paintOnLayer).getTile(e.getX()/16, e.getY()/16);
int x = tile % 16;
int y = tile / 16;
this.tileset.setSelX(x);
this.tileset.setSelY(y);
this.tileset.repaint();
if(this.tileInfoPanel != null)
this.tileInfoPanel.updateInfo(x, y);
}
break;
default:
break;
}
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null && this.objectPanel != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
int objX;
int objY;
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
if(!this.draggingObject)
{
for(GameObject curObj : this.level.getObjectList())
{
if(curObj.getX()/16*16 == curX && curObj.getY()/16*16 == curY)
{
this.selectedObject = curObj;
this.draggingObject = true;
this.objectPanel.setSelectedObject(curObj);
break;
}
}
}
}
break;
case InputEvent.BUTTON3_MASK:
break;
default:
break;
}
}
}
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
if(this.editMode == EditMode.MODE_TILE_EDIT)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
int curTile = this.tileset.getSelY() * 16 + this.tileset.getSelX();
if(this.paintX != curX || this.paintY != curY || this.lastPaintOnLayer != super.paintOnLayer || this.lastTile != curTile)
{
if((this.canPaint) && (this.isInMapArea(e.getX(), e.getY())))
{
this.paintX = curX;
this.paintY = curY;
this.lastPaintOnLayer = super.paintOnLayer;
this.lastTile = curTile;
this.paintTile(this.paintX, this.paintY);
}
}
}
break;
default:
break;
}
}
else if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null && this.objectPanel != null)
{
switch(e.getModifiers())
{
case InputEvent.BUTTON1_MASK:
{
if(this.selectedObject != null && this.draggingObject)
{
int curX = e.getX()/16*16;
int curY = e.getY()/16*16;
this.selectedObject.setX(curX);
this.selectedObject.setY(curY);
this.repaint();
}
}
break;
case InputEvent.BUTTON3_MASK:
break;
default:
break;
}
}
}
}
protected void draw(Graphics g)
{
// draw the level grid
if(this.showGrid)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(new Color(0, 0 ,0, 100));
if(this.level != null && this.level.getNumOfLayers() > 0)
{
for(int i = 0; i <= this.level.getLayer(0).getWidth(); i++)
{
// vertical
g2d.drawLine(i * 16, 0, i * 16, this.level.getLayer(0).getHeight() * 16);
}
for(int j = 0; j <= this.level.getLayer(0).getHeight(); j++)
{
// horizontal
g2d.drawLine(0, j * 16, this.level.getLayer(0).getWidth() * 16, j * 16);
}
}
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.draw(g);
// temp
if(this.editMode == EditMode.MODE_OBJECT_EDIT)
{
if(this.level != null)
{
for(GameObject curObj : this.level.getObjectList())
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
g2d.drawLine(curObj.getX(), curObj.getY(), curObj.getX() + 16, curObj.getY() + 16);
}
}
}
}
}
class TilesetPanel extends DrawPanel implements MouseInputListener
{
private TileInfoPanel tileInfoPanel = null;
private int selX = 0;
private int selY = 0;
public int getSelX()
{
return this.selX;
}
public int getSelY()
{
return this.selY;
}
public void setSelX(int value)
{
this.selX = value;
}
public void setSelY(int value)
{
this.selY = value;
}
// mouse listener
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
if(super.drawAreaLayers.size() > 0 && super.drawAreaLayers.get(0) != null)
{
if(e.getX() > 0 && e.getX() < super.drawAreaLayers.get(0).getWidth() && e.getY() > 0 && e.getY() < super.drawAreaLayers.get(0).getHeight())
{
this.selX = e.getX()/16;
this.selY = e.getY()/16;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
super.repaint();
}
}
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
if(super.drawAreaLayers.size() > 0 && super.drawAreaLayers.get(0) != null)
{
if(e.getX() > 0 && e.getX() < super.drawAreaLayers.get(0).getWidth() && e.getY() > 0 && e.getY() < super.drawAreaLayers.get(0).getHeight())
{
this.selX = e.getX()/16;
this.selY = e.getY()/16;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
super.repaint();
}
}
}
protected void draw(Graphics g)
{
if(super.drawAreaLayers.size() > 0)
{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.yellow);
// top
g2d.drawLine(this.selX * 16, this.selY * 16, this.selX * 16 + 16, this.selY * 16);
// bottom
g2d.drawLine(this.selX * 16, this.selY * 16 + 16, this.selX * 16 + 16, this.selY * 16 + 16);
// left
g2d.drawLine(this.selX * 16, this.selY * 16, this.selX * 16, this.selY * 16 + 16);
// right
g2d.drawLine(this.selX * 16 + 16, this.selY * 16, this.selX * 16 + 16, this.selY * 16 + 16);
}
}
public void setTileInfoPanel(TileInfoPanel newInfoPanel)
{
this.tileInfoPanel = newInfoPanel;
}
public void defaultSettings()
{
this.selX = 0;
this.selY = 0;
this.tileInfoPanel.updateInfo(this.selX, this.selY);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.draw(g);
}
}
class DrawPanel extends JPanel
{
//protected BufferedImage drawArea = null;
protected LinkedList<BufferedImage> drawAreaLayers = new LinkedList<BufferedImage>();
protected boolean [] showLayer = new boolean[10]; // Let's hardcode the max number of layers to display for now.
protected int paintOnLayer = 0;
public LinkedList<BufferedImage> getLayers()
{
return this.drawAreaLayers;
}
public BufferedImage getImage(int layer)
{
return this.drawAreaLayers.get(layer);
}
public void setImage(int layer, BufferedImage src)
{
if(layer >= this.drawAreaLayers.size())
{
this.drawAreaLayers.push(src);
}
else
{
this.drawAreaLayers.set(layer, src);
}
super.repaint();
}
public void loadImage(int layer, String fileName)
{
if(fileName.equals(""))
return;
try
{
this.drawAreaLayers.set(layer, ImageIO.read(this.getClass().getResource("./data/" + fileName)));
}
catch (IOException e)
{
System.out.printf("ERROR: Failed to load image!");
}
}
public void blit(int layer, BufferedImage src, int destx1, int desty1, int destx2, int desty2, int srcx1, int srcy1, int srcx2, int srcy2)
{
if(this.drawAreaLayers.get(layer) != null && src != null)
{
BufferedImage dest = this.drawAreaLayers.get(layer);
dest.createGraphics().drawImage(src, destx1, desty1, destx2, desty2, srcx1, srcy1, srcx2, srcy2, null);
WritableRaster raster = dest.getRaster();
for(int j = desty1; j < desty2; j++)
{
for(int i = destx1; i < destx2; i++)
{
int [] pixels = raster.getPixel(i, j, (int[]) null);
if(pixels[0] == 255 && pixels[1] == 0 && pixels[2] == 255) // magenta
{
pixels[3] = 0;
raster.setPixel(i, j, pixels);
}
}
}
}
}
protected void draw(int layer, Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
if(layer < this.drawAreaLayers.size() && this.drawAreaLayers.get(layer) != null)
{
g2d.drawImage(drawAreaLayers.get(layer), 0, 0, null);
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < this.drawAreaLayers.size(); i++)
{
if(this.showLayer[this.drawAreaLayers.size() - 1 - i])
{
this.draw(this.drawAreaLayers.size() - 1 - i, g);
}
}
}
}
class TileInfoPanel extends JPanel
{
private JLabel infoLabel = new JLabel();
private String infoText;
TileInfoPanel()
{
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.infoLabel.setHorizontalAlignment(JLabel.LEFT);
this.defaultInfo();
this.add(infoLabel);
this.setVisible(true);
}
public void defaultInfo()
{
infoText = " ";
this.infoLabel.setText(this.infoText);
}
public void updateInfo(int tileX, int tileY)
{
int tile = tileY * 16 + tileX;
this.infoText = " Tile #" + tile + " (" + tileX + "," + tileY + ")";
this.infoLabel.setText(this.infoText);
}
}
class ToolbarPanel extends JPanel
{
private MapPanel mapPanel = null;
private TilesetPanel tilesetPanel = null;
private ButtonGroup radioLayers = new ButtonGroup();
private JRadioButton drawOnBackground = new JRadioButton("BGD");
private JRadioButton drawOnMiddleground = new JRadioButton("MGD");
private JRadioButton drawOnForeground = new JRadioButton("FGD");
private JCheckBox showBackground = new JCheckBox("BGD");
private JCheckBox showMiddleground = new JCheckBox("MGD");
private JCheckBox showForeground = new JCheckBox("FGD");
private JCheckBox showGrid = new JCheckBox("Tile grid");
private JLabel paintLabel = new JLabel("Draw on:");
private JLabel showLabel = new JLabel("Show:");
public ToolbarPanel()
{
this.setLayout(new GridLayout(6, 2));
this.radioLayers.add(drawOnBackground);
this.radioLayers.add(drawOnMiddleground);
this.radioLayers.add(drawOnForeground);
this.defaultSettings();
this.add(paintLabel);
this.add(showLabel);
this.add(drawOnBackground);
this.add(showBackground);
this.add(drawOnMiddleground);
this.add(showMiddleground);
this.add(drawOnForeground);
this.add(showForeground);
this.add(new JLabel("")); // add an empty cell
this.add(showGrid);
drawOnBackground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 2;
}
});
drawOnMiddleground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 1;
}
});
drawOnForeground.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mapPanel.paintOnLayer = 0;
}
});
showBackground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnBackground.setEnabled(true);
mapPanel.showLayer[2] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnBackground.setEnabled(false);
if(drawOnBackground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[2] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showMiddleground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnMiddleground.setEnabled(true);
mapPanel.showLayer[1] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnMiddleground.setEnabled(false);
if(drawOnMiddleground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[1] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showForeground.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
drawOnForeground.setEnabled(true);
mapPanel.showLayer[0] = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
drawOnForeground.setEnabled(false);
if(drawOnForeground.isSelected())
radioLayers.clearSelection();
mapPanel.showLayer[0] = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
showGrid.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
switch(e.getStateChange())
{
case ItemEvent.SELECTED:
mapPanel.showGrid = true;
mapPanel.repaint();
break;
case ItemEvent.DESELECTED:
mapPanel.showGrid = false;
mapPanel.repaint();
break;
default:
break;
}
}
});
}
public void defaultSettings()
{
this.drawOnMiddleground.setSelected(true);
this.showBackground.setSelected(true);
this.showMiddleground.setSelected(true);
this.showForeground.setSelected(true);
this.showGrid.setSelected(true);
}
public void setPanels(MapPanel newMapPanel, TilesetPanel newTilesetPanel)
{
this.mapPanel = newMapPanel;
this.tilesetPanel = newTilesetPanel;
}
}
class ObjectPanel extends JPanel
{
private MapPanel mapPanel = null;
private ListCellRenderer<Object> renderer;
//private LinkedList<GameObject> availableObjectsList;
private LinkedList<GameObject> addedObjectsList;
private DefaultListModel<GameObject> availableListModel;
private DefaultListModel<GameObject> addedListModel;
private JList <GameObject> availableObjects;
private JList <GameObject> addedObjects;
private JScrollPane availablePane;
private JScrollPane addedPane;
private JButton buttonAdd = new JButton("Add");
private JButton buttonRemove = new JButton("Remove");
class ObjectCellRenderer extends JLabel implements ListCellRenderer<Object>
{
public ObjectCellRenderer()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
if(value instanceof GameObject)
setText(((GameObject)value).getName() + " ["+((GameObject)value).getX()+","+((GameObject)value).getY()+"]");
else
setText(value.toString());
Color background;
Color foreground;
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null && !dropLocation.isInsert() && dropLocation.getIndex() == index)
{
background = Color.BLUE;
foreground = Color.WHITE;
// check if this cell is selected
}
else if (isSelected)
{
background = Color.BLUE;
foreground = Color.WHITE;
// unselected, and not the DnD drop location
}
else
{
background = Color.WHITE;
foreground = Color.BLACK;
}
setBackground(background);
setForeground(foreground);
return this;
}
}
public ObjectPanel()
{
renderer = new ObjectCellRenderer();
buttonAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(availableListModel != null)
{
GameObject newObj = new GameObject();
int selectedIndex = availableObjects.getSelectedIndex();
if(selectedIndex != -1)
{
newObj.setName(availableListModel.get(selectedIndex).getName());
addedObjectsList.push(newObj);
addedListModel.addElement(newObj);
addedObjects.setSelectedValue(newObj, true);
}
mapPanel.repaint();
}
}
});
buttonRemove.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(addedListModel != null)
{
int selectedIndex = addedObjects.getSelectedIndex();
if(selectedIndex != -1)
{
GameObject objToRem = addedListModel.get(selectedIndex);
ListIterator<GameObject> objsli = addedObjectsList.listIterator();
while (objsli.hasNext())
{
if(objsli.next() == objToRem)
{
objsli.remove();
addedListModel.remove(selectedIndex);
addedObjects.setSelectedIndex(selectedIndex == 0 ? 0 : selectedIndex - 1);
break;
}
}
mapPanel.repaint();
}
}
}
});
}
// feature not needed?
void addListeners()
{
// if(availableObjects != null)
// {
// availableObjects.addListSelectionListener(new ListSelectionListener()
// {
// public void valueChanged(ListSelectionEvent e)
// {
// if(e.getValueIsAdjusting() == false)
// {
// if(availableObjects.getSelectedIndex() == -1)
// {
// //No selection
// }
// else
// {
// System.out.printf("Selected: %s [%d,%d]\n", availableListModel.get(availableObjects.getSelectedIndex()).getName(), availableListModel.get(availableObjects.getSelectedIndex()).getX(), availableListModel.get(availableObjects.getSelectedIndex()).getY());
// }
// }
// }
// });
// }
// if(addedObjects != null)
// {
// addedObjects.addListSelectionListener(new ListSelectionListener()
// {
// public void valueChanged(ListSelectionEvent e)
// {
// if(e.getValueIsAdjusting() == false)
// {
// if(addedObjects.getSelectedIndex() == -1)
// {
// //No selection
// }
// else
// {
// System.out.printf("Selected: %s [%d,%d]\n", addedListModel.get(addedObjects.getSelectedIndex()).getName(), addedListModel.get(addedObjects.getSelectedIndex()).getX(), addedListModel.get(addedObjects.getSelectedIndex()).getY());
// }
// }
// }
// });
// }
}
void loadObjects()
{
this.availableListModel = new DefaultListModel<GameObject>();
this.addedListModel = new DefaultListModel<GameObject>();
// Check a directory for object files
File folder = new File(Data.getDataDirectory() + "/data/obj/");
File [] listOfFiles = folder.listFiles();
FileRead fp;
String line;
String [] words;
for(int i = 0; i < listOfFiles.length; i++)
{
if(listOfFiles[i].isFile())
{
fp = new FileRead((File)listOfFiles[i]);
while(fp.hasNext())
{
line = fp.getLine();
if(line == null)
break;
words = line.split("\\s");
if (words[0].equals("NAME"))
{
GameObject newObj = new GameObject();
this.availableListModel.addElement(newObj);
newObj.setName(words[1]);
break;
}
}
fp.close();
}
}
// Load objects present in the level file
this.addedObjectsList = this.mapPanel.level.getObjectList();
for(GameObject curObj : this.addedObjectsList)
{
this.addedListModel.addElement(curObj);
}
this.availableObjects = new JList<>(this.availableListModel);
this.availableObjects.setCellRenderer(this.renderer);
this.addedObjects = new JList<>(this.addedListModel);
this.addedObjects.setCellRenderer(this.renderer);
this.availableObjects.setLayoutOrientation(JList.VERTICAL);
this.availableObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addedObjects.setLayoutOrientation(JList.VERTICAL);
this.addedObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addListeners();
availablePane = new JScrollPane(availableObjects);
addedPane = new JScrollPane(addedObjects);
this.removeAll();
this.add(availablePane);
this.add(addedPane);
this.add(buttonAdd);
this.add(buttonRemove);
this.repaint();
}
void setSelectedObject(GameObject selObj)
{
addedObjects.setSelectedValue(selObj, true);
}
void setPanels(MapPanel newMapPanel)
{
this.mapPanel = newMapPanel;
}
}
class ToolsetTabPane extends JTabbedPane
{
private MapPanel mapPanel = null;
public void setMapPanel(MapPanel newMapPanel)
{
this.mapPanel = newMapPanel;
this.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
switch(getSelectedIndex())
{
case 0:
mapPanel.setEditMode(EditMode.MODE_TILE_EDIT);
break;
case 1:
mapPanel.setEditMode(EditMode.MODE_OBJECT_EDIT);
break;
case 2:
mapPanel.setEditMode(EditMode.MODE_LEVEL_EDIT);
break;
default:
break;
}
mapPanel.repaint();
}
});
}
}
public class Editor
{
private static void createGui()
{
JFrame frame = new JFrame("FROG Level Editor");
ImageIcon icon = new ImageIcon("./data/icon.png");
frame.setIconImage(icon.getImage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel windowContainer = new JPanel(new BorderLayout());
windowContainer.setLayout(new BoxLayout(windowContainer, BoxLayout.LINE_AXIS));
MapPanel mapPanel = new MapPanel();
ToolsetTabPane toolsetTabPane = new ToolsetTabPane();
JPanel toolPanel = new JPanel();
ObjectPanel objectPanel = new ObjectPanel();
JPanel levelSettingsPanel = new JPanel();
TilesetPanel tilesetPanel = new TilesetPanel();
TileInfoPanel tileInfoPanel = new TileInfoPanel();
ToolbarPanel toolbarPanel = new ToolbarPanel();
objectPanel.setPanels(mapPanel);
tilesetPanel.setTileInfoPanel(tileInfoPanel);
toolbarPanel.setPanels(mapPanel, tilesetPanel);
toolsetTabPane.addTab("Tiles", null, toolPanel, "Tile edit mode");
toolsetTabPane.addTab("Objects", null, objectPanel, "Object edit mode");
toolsetTabPane.addTab("Level", null, levelSettingsPanel, "Level settings");
toolsetTabPane.setMapPanel(mapPanel);
toolPanel.setLayout(new BoxLayout(toolPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollFrame = new JScrollPane(mapPanel);
mapPanel.setAutoscrolls(true);
mapPanel.addMouseListener(mapPanel);
mapPanel.addMouseMotionListener(mapPanel);
tilesetPanel.addMouseListener(tilesetPanel);
tilesetPanel.addMouseMotionListener(tilesetPanel);
mapPanel.setPreferredSize(new Dimension(640,480));
tileInfoPanel.setMinimumSize(new Dimension(256,15));
tileInfoPanel.setMaximumSize(new Dimension(256,15));
toolsetTabPane.setPreferredSize(new Dimension(256,256));
toolsetTabPane.setMinimumSize(new Dimension(256,256));
toolsetTabPane.setMaximumSize(new Dimension(256,1200));
toolPanel.setPreferredSize(new Dimension(256,256));
toolPanel.setMinimumSize(new Dimension(256,256));
toolPanel.setMaximumSize(new Dimension(256,1200));
tilesetPanel.setPreferredSize(new Dimension(256,256));
tilesetPanel.setMinimumSize(new Dimension(256,256));
tilesetPanel.setMaximumSize(new Dimension(256,256));
toolbarPanel.setPreferredSize(new Dimension(256,150));
toolbarPanel.setMinimumSize(new Dimension(256,80));
toolbarPanel.setMaximumSize(new Dimension(256,150));
mapPanel.setPanels(tilesetPanel, tileInfoPanel, objectPanel);
toolPanel.add(tilesetPanel, BorderLayout.NORTH);
toolPanel.add(tileInfoPanel);
toolPanel.add(toolbarPanel, BorderLayout.NORTH);
windowContainer.add(scrollFrame);
windowContainer.add(toolsetTabPane);
//windowContainer.add(toolPanel);
mapPanel.setBorder(BorderFactory.createLineBorder(Color.black));
tilesetPanel.setBorder(BorderFactory.createLineBorder(Color.black));
//tileInfoPanel.setBorder(BorderFactory.createLineBorder(Color.black));
// menu
Menu menuBar = new Menu();
menuBar.setPanels(mapPanel, tilesetPanel, toolbarPanel, objectPanel);
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
frame.getContentPane().add(windowContainer);
frame.setLocationRelativeTo(null);
// display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createGui();
}
});
}
}
|
Implemented object direction selection
|
Editor.java
|
Implemented object direction selection
|
|
Java
|
lgpl-2.1
|
a3093f27696debc3ea9fb15c80a5748c1f0f3e51
| 0
|
lcahlander/exist,dizzzz/exist,ljo/exist,ambs/exist,kohsah/exist,lcahlander/exist,patczar/exist,RemiKoutcherawy/exist,wshager/exist,windauer/exist,MjAbuz/exist,olvidalo/exist,jessealama/exist,opax/exist,joewiz/exist,olvidalo/exist,shabanovd/exist,RemiKoutcherawy/exist,hungerburg/exist,MjAbuz/exist,adamretter/exist,joewiz/exist,jessealama/exist,eXist-db/exist,eXist-db/exist,opax/exist,ambs/exist,dizzzz/exist,opax/exist,RemiKoutcherawy/exist,jensopetersen/exist,jessealama/exist,joewiz/exist,RemiKoutcherawy/exist,zwobit/exist,patczar/exist,wolfgangmm/exist,joewiz/exist,shabanovd/exist,ambs/exist,patczar/exist,MjAbuz/exist,ambs/exist,ljo/exist,RemiKoutcherawy/exist,jessealama/exist,zwobit/exist,jessealama/exist,patczar/exist,ambs/exist,joewiz/exist,hungerburg/exist,RemiKoutcherawy/exist,windauer/exist,MjAbuz/exist,dizzzz/exist,adamretter/exist,joewiz/exist,eXist-db/exist,lcahlander/exist,shabanovd/exist,wolfgangmm/exist,shabanovd/exist,olvidalo/exist,jensopetersen/exist,zwobit/exist,patczar/exist,shabanovd/exist,dizzzz/exist,adamretter/exist,ljo/exist,dizzzz/exist,jensopetersen/exist,wolfgangmm/exist,zwobit/exist,patczar/exist,ljo/exist,eXist-db/exist,shabanovd/exist,dizzzz/exist,adamretter/exist,windauer/exist,adamretter/exist,wshager/exist,windauer/exist,zwobit/exist,wshager/exist,adamretter/exist,lcahlander/exist,windauer/exist,hungerburg/exist,windauer/exist,lcahlander/exist,ljo/exist,wolfgangmm/exist,wshager/exist,eXist-db/exist,kohsah/exist,wolfgangmm/exist,kohsah/exist,jensopetersen/exist,MjAbuz/exist,eXist-db/exist,lcahlander/exist,kohsah/exist,kohsah/exist,wshager/exist,hungerburg/exist,hungerburg/exist,ambs/exist,wolfgangmm/exist,jessealama/exist,olvidalo/exist,kohsah/exist,olvidalo/exist,opax/exist,jensopetersen/exist,MjAbuz/exist,opax/exist,zwobit/exist,wshager/exist,jensopetersen/exist,ljo/exist
|
/*
* eXist Open Source Native XML Database Copyright (C) 2001-06 Wolfgang M. Meier
* wolfgang@exist-db.org http://exist.sourceforge.net
*
* This program 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 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import org.apache.log4j.Logger;
import org.exist.storage.BrokerPool;
import org.exist.storage.BufferStats;
import org.exist.storage.CacheManager;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.NativeBroker;
import org.exist.storage.StorageAddress;
import org.exist.storage.btree.BTree;
import org.exist.storage.btree.BTreeCallback;
import org.exist.storage.btree.BTreeException;
import org.exist.storage.btree.DBException;
import org.exist.storage.btree.IndexQuery;
import org.exist.storage.btree.Value;
import org.exist.storage.cache.Cache;
import org.exist.storage.cache.Cacheable;
import org.exist.storage.cache.LRUCache;
import org.exist.storage.io.VariableByteArrayInput;
import org.exist.storage.io.VariableByteInput;
import org.exist.storage.io.VariableByteOutputStream;
import org.exist.storage.journal.LogEntryTypes;
import org.exist.storage.journal.Loggable;
import org.exist.storage.journal.Lsn;
import org.exist.storage.lock.Lock;
import org.exist.storage.lock.ReentrantReadWriteLock;
import org.exist.storage.txn.TransactionException;
import org.exist.storage.txn.Txn;
import org.exist.util.ByteArray;
import org.exist.util.ByteConversion;
import org.exist.util.FixedByteArray;
import org.exist.util.IndexCallback;
import org.exist.util.LockException;
import org.exist.util.ReadOnlyException;
import org.exist.util.sanity.SanityCheck;
import org.exist.xquery.Constants;
import org.exist.xquery.TerminatedException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Data store for variable size values.
*
* This class maps keys to values of variable size. Keys are stored in the
* b+-tree. B+-tree values are pointers to the logical storage address of the
* value in the data section. The pointer consists of the page number and a
* logical tuple identifier.
*
* If a value is larger than the internal page size (4K), it is split into
* overflow pages. Appending data to a overflow page is very fast. Only the
* first and the last data page are loaded.
*
* Data pages are buffered.
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
*/
public class BFile extends BTree {
protected final static Logger LOGSTATS = Logger.getLogger( NativeBroker.EXIST_STATISTICS_LOGGER );
public final static short FILE_FORMAT_VERSION_ID = 13;
public final static long UNKNOWN_ADDRESS = -1;
public final static long DATA_SYNC_PERIOD = 15000;
// minimum free space a page should have to be
// considered for reusing
public final static int PAGE_MIN_FREE = 64;
// page signatures
public final static byte RECORD = 20;
public final static byte LOB = 21;
public final static byte FREE_LIST = 22;
public final static byte MULTI_PAGE = 23;
public static final int LENGTH_RECORDS_COUNT = 2; //sizeof short
public static final int LENGTH_NEXT_TID = 2; //sizeof short
/*
* Byte ids for the records written to the log file.
*/
public final static byte LOG_CREATE_PAGE = 0x30;
public final static byte LOG_STORE_VALUE = 0x31;
public final static byte LOG_REMOVE_VALUE = 0x32;
public final static byte LOG_REMOVE_PAGE = 0x33;
public final static byte LOG_OVERFLOW_APPEND = 0x34;
public final static byte LOG_OVERFLOW_STORE = 0x35;
public final static byte LOG_OVERFLOW_CREATE = 0x36;
public final static byte LOG_OVERFLOW_MODIFIED = 0x37;
public final static byte LOG_OVERFLOW_CREATE_PAGE = 0x38;
public final static byte LOG_OVERFLOW_REMOVE = 0x39;
static {
// register log entry types for this db file
LogEntryTypes.addEntryType(LOG_CREATE_PAGE, CreatePageLoggable.class);
LogEntryTypes.addEntryType(LOG_STORE_VALUE, StoreValueLoggable.class);
LogEntryTypes.addEntryType(LOG_REMOVE_VALUE, RemoveValueLoggable.class);
LogEntryTypes.addEntryType(LOG_REMOVE_PAGE, RemoveEmptyPageLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_APPEND, OverflowAppendLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_STORE, OverflowStoreLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_CREATE, OverflowCreateLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_MODIFIED, OverflowModifiedLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_CREATE_PAGE, OverflowCreatePageLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_REMOVE, OverflowRemoveLoggable.class);
}
protected BFileHeader fileHeader;
protected int minFree;
protected Cache dataCache = null;
protected Lock lock = null;
public int fixedKeyLen = -1;
protected int maxValueSize;
public BFile(BrokerPool pool, byte fileId, boolean transactional, File file, DefaultCacheManager cacheManager,
double cacheGrowth, double thresholdBTree, double thresholdData) throws DBException {
super(pool, fileId, transactional, cacheManager, file, thresholdBTree);
fileHeader = (BFileHeader) getFileHeader();
dataCache = new LRUCache(64, cacheGrowth, thresholdData, CacheManager.DATA_CACHE);
dataCache.setFileName(file.getName());
cacheManager.registerCache(dataCache);
minFree = PAGE_MIN_FREE;
lock = new ReentrantReadWriteLock(file.getName());
maxValueSize = fileHeader.getWorkSize() / 2;
if(exists()) {
open();
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating data file: " + getFile().getName());
}
create();
}
}
/**
* @return file version
*/
@Override
public short getFileVersion() {
return FILE_FORMAT_VERSION_ID;
}
/**
* Returns the Lock object responsible for this BFile.
*
* @return Lock
*/
public Lock getLock() {
return lock;
}
protected long getDataSyncPeriod() {
return DATA_SYNC_PERIOD;
}
/**
* Append the given data fragment to the value associated
* with the key. A new entry is created if the key does not
* yet exist in the database.
*
* @param key
* @param value
* @throws ReadOnlyException
* @throws IOException
*/
public long append(Value key, ByteArray value)
throws ReadOnlyException, IOException {
return append(null, key, value);
}
public long append(Txn transaction, Value key, ByteArray value) throws IOException {
if (key == null) {
LOG.debug("key is null");
return UNKNOWN_ADDRESS;
}
if (key.getLength() > fileHeader.getMaxKeySize()) {
//TODO : throw an exception ? -pb
LOG.warn("Key length exceeds page size! Skipping key ...");
return UNKNOWN_ADDRESS;
}
try {
// check if key exists already
long p = findValue(key);
if (p == KEY_NOT_FOUND) {
// key does not exist:
p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
}
// key exists: get old data
final long pnum = StorageAddress.pageFromPointer(p);
final short tid = StorageAddress.tidFromPointer(p);
final DataPage page = getDataPage(pnum);
if (page instanceof OverflowPage)
{((OverflowPage) page).append(transaction, value);}
else {
final int valueLen = value.size();
final byte[] data = page.getData();
final int offset = page.findValuePosition(tid);
if (offset < 0)
{throw new IOException("tid " + tid + " not found on page " + pnum);}
if (offset + 4 > data.length) {
LOG.error("found invalid pointer in file " + getFile().getName() +
" for page" + page.getPageInfo() + " : " +
"tid = " + tid + "; offset = " + offset);
return UNKNOWN_ADDRESS;
}
final int l = ByteConversion.byteToInt(data, offset);
//TOUNDERSTAND : unless l can be negative, we should never get there -pb
if (offset + 4 + l > data.length) {
LOG.error("found invalid data record in file " + getFile().getName() +
" for page" + page.getPageInfo() + " : " +
"length = " + data.length + "; required = " + (offset + 4 + l));
return UNKNOWN_ADDRESS;
}
final byte[] newData = new byte[l + valueLen];
System.arraycopy(data, offset + 4, newData, 0, l);
value.copyTo(newData, l);
p = update(transaction, p, page, key, new FixedByteArray(newData, 0, newData.length));
}
return p;
} catch (final BTreeException bte) {
LOG.warn("btree exception while appending value", bte);
}
return UNKNOWN_ADDRESS;
}
/**
* Close the BFile.
*
* @throws DBException
* @return always true
*/
@Override
public boolean close() throws DBException {
super.close();
return true;
}
/**
* Check, if key is contained in BFile.
*
* @param key key to look for
* @return true, if key exists
*/
public boolean containsKey(Value key) {
try {
return findValue(key) != KEY_NOT_FOUND;
} catch (final BTreeException e) {
LOG.warn(e.getMessage());
} catch (final IOException e) {
LOG.warn(e.getMessage());
}
return false;
}
@Override
public boolean create() throws DBException {
if (super.create((short) fixedKeyLen)) {
return true;
}
return false;
}
@Override
public void closeAndRemove() {
super.closeAndRemove();
cacheManager.deregisterCache(dataCache);
}
private SinglePage createDataPage() {
try {
final SinglePage page = new SinglePage();
dataCache.add(page, 2);
return page;
} catch (final IOException ioe) {
LOG.warn(ioe);
return null;
}
}
@Override
public FileHeader createFileHeader(int pageSize) {
return new BFileHeader(pageSize);
}
@Override
public PageHeader createPageHeader() {
return new BFilePageHeader();
}
/**
* Remove all entries matching the given query.
*
* @param query
* @throws IOException
* @throws BTreeException
*/
public void removeAll(Txn transaction, IndexQuery query) throws IOException, BTreeException {
// first collect the values to remove, then sort them by their page number
// and remove them.
try {
final RemoveCallback cb = new RemoveCallback();
remove(transaction, query, cb);
LOG.debug("Found " + cb.count + " items to remove.");
if (cb.count == 0)
{return;}
Arrays.sort(cb.pointers, 0, cb.count - 1);
for (int i = 0; i < cb.count; i++) {
remove(transaction, cb.pointers[i]);
}
} catch (final TerminatedException e) {
// Should never happen during remove
LOG.warn("removeAll() - method has been terminated.");
}
}
private class RemoveCallback implements BTreeCallback {
long[] pointers = new long[128];
int count = 0;
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
if (count == pointers.length) {
long[] np = new long[count * 2];
System.arraycopy(pointers, 0, np, 0, count);
pointers = np;
}
pointers[count++] = pointer;
return true;
}
}
public ArrayList<Value> findEntries(IndexQuery query) throws IOException,
BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(FindCallback.BOTH);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> findKeys(IndexQuery query)
throws IOException, BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(FindCallback.KEYS);
query(query, cb);
return cb.getValues();
}
public void find(IndexQuery query, IndexCallback callback)
throws IOException, BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(callback);
query(query, cb);
}
/* Flushes {@link org.exist.storage.btree.Paged#flush()dirty data} to the disk and cleans up the cache.
* @return <code>true</code> if something has actually been cleaned
*/
@Override
public boolean flush() throws DBException {
boolean flushed = false;
//TODO : consider log operation as a flush ?
if (isTransactional)
{logManager.flushToLog(true);}
flushed = flushed | dataCache.flush();
flushed = flushed | super.flush();
return flushed;
}
public BufferStats getDataBufferStats() {
if (dataCache == null)
{return null;}
return new BufferStats(dataCache.getBuffers(), dataCache.getUsedBuffers(),
dataCache.getHits(), dataCache.getFails());
}
@Override
public void printStatistics() {
super.printStatistics();
final NumberFormat nf = NumberFormat.getPercentInstance();
final StringBuilder buf = new StringBuilder();
buf.append(getFile().getName()).append(" DATA ");
buf.append("Buffers occupation : ");
if (dataCache.getBuffers() == 0 && dataCache.getUsedBuffers() == 0)
{buf.append("N/A");}
else
{buf.append(nf.format(dataCache.getUsedBuffers()/(float)dataCache.getBuffers()));}
buf.append(" (" + dataCache.getUsedBuffers() + " out of " + dataCache.getBuffers() + ")");
//buf.append(dataCache.getBuffers()).append(" / ");
//buf.append(dataCache.getUsedBuffers()).append(" / ");
buf.append(" Cache efficiency : ");
if (dataCache.getHits() == 0 && dataCache.getFails() == 0)
{buf.append("N/A");}
else
{buf.append(nf.format(dataCache.getHits()/(float)(dataCache.getHits() + dataCache.getFails())));}
//buf.append(dataCache.getHits()).append(" / ");
//buf.append(dataCache.getFails());
LOGSTATS.info(buf.toString());
}
/**
* Get the value data associated with the specified key
* or null if the key could not be found.
*
* @param key
*/
public Value get(Value key) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return null;}
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
return get(page, p);
} catch (final BTreeException e) {
LOG.warn("An exception occurred while trying to retrieve key " + key + ": " + e.getMessage(), e);
} catch (final IOException e) {
LOG.warn(e.getMessage(), e);
}
return null;
}
/**
* Get the value data for the given key as a variable byte
* encoded input stream.
*
* @param key
* @throws IOException
*/
public VariableByteInput getAsStream(Value key) throws IOException {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return null;}
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
switch (page.getPageHeader().getStatus()) {
case MULTI_PAGE:
return ((OverflowPage) page).getDataStream(p);
default:
return getAsStream(page, p);
}
} catch (final BTreeException e) {
LOG.warn("An exception occurred while trying to retrieve key " + key + ": " + e.getMessage(), e);
}
return null;
}
/**
* Get the value located at the specified address as a
* variable byte encoded input stream.
*
* @param pointer
* @throws IOException
*/
public VariableByteInput getAsStream(long pointer) throws IOException {
final DataPage page = getDataPage(StorageAddress.pageFromPointer(pointer));
switch (page.getPageHeader().getStatus()) {
case MULTI_PAGE:
return ((OverflowPage) page).getDataStream(pointer);
default:
return getAsStream(page, pointer);
}
}
private VariableByteInput getAsStream(DataPage page, long pointer) throws IOException {
dataCache.add(page.getFirstPage(), 2);
final short tid = StorageAddress.tidFromPointer(pointer);
final int offset = page.findValuePosition(tid);
if (offset < 0)
{throw new IOException("no data found at tid " + tid + "; page " + page.getPageNum());}
final byte[] data = page.getData();
final int l = ByteConversion.byteToInt(data, offset);
final SimplePageInput input = new SimplePageInput(data, offset + 4, l, pointer);
return input;
}
/**
* Returns the value located at the specified address.
*
* @param p
* @return value located at the specified address
*/
public Value get(long p) {
try {
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
return get(page, p);
} catch (final IOException e) {
LOG.debug(e);
}
return null;
}
/**
* Retrieve value at logical address p from page
*/
protected Value get(DataPage page, long p) throws IOException {
final short tid = StorageAddress.tidFromPointer(p);
final int offset = page.findValuePosition(tid);
final byte[] data = page.getData();
if (offset < 0 || offset > data.length) {
LOG.error("wrong pointer (tid: " + tid + page.getPageInfo()
+ ") in file " + getFile().getName() + "; offset = "
+ offset);
return null;
}
final int l = ByteConversion.byteToInt(data, offset);
if (l + 6 > data.length) {
LOG.error(getFile().getName() + " wrong data length in page "
+ page.getPageNum() + ": expected=" + (l + 6) + "; found="
+ data.length);
return null;
}
dataCache.add(page.getFirstPage());
final Value v = new Value(data, offset + 4, l);
v.setAddress(p);
return v;
}
private DataPage getDataPage(long pos) throws IOException {
return getDataPage(pos, true);
}
private DataPage getDataPage(long pos, boolean initialize) throws IOException {
final DataPage wp = (DataPage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
if (page == null) {
LOG.debug("page " + pos + " not found!");
return null;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() == MULTI_PAGE)
{return new OverflowPage(page, data);}
return new SinglePage(page, data, initialize);
} else if (wp.getPageHeader().getStatus() == MULTI_PAGE)
{return new OverflowPage(wp);}
else
{return wp;}
}
private SinglePage getSinglePage(long pos) throws IOException {
return getSinglePage(pos, false);
}
private SinglePage getSinglePage(long pos, boolean initialize) throws IOException {
final SinglePage wp = (SinglePage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
if (page == null) {
LOG.debug("page " + pos + " not found!");
return null;
}
final byte[] data = page.read();
return new SinglePage(page, data, initialize);
}
return wp;
}
public ArrayList<Value> getEntries() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.BOTH);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> getKeys() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.KEYS);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> getValues() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.VALUES);
query(query, cb);
return cb.getValues();
}
public boolean open() throws DBException {
return super.open(FILE_FORMAT_VERSION_ID);
}
/**
* Put data under given key.
*
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @see BFile#put(Value,byte[],boolean)
* @param key
* @param data the data (value) to update
* @param overwrite overwrite if set to true, value will be overwritten if it already exists
* @throws ReadOnlyException
*/
public long put(Value key, byte[] data, boolean overwrite) throws ReadOnlyException {
return put(null, key, data, overwrite);
}
public long put(Txn transaction, Value key, byte[] data, boolean overwrite)
/* throws ReadOnlyException */ {
SanityCheck.THROW_ASSERT(key.getLength() <= fileHeader.getWorkSize(), "Key length exceeds page size!");
final FixedByteArray buf = new FixedByteArray(data, 0, data.length);
return put(transaction, key, buf, overwrite);
}
/**
* Convenience method for {@link BFile#put(Value, byte[], boolean)}, overwrite is true.
*
* @param key with which the data is updated
* @param value value to update
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @throws ReadOnlyException
*/
public long put(Value key, ByteArray value) throws ReadOnlyException {
return put(key, value, true);
}
/**
* Put a value under given key. The difference of this
* method and {@link BFile#append(Value, ByteArray)} is,
* that the value gets updated and not stored.
*
* @param key with which the data is updated
* @param value value to update
* @param overwrite if set to true, value will be overwritten if it already exists
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @throws ReadOnlyException
*/
public long put(Value key, ByteArray value, boolean overwrite) throws ReadOnlyException {
return put(null, key, value, overwrite);
}
public long put(Txn transaction, Value key, ByteArray value, boolean overwrite) {
if (key == null) {
LOG.debug("key is null");
return UNKNOWN_ADDRESS;
}
if (key.getLength() > fileHeader.getWorkSize()) {
//TODO : exception ? -pb
LOG.warn("Key length exceeds page size! Skipping key ...");
return UNKNOWN_ADDRESS;
}
try {
try {
// check if key exists already
//TODO : rely on a KEY_NOT_FOUND (or maybe VALUE_NOT_FOUND) result ! -pb
long p = findValue(key);
if (p == KEY_NOT_FOUND) {
// key does not exist:
p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
}
// if exists, update value
if (overwrite) {
return update(transaction, p, key, value);
}
//TODO : throw an exception ? -pb
return UNKNOWN_ADDRESS;
//TODO : why catch an exception here ??? It costs too much ! -pb
} catch (final BTreeException bte) {
// key does not exist:
final long p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
} catch (final IOException ioe) {
ioe.printStackTrace();
LOG.warn(ioe);
return UNKNOWN_ADDRESS;
}
} catch (final IOException e) {
e.printStackTrace();
LOG.warn(e);
return UNKNOWN_ADDRESS;
} catch (final BTreeException bte) {
bte.printStackTrace();
LOG.warn(bte);
return UNKNOWN_ADDRESS;
}
}
public void remove(Value key) {
remove(null, key);
}
public void remove(Txn transaction, Value key) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return;}
final long pos = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pos);
remove(transaction, page, p);
removeValue(transaction, key);
} catch (final BTreeException bte) {
LOG.debug(bte);
} catch (final IOException ioe) {
LOG.debug(ioe);
}
}
public void remove(Txn transaction, long p) {
try {
final long pos = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pos);
remove(transaction, page, p);
} catch (final IOException e) {
LOG.debug("io problem", e);
}
}
private void remove(Txn transaction, DataPage page, long p) throws IOException {
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
// overflow page: simply delete the whole page
((OverflowPage)page).delete(transaction);
return;
}
final short tid = StorageAddress.tidFromPointer(p);
final int offset = page.findValuePosition(tid);
final byte[] data = page.getData();
if (offset > data.length || offset < 0) {
LOG.error("wrong pointer (tid: " + tid + ", " + page.getPageInfo() + ")");
return;
}
final int l = ByteConversion.byteToInt(data, offset);
if (isTransactional && transaction != null) {
final Loggable loggable = new RemoveValueLoggable(transaction, fileId, page.getPageNum(), tid, data, offset + 4, l);
writeToLog(loggable, page);
}
final BFilePageHeader ph = page.getPageHeader();
final int end = offset + 4 + l;
int len = ph.getDataLength();
// remove old value
System.arraycopy(data, end, data, offset - 2, len - end);
ph.setDirty(true);
ph.decRecordCount();
len = len - l - 6;
ph.setDataLength(len);
page.setDirty(true);
// if this page is empty, remove it
if (len == 0) {
if (isTransactional && transaction != null) {
final Loggable loggable = new RemoveEmptyPageLoggable(transaction, fileId, page.getPageNum());
writeToLog(loggable, page);
}
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(page.getPageNum()));
dataCache.remove(page);
page.delete();
} else {
page.removeTID(tid, l + 6);
// adjust free space data
final int newFree = fileHeader.getWorkSize() - len;
if (newFree > minFree) {
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null) {
free = new FreeSpace(page.getPageNum(), newFree);
fileHeader.addFreeSpace(free);
} else {
free.setFree(newFree);
}
}
dataCache.add(page, 2);
}
}
private final void saveFreeSpace(FreeSpace space, DataPage page) {
final int free = fileHeader.getWorkSize() - page.getPageHeader().getDataLength();
space.setFree(free);
if(free < minFree)
{fileHeader.removeFreeSpace(space);}
}
public void setLocation(String location) throws DBException {
setFile(new File(location + ".dbx"));
}
public long storeValue(Txn transaction, ByteArray value) throws IOException {
final int vlen = value.size();
// does value fit into a single page?
if (6 + vlen > maxValueSize) {
final OverflowPage page = new OverflowPage(transaction);
final byte[] data = new byte[vlen + 6];
page.getPageHeader().setDataLength(vlen + 6);
ByteConversion.shortToByte((short) 1, data, 0);
ByteConversion.intToByte(vlen, data, 2);
//System.arraycopy(value, 0, data, 6, vlen);
value.copyTo(data, 6);
page.setData(transaction, data);
page.setDirty(true);
//dataCache.add(page);
return StorageAddress.createPointer((int) page.getPageNum(),
(short) 1);
}
DataPage page = null;
short tid = -1;
FreeSpace free = null;
int realSpace = 0;
// check for available tid
while (tid < 0) {
free = fileHeader.findFreeSpace(vlen + 6);
if (free == null) {
page = createDataPage();
if (isTransactional && transaction != null) {
final Loggable loggable = new CreatePageLoggable(transaction, fileId, page.getPageNum());
writeToLog(loggable, page);
}
page.setData(new byte[fileHeader.getWorkSize()]);
free = new FreeSpace(page.getPageNum(),
fileHeader.getWorkSize() - page.getPageHeader().getDataLength());
fileHeader.addFreeSpace(free);
} else {
page = getDataPage(free.getPage());
// check if this is really a data page
if (page.getPageHeader().getStatus() != BFile.RECORD) {
LOG.warn("page " + page.getPageNum()
+ " is not a data page; removing it");
fileHeader.removeFreeSpace(free);
continue;
}
// check if the information about free space is really correct
realSpace = fileHeader.getWorkSize() - page.getPageHeader().getDataLength();
if (realSpace < 6 + vlen) {
// not correct: adjust and continue
LOG.warn("Wrong data length in list of free pages: adjusting to " + realSpace);
free.setFree(realSpace);
continue;
}
}
tid = page.getNextTID();
if (tid < 0) {
LOG.info("removing page " + page.getPageNum() + " from free pages");
fileHeader.removeFreeSpace(free);
}
}
if (isTransactional && transaction != null) {
final Loggable loggable = new StoreValueLoggable(transaction, fileId, page.getPageNum(), tid, value);
writeToLog(loggable, page);
}
int len = page.getPageHeader().getDataLength();
final byte[] data = page.getData();
// save tid
ByteConversion.shortToByte(tid, data, len);
len += 2;
page.setOffset(tid, len);
// save data length
ByteConversion.intToByte(vlen, data, len);
len += 4;
// save data
value.copyTo(data, len);
len += vlen;
page.getPageHeader().setDataLength(len);
page.getPageHeader().incRecordCount();
saveFreeSpace(free, page);
page.setDirty(true);
dataCache.add(page);
// return pointer from pageNum and offset into page
return StorageAddress.createPointer((int) page.getPageNum(), tid);
}
/**
* Update a key/value pair.
*
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public long update(Value key, ByteArray value) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return UNKNOWN_ADDRESS;}
return update(p, key, value);
} catch (final BTreeException bte) {
LOG.debug(bte);
} catch (final IOException ioe) {
LOG.debug(ioe);
}
return UNKNOWN_ADDRESS;
}
/**
* Update the key/value pair found at the logical address p.
*
* @param p
* Description of the Parameter
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public long update(long p, Value key, ByteArray value) {
return update(null, p, key, value);
}
public long update(Txn transaction, long p, Value key, ByteArray value) {
try {
return update(transaction, p, getDataPage(StorageAddress.pageFromPointer(p)),
key, value);
} catch (final BTreeException bte) {
LOG.debug(bte);
return UNKNOWN_ADDRESS;
} catch (final IOException ioe) {
LOG.warn(ioe.getMessage(), ioe);
return UNKNOWN_ADDRESS;
}
}
/**
* Update the key/value pair with logical address p and stored in page.
*
* @param p
* Description of the Parameter
* @param page
* Description of the Parameter
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @exception BTreeException
* Description of the Exception
* @exception IOException
* Description of the Exception
*/
protected long update(Txn transaction, long p, DataPage page, Value key, ByteArray value)
throws BTreeException, IOException {
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
final int valueLen = value.size();
// does value fit into a single page?
if (valueLen + 6 < maxValueSize) {
// yes: remove the overflow page
remove(transaction, page, p);
final long np = storeValue(transaction, value);
addValue(transaction, key, np);
return np;
}
// this is an overflow page: simply replace the value
final byte[] data = new byte[valueLen + 6];
// save tid
ByteConversion.shortToByte((short) 1, data, 0);
// save length
ByteConversion.intToByte(valueLen, data, 2);
// save data
value.copyTo(data, 6);
((OverflowPage)page).setData(transaction, data);
return p;
}
remove(transaction, page, p);
final long np = storeValue(transaction, value);
addValue(transaction, key, np);
return np;
}
public void debugFreeList() {
fileHeader.debugFreeList();
}
/* ---------------------------------------------------------------------------------
* Methods used by recovery and transaction management
* --------------------------------------------------------------------------------- */
/**
* Write loggable to the journal and update the LSN in the page header.
*/
private void writeToLog(Loggable loggable, DataPage page) {
try {
logManager.writeToLog(loggable);
page.getPageHeader().setLsn(loggable.getLsn());
} catch (final TransactionException e) {
LOG.warn(e.getMessage(), e);
}
}
private SinglePage getSinglePageForRedo(Loggable loggable, long pos) throws IOException {
final SinglePage wp = (SinglePage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD)
{return null;}
if (loggable != null && isUptodate(page, loggable))
{return null;}
return new SinglePage(page, data, true);
}
return wp;
}
private boolean isUptodate(Page page, Loggable loggable) {
return page.getPageHeader().getLsn() >= loggable.getLsn();
}
private boolean requiresRedo(Loggable loggable, DataPage page) {
return loggable.getLsn() > page.getPageHeader().getLsn();
}
protected void redoStoreValue(StoreValueLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.page);
if (page != null && requiresRedo(loggable, page)) {
storeValueHelper(loggable, loggable.tid, loggable.value, page);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage());
}
}
protected void undoStoreValue(StoreValueLoggable loggable) {
try {
final SinglePage page = (SinglePage) getDataPage(loggable.page, true);
removeValueHelper(null, loggable.tid, page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoCreatePage(CreatePageLoggable loggable) {
createPageHelper(loggable, loggable.newPage);
}
protected void undoCreatePage(CreatePageLoggable loggable) {
try {
final SinglePage page = (SinglePage) getDataPage(loggable.newPage);
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(page.getPageNum()));
dataCache.remove(page);
page.delete();
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoRemoveValue(RemoveValueLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.page);
if (wp == null) {
final Page page = getPage(loggable.page);
if (page == null) {
LOG.warn("page " + loggable.page + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable)) {
// page is obviously deleted later
return;
}
wp = new SinglePage(page, data, true);
}
if (wp.ph.getLsn() != Page.NO_PAGE && requiresRedo(loggable, wp)) {
removeValueHelper(loggable, loggable.tid, wp);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemoveValue(RemoveValueLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.page, true);
final FixedByteArray data = new FixedByteArray(loggable.oldData);
storeValueHelper(null, loggable.tid, data, page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during undo: " + e.getMessage(), e);
}
}
protected void redoRemovePage(RemoveEmptyPageLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.page);
if (wp == null) {
final Page page = getPage(loggable.page);
if (page == null) {
LOG.warn("page " + loggable.page + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable)) {
return;
}
wp = new SinglePage(page, data, false);
}
if (wp.getPageHeader().getLsn() == Lsn.LSN_INVALID || requiresRedo(loggable, wp)) {
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(wp.getPageNum()));
dataCache.remove(wp);
wp.delete();
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemovePage(RemoveEmptyPageLoggable loggable) {
createPageHelper(loggable, loggable.page);
}
protected void redoCreateOverflow(OverflowCreateLoggable loggable) {
try {
DataPage firstPage = (DataPage) dataCache.get(loggable.pageNum);
if (firstPage == null) {
final Page page = getPage(loggable.pageNum);
byte[] data = page.read();
if (page.getPageHeader().getLsn() == Lsn.LSN_INVALID || requiresRedo(loggable, page)) {
reuseDeleted(page);
final BFilePageHeader ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(MULTI_PAGE);
ph.setNextInChain(0L);
ph.setLastInChain(0L);
ph.setDataLength(0);
ph.nextTID = 32;
data = new byte[fileHeader.getWorkSize()];
firstPage = new SinglePage(page, data, true);
firstPage.setDirty(true);
} else
{firstPage = new SinglePage(page, data, false);}
}
if (firstPage.getPageHeader().getLsn() != Page.NO_PAGE && requiresRedo(loggable, firstPage)) {
firstPage.getPageHeader().setLsn(loggable.getLsn());
firstPage.setDirty(true);
}
dataCache.add(firstPage);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoCreateOverflow(OverflowCreateLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
dataCache.remove(page);
page.delete();
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoCreateOverflowPage(OverflowCreatePageLoggable loggable) {
createPageHelper(loggable, loggable.newPage);
if (loggable.prevPage != Page.NO_PAGE) {
try {
final SinglePage page = getSinglePageForRedo(null, loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(loggable.newPage);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
}
protected void undoCreateOverflowPage(OverflowCreatePageLoggable loggable) {
try {
SinglePage page = getSinglePage(loggable.newPage);
dataCache.remove(page);
page.delete();
if (loggable.prevPage != Page.NO_PAGE) {
try {
page = getSinglePage(loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(0);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoAppendOverflow(OverflowAppendLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
loggable.data.copyTo(0, page.getData(), ph.getDataLength(), loggable.chunkSize);
ph.setDataLength(ph.getDataLength() + loggable.chunkSize);
ph.setLsn(loggable.getLsn());
page.setDirty(true);
dataCache.add(page);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoAppendOverflow(OverflowAppendLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(ph.getDataLength() - loggable.chunkSize);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoStoreOverflow(OverflowStoreLoggable loggable) {
try {
SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
try {
System.arraycopy(loggable.data, 0, page.getData(), 0, loggable.size);
} catch (final ArrayIndexOutOfBoundsException e) {
LOG.warn(loggable.data.length + "; " + page.getData().length + "; " + ph.getDataLength() + "; " + loggable.size);
throw e;
}
ph.setDataLength(loggable.size);
ph.setNextInChain(0);
ph.setLsn(loggable.getLsn());
page.setDirty(true);
dataCache.add(page);
if (loggable.prevPage != Page.NO_PAGE) {
page = getSinglePage(loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(loggable.pageNum);
page.setDirty(true);
dataCache.add(page);
}
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoModifiedOverflow(OverflowModifiedLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(loggable.length);
ph.setLastInChain(loggable.lastInChain);
// adjust length field in first page
ByteConversion.intToByte(ph.getDataLength() - 6, page.getData(), 2);
page.setDirty(true);
// keep the first page in cache
dataCache.add(page, 2);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoModifiedOverflow(OverflowModifiedLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(loggable.oldLength);
// adjust length field in first page
ByteConversion.intToByte(ph.getDataLength() - 6, page.getData(), 2);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during undo: " + e.getMessage(), e);
}
}
protected void redoRemoveOverflow(OverflowRemoveLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.pageNum);
if (wp == null) {
final Page page = getPage(loggable.pageNum);
if (page == null) {
LOG.warn("page " + loggable.pageNum + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable))
{return;}
wp = new SinglePage(page, data, true);
}
if (requiresRedo(loggable, wp)) {
wp.setDirty(true);
dataCache.remove(wp);
wp.delete();
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemoveOverflow(OverflowRemoveLoggable loggable) {
final DataPage page = createPageHelper(loggable, loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setStatus(loggable.status);
ph.setDataLength(loggable.length);
ph.setNextInChain(loggable.nextInChain);
page.setData(loggable.data);
page.setDirty(true);
dataCache.add(page);
}
private void storeValueHelper(Loggable loggable, short tid, ByteArray value, SinglePage page) {
int len = page.ph.getDataLength();
// save tid
ByteConversion.shortToByte(tid, page.data, len);
len += 2;
page.adjustTID(tid);
page.setOffset(tid, len);
// save data length
ByteConversion.intToByte(value.size(), page.data, len);
len += 4;
// save data
try {
value.copyTo(page.data, len);
} catch (final RuntimeException e) {
LOG.warn(getFile().getName() + ": storage error in page: " + page.getPageNum() +
"; len: " + len + " ; value: " + value.size() + "; max: " + fileHeader.getWorkSize() +
"; status: " + page.ph.getStatus());
LOG.debug(page.printContents());
throw e;
}
len += value.size();
page.ph.setDataLength(len);
page.ph.incRecordCount();
if (loggable != null)
{page.ph.setLsn(loggable.getLsn());}
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null)
{free = new FreeSpace(page.getPageNum(), fileHeader.getWorkSize() - len);}
saveFreeSpace(free, page);
page.setDirty(true);
dataCache.add(page);
}
private void removeValueHelper(Loggable loggable, short tid, SinglePage page) throws IOException {
final int offset = page.findValuePosition(tid);
if (offset < 0) {
LOG.warn("TID: " + tid + " not found on page: " + page.getPageNum());
return;
}
final int l = ByteConversion.byteToInt(page.data, offset);
final int end = offset + 4 + l;
int len = page.ph.getDataLength();
// remove old value
System.arraycopy(page.data, end, page.data, offset - 2, len - end);
page.ph.setDirty(true);
page.ph.decRecordCount();
len = len - l - 6;
page.ph.setDataLength(len);
if (loggable != null)
{page.ph.setLsn(loggable.getLsn());}
page.setDirty(true);
if (len > 0) {
page.removeTID(tid, l + 6);
// adjust free space data
final int newFree = fileHeader.getWorkSize() - len;
if (newFree > minFree) {
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null) {
free = new FreeSpace(page.getPageNum(), newFree);
fileHeader.addFreeSpace(free);
} else {
free.setFree(newFree);
}
}
dataCache.add(page, 2);
}
}
private DataPage createPageHelper(Loggable loggable, long newPage) {
try {
DataPage dp = (DataPage) dataCache.get(newPage);
if (dp == null) {
final Page page = getPage(newPage);
byte[] data = page.read();
if (page.getPageHeader().getLsn() == Lsn.LSN_INVALID || (loggable != null && requiresRedo(loggable, page)) ) {
reuseDeleted(page);
final BFilePageHeader ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(RECORD);
ph.setDataLength(0);
ph.setDataLen(fileHeader.getWorkSize());
data = new byte[fileHeader.getWorkSize()];
ph.nextTID = 32;
dp = new SinglePage(page, data, true);
} else {
dp = new SinglePage(page, data, true);
}
}
if (loggable != null && loggable.getLsn() > dp.getPageHeader().getLsn())
{dp.getPageHeader().setLsn(loggable.getLsn());}
dp.setDirty(true);
dataCache.add(dp);
return dp;
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
return null;
}
/**
* The file header. Most important, the file header stores the list of
* data pages containing unused space.
*
* @author wolf
*/
private final class BFileHeader extends BTreeFileHeader {
private FreeList freeList = new FreeList();
//public final static int MAX_FREE_LIST_LEN = 128;
public BFileHeader(int pageSize) {
super(pageSize);
}
public void addFreeSpace(FreeSpace freeSpace) {
freeList.add(freeSpace);
setDirty(true);
}
public FreeSpace findFreeSpace(int needed) {
return freeList.find(needed);
}
public FreeSpace getFreeSpace(long page) {
return freeList.retrieve(page);
}
public void removeFreeSpace(FreeSpace space) {
if (space == null) {return;}
freeList.remove(space);
setDirty(true);
}
public void debugFreeList() {
LOG.debug(getFile().getName() + ": " + freeList.toString());
}
@Override
public int read(byte[] buf) throws IOException {
final int offset = super.read(buf);
return freeList.read(buf, offset);
}
@Override
public int write(byte[] buf) throws IOException {
final int offset = super.write(buf);
return freeList.write(buf, offset);
}
}
private final class BFilePageHeader extends BTreePageHeader {
private int dataLen = 0;
private long lastInChain = -1L;
private long nextInChain = -1L;
// tuple identifier: used to identify distinct
// values inside a page
private short nextTID = -1;
private short records = 0;
public BFilePageHeader() {
super();
}
public BFilePageHeader(byte[] data, int offset) throws IOException {
super(data, offset);
}
public void decRecordCount() {
records--;
}
public int getDataLength() {
return dataLen;
}
public long getLastInChain() {
return lastInChain;
}
public long getNextInChain() {
return nextInChain;
}
public short getNextTID() {
if (nextTID == Short.MAX_VALUE) {
LOG.warn("tid limit reached");
return -1;
}
return ++nextTID;
}
public short getCurrentTID() {
if(nextTID == Short.MAX_VALUE) {
return -1;
}
return nextTID;
}
public short getRecordCount() {
return records;
}
public void incRecordCount() {
records++;
}
@Override
public int read(byte[] data, int offset) throws IOException {
offset = super.read(data, offset);
records = ByteConversion.byteToShort(data, offset);
offset += LENGTH_RECORDS_COUNT;
dataLen = ByteConversion.byteToInt(data, offset);
offset += 4;
nextTID = ByteConversion.byteToShort(data, offset);
offset += LENGTH_NEXT_TID;
nextInChain = ByteConversion.byteToLong(data, offset);
offset += 8;
lastInChain = ByteConversion.byteToLong(data, offset);
return offset + 8;
}
public void setDataLength(int len) {
dataLen = len;
}
public void setLastInChain(long p) {
lastInChain = p;
}
public void setNextInChain(long b) {
nextInChain = b;
}
public void setRecordCount(short recs) {
records = recs;
}
public void setTID(short tid) {
this.nextTID = tid;
}
@Override
public int write(byte[] data, int offset) throws IOException {
offset = super.write(data, offset);
ByteConversion.shortToByte(records, data, offset);
offset += LENGTH_RECORDS_COUNT;
ByteConversion.intToByte(dataLen, data, offset);
offset += 4;
ByteConversion.shortToByte(nextTID, data, offset);
offset += LENGTH_NEXT_TID;
ByteConversion.longToByte(nextInChain, data, offset);
offset += 8;
ByteConversion.longToByte(lastInChain, data, offset);
return offset + 8;
}
}
private abstract class DataPage implements Comparable, Cacheable {
int refCount = 0;
int timestamp = 0;
boolean saved = true;
public abstract void delete() throws IOException;
public abstract byte[] getData() throws IOException;
public abstract BFilePageHeader getPageHeader();
public abstract String getPageInfo();
public abstract long getPageNum();
public abstract int findValuePosition(short tid) throws IOException;
public abstract short getNextTID();
public abstract void removeTID(short tid, int length) throws IOException;
public abstract void setOffset(short tid, int offset);
public long getKey() {
return getPageNum();
}
public int getReferenceCount() {
return refCount;
}
public int incReferenceCount() {
if (refCount < Cacheable.MAX_REF) {++refCount;}
return refCount;
}
public int decReferenceCount() {
return refCount > 0 ? --refCount : 0;
}
public void setReferenceCount(int count) {
refCount = count;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#setTimestamp(int)
*/
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#getTimestamp()
*/
public int getTimestamp() {
return timestamp;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#release()
*/
public boolean sync(boolean syncJournal) {
if (isDirty()) {
try {
write();
if (isTransactional && syncJournal && logManager.lastWrittenLsn() < getPageHeader().getLsn())
{logManager.flushToLog(true);}
return true;
} catch (final IOException e) {
LOG.error("IO exception occurred while saving page "
+ getPageNum());
}
}
return false;
}
public boolean isDirty() {
return !saved;
}
public boolean allowUnload() {
return true;
}
public abstract void setData(byte[] buf);
public abstract SinglePage getFirstPage();
public void setDirty(boolean dirty) {
saved = !dirty;
getPageHeader().setDirty(dirty);
}
public abstract void write() throws IOException;
public int compareTo(Object other) {
if (getPageNum() == ((DataPage) other).getPageNum())
{return Constants.EQUAL;}
else if (getPageNum() > ((DataPage) other).getPageNum())
{return Constants.SUPERIOR;}
else
{return Constants.INFERIOR;}
}
}
private final class FilterCallback implements BTreeCallback {
BFileCallback callback;
public FilterCallback(BFileCallback callback) {
this.callback = callback;
}
public boolean indexInfo(Value value, long pointer) throws TerminatedException{
try {
long pos;
short tid;
DataPage page;
int offset;
int l;
Value v;
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
offset = page.findValuePosition(tid);
final byte[] data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
callback.info(value, v);
return true;
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
return true;
}
}
}
private final class FindCallback implements BTreeCallback {
public final static int BOTH = 2;
public final static int KEYS = 1;
public final static int VALUES = 0;
private int mode = VALUES;
private IndexCallback callback = null;
private ArrayList<Value> values = null;
public FindCallback(int mode) {
this.mode = mode;
values = new ArrayList<Value>();
}
public FindCallback(IndexCallback callback) {
this.mode = BOTH;
this.callback = callback;
}
public ArrayList<Value> getValues() {
return values;
}
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
long pos;
short tid;
DataPage page;
int offset;
int l;
Value v;
byte[] data;
try {
switch (mode) {
case VALUES:
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
dataCache.add(page.getFirstPage());
offset = page.findValuePosition(tid);
data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
v.setAddress(pointer);
if (callback == null)
{values.add(v);}
else
{return callback.indexInfo(value, v);}
return true;
case KEYS:
value.setAddress(pointer);
if (callback == null)
{values.add(value);}
else
{return callback.indexInfo(value, null);}
return true;
case BOTH:
final Value[] entry = new Value[2];
entry[0] = value;
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
data = page.getData();
}
dataCache.add(page.getFirstPage());
offset = page.findValuePosition(tid);
data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
v.setAddress(pointer);
entry[1] = v;
if (callback == null) {
values.add(entry[0]);
values.add(entry[1]);
} else
{return callback.indexInfo(value, v);}
return true;
}
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
}
return false;
}
}
private final class OverflowPage extends DataPage {
byte[] data = null;
SinglePage firstPage;
public OverflowPage(Txn transaction) throws IOException {
firstPage = new SinglePage(false);
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowCreateLoggable(fileId, transaction, firstPage.getPageNum());
writeToLog(loggable, firstPage);
}
final BFilePageHeader ph = firstPage.getPageHeader();
ph.setStatus(MULTI_PAGE);
ph.setNextInChain(0L);
ph.setLastInChain(0L);
ph.setDataLength(0);
firstPage.setData(new byte[fileHeader.getWorkSize()]);
dataCache.add(firstPage, 3);
}
public OverflowPage(DataPage page) {
firstPage = (SinglePage) page;
}
public OverflowPage(Page p, byte[] data) throws IOException {
firstPage = new SinglePage(p, data, false);
firstPage.getPageHeader().setStatus(MULTI_PAGE);
}
/**
* Append a new chunk of data to the page
*
* @param chunk
* chunk of data to append
*/
public void append(Txn transaction, ByteArray chunk) throws IOException {
SinglePage nextPage;
BFilePageHeader ph = firstPage.getPageHeader();
final int newLen = ph.getDataLength() + chunk.size();
// get the last page and fill it
final long next = ph.getLastInChain();
DataPage page;
if (next > 0)
{page = getDataPage(next, false);}
else
{page = firstPage;}
ph = page.getPageHeader();
int chunkSize = fileHeader.getWorkSize() - ph.getDataLength();
final int chunkLen = chunk.size();
if (chunkLen < chunkSize) {chunkSize = chunkLen;}
// fill last page
if (isTransactional && transaction != null) {
final Loggable loggable =
new OverflowAppendLoggable(fileId, transaction, page.getPageNum(), chunk, 0, chunkSize);
writeToLog(loggable, page);
}
chunk.copyTo(0, page.getData(), ph.getDataLength(), chunkSize);
if(page != firstPage)
{ph.setDataLength(ph.getDataLength() + chunkSize);}
page.setDirty(true);
// write the remaining chunks to new pages
int remaining = chunkLen - chunkSize;
int current = chunkSize;
chunkSize = fileHeader.getWorkSize();
if (remaining > 0) {
// walk through chain of pages
while (remaining > 0) {
if (remaining < chunkSize) {chunkSize = remaining;}
// add a new page to the chain
nextPage = createDataPage();
if (isTransactional && transaction != null) {
Loggable loggable = new OverflowCreatePageLoggable(transaction, fileId, nextPage.getPageNum(),
page.getPageNum());
writeToLog(loggable, nextPage);
loggable = new OverflowAppendLoggable(fileId, transaction, nextPage.getPageNum(),
chunk, current, chunkSize);
writeToLog(loggable, page);
}
nextPage.setData(new byte[fileHeader.getWorkSize()]);
page.getPageHeader().setNextInChain(nextPage.getPageNum());
page.setDirty(true);
dataCache.add(page);
page = nextPage;
// copy next chunk of data to the page
chunk.copyTo(current, page.getData(), 0, chunkSize);
page.setDirty(true);
if (page != firstPage)
{page.getPageHeader().setDataLength(chunkSize);}
remaining = remaining - chunkSize;
current += chunkSize;
}
}
ph = firstPage.getPageHeader();
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowModifiedLoggable(fileId, transaction, firstPage.getPageNum(),
ph.getDataLength() + chunkLen, ph.getDataLength(), page == firstPage ? 0 : page.getPageNum());
writeToLog(loggable, page);
}
if (page != firstPage) {
// add link to last page
dataCache.add(page);
ph.setLastInChain(page.getPageNum());
} else
{ph.setLastInChain(0L);}
// adjust length field in first page
ph.setDataLength(newLen);
ByteConversion.intToByte(firstPage.getPageHeader().getDataLength() - 6, firstPage.getData(), 2);
firstPage.setDirty(true);
// keep the first page in cache
dataCache.add(firstPage, 2);
}
@Override
public void delete() throws IOException {
delete(null);
}
public void delete(Txn transaction) throws IOException {
long next = firstPage.getPageNum();
SinglePage page = firstPage;
do {
next = page.ph.getNextInChain();
if (isTransactional && transaction != null) {
int dataLen = page.ph.getDataLength();
if (dataLen > fileHeader.getWorkSize())
{dataLen = fileHeader.getWorkSize();}
final Loggable loggable = new OverflowRemoveLoggable(fileId, transaction,
page.ph.getStatus(), page.getPageNum(),
page.getData(), dataLen,
page.ph.getNextInChain());
writeToLog(loggable, page);
}
page.getPageHeader().setNextInChain(-1L);
page.setDirty(true);
dataCache.remove(page);
page.delete();
if (next > 0) {page = getSinglePage(next);}
} while (next > 0);
}
public VariableByteInput getDataStream(long pointer) {
final MultiPageInput input = new MultiPageInput(firstPage, pointer);
return input;
}
@Override
public byte[] getData() throws IOException {
if (data != null) {return data;}
SinglePage page = firstPage;
long next;
byte[] temp;
int len;
final ByteArrayOutputStream os = new ByteArrayOutputStream(page
.getPageHeader().getDataLength());
do {
temp = page.getData();
next = page.getPageHeader().getNextInChain();
len = next > 0 ? fileHeader.getWorkSize() : page
.getPageHeader().getDataLength();
os.write(temp, 0, len);
if (next > 0) {
page = (SinglePage) getDataPage(next, false);
dataCache.add(page);
}
} while (next > 0);
data = os.toByteArray();
if (data.length != firstPage.getPageHeader().getDataLength()) {
LOG.warn(getFile().getName() + " read=" + data.length
+ "; expected="
+ firstPage.getPageHeader().getDataLength());
}
return data;
}
@Override
public SinglePage getFirstPage() {
return firstPage;
}
@Override
public BFilePageHeader getPageHeader() {
return firstPage.getPageHeader();
}
@Override
public String getPageInfo() {
return "MULTI_PAGE: " + firstPage.getPageInfo();
}
@Override
public long getPageNum() {
return firstPage.getPageNum();
}
@Override
public void setData(byte[] buf) {
setData(null, buf);
}
public void setData(Txn transaction, byte[] data) {
this.data = data;
try {
write(transaction);
} catch (final IOException e) {
LOG.warn(e);
}
}
@Override
public void write() throws IOException {
write(null);
}
public void write(Txn transaction) throws IOException {
if (data == null) {return;}
int chunkSize = fileHeader.getWorkSize();
int remaining = data.length;
int current = 0;
long next = 0L;
SinglePage page = firstPage;
page.getPageHeader().setDataLength(remaining);
SinglePage nextPage;
long prevPageNum = Page.NO_PAGE;
// walk through chain of pages
while (remaining > 0) {
if (remaining < chunkSize) {chunkSize = remaining;}
page.clear();
// copy next chunk of data to the page
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowStoreLoggable(fileId, transaction, page.getPageNum(), prevPageNum,
data, current, chunkSize);
writeToLog(loggable, page);
}
System.arraycopy(data, current, page.getData(), 0, chunkSize);
if (page != firstPage)
{page.getPageHeader().setDataLength(chunkSize);}
page.setDirty(true);
remaining -= chunkSize;
current += chunkSize;
next = page.getPageHeader().getNextInChain();
if (remaining > 0) {
if (next > 0) {
// load next page in chain
nextPage = (SinglePage) getDataPage(next, false);
dataCache.add(page);
prevPageNum = page.getPageNum();
page = nextPage;
} else {
// add a new page to the chain
nextPage = createDataPage();
if (isTransactional && transaction != null) {
final Loggable loggable = new CreatePageLoggable(transaction, fileId, nextPage.getPageNum());
writeToLog(loggable, nextPage);
}
nextPage.setData(new byte[fileHeader.getWorkSize()]);
nextPage.getPageHeader().setNextInChain(0L);
page.getPageHeader().setNextInChain(
nextPage.getPageNum());
dataCache.add(page);
prevPageNum = page.getPageNum();
page = nextPage;
}
} else {
page.getPageHeader().setNextInChain(0L);
if (page != firstPage) {
page.setDirty(true);
dataCache.add(page);
firstPage.getPageHeader().setLastInChain(
page.getPageNum());
} else
{firstPage.getPageHeader().setLastInChain(0L);}
firstPage.setDirty(true);
dataCache.add(firstPage, 3);
}
}
if (next > 0) {
// there are more pages in the chain:
// remove them
while (next > 0) {
nextPage = (SinglePage) getDataPage(next, false);
next = nextPage.getPageHeader().getNextInChain();
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowRemoveLoggable(fileId, transaction,
nextPage.getPageHeader().getStatus(), nextPage.getPageNum(),
nextPage.getData(), nextPage.getPageHeader().getDataLength(),
nextPage.getPageHeader().getNextInChain());
writeToLog(loggable, nextPage);
}
nextPage.setDirty(true);
nextPage.delete();
dataCache.remove(nextPage);
}
}
firstPage.getPageHeader().setDataLength(data.length);
firstPage.setDirty(true);
dataCache.add(firstPage, 3);
// LOG.debug(firstPage.getPageNum() + " data length: " + firstPage.ph.getDataLength());
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#findValuePosition(short)
*/
@Override
public int findValuePosition(short tid) throws IOException {
return 2;
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#getNextTID()
*/
@Override
public short getNextTID() {
return 1;
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#removeTID(short)
*/
@Override
public void removeTID(short tid, int length) {
//
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#setOffset(short, int)
*/
@Override
public void setOffset(short tid, int offset) {
//
}
}
public interface PageInputStream {
public long getAddress();
public long position();
public void seek(long position) throws IOException;
}
/**
* Variable byte input stream to read data from a single page.
*
* @author wolf
*/
private final class SimplePageInput extends VariableByteArrayInput
implements PageInputStream {
private long address = 0L;
public SimplePageInput(byte[] data, int start, int len, long address) {
super(data, start, len);
this.address = address;
}
public long getAddress() {
return address;
}
public long position() {
return position;
}
public void seek(long pos) throws IOException {
this.position = (int) pos;
}
}
/**
* Variable byte input stream to read a multi-page sequences.
*
* @author wolf
*/
private final class MultiPageInput implements VariableByteInput, PageInputStream {
private SinglePage nextPage;
private int pageLen;
private short offset = 0;
private long address = 0L;
public MultiPageInput(SinglePage first, long address) {
nextPage = first;
offset = 6;
pageLen = first.ph.getDataLength();
if (pageLen > fileHeader.getWorkSize())
{pageLen = fileHeader.getWorkSize();}
dataCache.add(first, 3);
this.address = address;
}
public long getAddress() {
return address;
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read()
*/
public final int read() throws IOException {
if (offset == pageLen) {
advance();
}
return (nextPage.data[offset++] & 0xFF);
}
/*
* (non-Javadoc)
*
* @see org.exist.util.VariableInputStream#readByte()
*/
public final byte readByte() throws IOException {
if (offset == pageLen) {advance();}
return (nextPage.data[offset++]);
}
public final short readShort() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
short i = (short) (b & 0177);
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177) << shift;
}
return i;
}
public final int readInt() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
int i = b & 0177;
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177) << shift;
}
return i;
}
public int readFixedInt() throws IOException {
if (offset == pageLen) {advance();}
// do we have to read across a page boundary?
if (offset + 4 < pageLen) {
return ( nextPage.data[offset++] & 0xff ) |
( (nextPage.data[offset++] & 0xff) << 8 ) |
( (nextPage.data[offset++] & 0xff) << 16 ) |
( (nextPage.data[offset++] & 0xff) << 24 );
}
int r = nextPage.data[offset++] & 0xff;
int shift = 8;
for (int i = 0; i < 3; i++) {
if (offset == pageLen) {advance();}
r |= (nextPage.data[offset++] & 0xff) << shift;
shift += 8;
}
return r;
}
public final long readLong() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
long i = b & 0177;
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177L) << shift;
}
return i;
}
public final void skip(int count) throws IOException {
for (int i = 0; i < count; i++) {
do {
if (offset == pageLen) {advance();}
} while ((nextPage.data[offset++] & 0200) > 0);
}
}
public final void skipBytes(long count) throws IOException {
for(long i = 0; i < count; i++) {
if (offset == pageLen) {advance();}
offset++;
}
}
private final void advance() throws IOException {
final long next = nextPage.getPageHeader().getNextInChain();
if (next < 1) {
pageLen = -1;
offset = 0;
throw new EOFException();
}
try {
lock.acquire(Lock.READ_LOCK);
nextPage = (SinglePage) getDataPage(next, false);
pageLen = nextPage.ph.getDataLength();
offset = 0;
dataCache.add(nextPage);
} catch (final LockException e) {
throw new IOException("failed to acquire a read lock on "
+ getFile().getName());
} finally {
lock.release(Lock.READ_LOCK);
}
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#available()
*/
public final int available() throws IOException {
if (pageLen < 0)
{return 0;}
int inPage = pageLen - offset;
if (inPage == 0)
{inPage = nextPage.getPageHeader().getNextInChain() > 0 ? 1 : 0;}
return inPage;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#read(byte[])
*/
public final int read(byte[] data) throws IOException {
return read(data, 0, data.length);
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read(byte[], int, int)
*/
public final int read(byte[] b, int off, int len) throws IOException {
if (pageLen < 0) {return -1;}
for (int i = 0; i < len; i++) {
if (offset == pageLen) {
final long next = nextPage.getPageHeader().getNextInChain();
if (next < 1) {
pageLen = -1;
offset = 0;
return i;
}
nextPage = (SinglePage) getDataPage(next, false);
pageLen = nextPage.ph.getDataLength();
offset = 0;
dataCache.add(nextPage);
}
b[off + i] = nextPage.data[offset++];
}
return len;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#readUTF()
*/
public final String readUTF() throws IOException, EOFException {
final int len = readInt();
final byte data[] = new byte[len];
read(data);
String s;
try {
s = new String(data, "UTF-8");
} catch (final UnsupportedEncodingException e) {
LOG.warn(e);
s = new String(data);
}
return s;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#copyTo(org.exist.storage.io.VariableByteOutputStream)
*/
public final void copyTo(VariableByteOutputStream os) throws IOException {
byte more;
do {
if (offset == pageLen) {advance();}
more = nextPage.data[offset++];
os.writeByte(more);
more &= 0200;
} while (more > 0);
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#copyTo(org.exist.storage.io.VariableByteOutputStream,
* int)
*/
public final void copyTo(VariableByteOutputStream os, int count) throws IOException {
byte more;
for (int i = 0; i < count; i++) {
do {
if (offset == pageLen) {advance();}
more = nextPage.data[offset++];
os.writeByte(more);
} while ((more & 0x200) > 0);
}
}
public void copyRaw(VariableByteOutputStream os, int count) throws IOException {
for (int i = count; i != 0; ) {
if (offset == pageLen) {advance();}
int avail = pageLen - offset;
if (i >= avail) {
os.write(nextPage.data, offset, avail);
i -= avail;
offset = (short) pageLen;
} else {
os.write(nextPage.data, offset, i);
offset += i;
break;
}
//os.writeByte(nextPage.data[offset++]);
}
}
public long position() {
return StorageAddress.createPointer((int) nextPage.getPageNum(), offset);
}
public void seek(long position) throws IOException {
final int newPage = StorageAddress.pageFromPointer(position);
short newOffset = StorageAddress.tidFromPointer(position);
try {
lock.acquire(Lock.READ_LOCK);
nextPage = getSinglePage(newPage);
pageLen = nextPage.ph.getDataLength();
if (pageLen > fileHeader.getWorkSize())
{pageLen = fileHeader.getWorkSize();}
offset = newOffset;
dataCache.add(nextPage);
} catch (final LockException e) {
throw new IOException("Failed to acquire a read lock on " + getFile().getName());
} finally {
lock.release(Lock.READ_LOCK);
}
}
}
/**
* Represents a single data page (as opposed to a overflow page).
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
*/
private final class SinglePage extends DataPage {
// the raw working data of this page (without page header)
byte[] data = null;
// the low-level page
Page page;
// the page header
BFilePageHeader ph;
// table mapping record ids (tids) to offsets
short[] offsets = null;
public SinglePage() throws IOException {
this(true);
}
public SinglePage(boolean compress) throws IOException {
page = getFreePage();
ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(RECORD);
ph.setDirty(true);
ph.setDataLength(0);
//ph.setNextChunk( -1 );
data = new byte[fileHeader.getWorkSize()];
offsets = new short[32];
ph.nextTID = 32;
Arrays.fill(offsets, (short)-1);
}
public SinglePage(Page p, byte[] data, boolean initialize) throws IOException {
if (p == null) {throw new IOException("illegal page");}
if (!(p.getPageHeader().getStatus() == RECORD || p.getPageHeader()
.getStatus() == MULTI_PAGE)) {
final IOException e = new IOException("not a data-page: "
+ p.getPageHeader().getStatus());
LOG.debug("not a data-page: " + p.getPageInfo(), e);
throw e;
}
this.data = data;
page = p;
ph = (BFilePageHeader) page.getPageHeader();
if(initialize) {
offsets = new short[ph.nextTID];
if (ph.getStatus() != MULTI_PAGE)
readOffsets();
}
}
@Override
public final int findValuePosition(short tid) throws IOException {
return offsets[tid];
}
private void readOffsets() {
//if(offsets.length > 256)
//LOG.warn("TID size: " + ph.nextTID);
Arrays.fill(offsets, (short)-1);
final int dlen = ph.getDataLength();
for(short pos = 0; pos < dlen; ) {
final short tid = ByteConversion.byteToShort(data, pos);
if (tid < 0) {
LOG.error("Invalid tid found: " + tid + "; ignoring rest of page ...");
ph.setDataLength(pos);
return;
}
if(tid >= offsets.length) {
LOG.error("Problematic tid found: " + tid + "; trying to recover ...");
short[] t = new short[tid + 1];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = (short)(tid + 1);
}
offsets[tid] = (short)(pos + 2);
pos += ByteConversion.byteToInt(data, pos + 2) + 6;
}
}
@Override
public short getNextTID() {
for(short i = 0; i < offsets.length; i++) {
if(offsets[i] == -1) {
return i;
}
}
final short tid = (short)offsets.length;
short next = (short)(ph.nextTID * 2);
if(next < 0 || next < ph.nextTID) {
return -1;
}
short[] t = new short[next];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = next;
return tid;
}
public void adjustTID(short tid) {
if (tid >= ph.nextTID) {
short next = (short)(tid * 2);
short[] t = new short[next];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = next;
}
}
public void clear() {
Arrays.fill(data, (byte) 0);
}
private String printContents() {
final StringBuilder buf = new StringBuilder();
for(short i = 0; i < offsets.length; i++) {
if (offsets[i] > -1) {
buf.append('[').append(i).append(", ").append(offsets[i]);
final short len = ByteConversion.byteToShort(data, offsets[i]);
buf.append(", ").append(len).append(']');
}
}
return buf.toString();
}
@Override
public void setOffset(short tid, int offset) {
if (offsets == null) {
LOG.warn("page: " + page.getPageNum() + " file: " + getFile().getName() + " status: " +
getPageHeader().getStatus());
throw new RuntimeException("page offsets not initialized");
}
offsets[tid] = (short)offset;
}
@Override
public void removeTID(short tid, int length) throws IOException {
final int offset = offsets[tid] - 2;
offsets[tid] = -1;
for(short i = 0; i < offsets.length; i++) {
if(offsets[i] > offset)
{offsets[i] -= length;}
}
//readOffsets(start);
}
@Override
public void delete() throws IOException {
// reset page header fields
ph.setDataLength(0);
ph.setNextInChain(-1L);
ph.setLastInChain(-1L);
ph.setTID((short) -1);
ph.setRecordCount((short) 0);
setReferenceCount(0);
ph.setDirty(true);
unlinkPages(page);
}
@Override
public SinglePage getFirstPage() {
return this;
}
@Override
public byte[] getData() {
return data;
}
@Override
public BFilePageHeader getPageHeader() {
return ph;
}
@Override
public String getPageInfo() {
return page.getPageInfo();
}
@Override
public long getPageNum() {
return page.getPageNum();
}
@Override
public void setData(byte[] buf) {
data = buf;
}
@Override
public void write() throws IOException {
//LOG.debug(getFile().getName() + " writing page " + getPageNum());
writeValue(page, new Value(data));
setDirty(false);
}
}
}
|
src/org/exist/storage/index/BFile.java
|
/*
* eXist Open Source Native XML Database Copyright (C) 2001-06 Wolfgang M. Meier
* wolfgang@exist-db.org http://exist.sourceforge.net
*
* This program 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 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import org.apache.log4j.Logger;
import org.exist.storage.BrokerPool;
import org.exist.storage.BufferStats;
import org.exist.storage.CacheManager;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.NativeBroker;
import org.exist.storage.StorageAddress;
import org.exist.storage.btree.BTree;
import org.exist.storage.btree.BTreeCallback;
import org.exist.storage.btree.BTreeException;
import org.exist.storage.btree.DBException;
import org.exist.storage.btree.IndexQuery;
import org.exist.storage.btree.Value;
import org.exist.storage.cache.Cache;
import org.exist.storage.cache.Cacheable;
import org.exist.storage.cache.LRUCache;
import org.exist.storage.io.VariableByteArrayInput;
import org.exist.storage.io.VariableByteInput;
import org.exist.storage.io.VariableByteOutputStream;
import org.exist.storage.journal.LogEntryTypes;
import org.exist.storage.journal.Loggable;
import org.exist.storage.journal.Lsn;
import org.exist.storage.lock.Lock;
import org.exist.storage.lock.ReentrantReadWriteLock;
import org.exist.storage.txn.TransactionException;
import org.exist.storage.txn.Txn;
import org.exist.util.ByteArray;
import org.exist.util.ByteConversion;
import org.exist.util.FixedByteArray;
import org.exist.util.IndexCallback;
import org.exist.util.LockException;
import org.exist.util.ReadOnlyException;
import org.exist.util.sanity.SanityCheck;
import org.exist.xquery.Constants;
import org.exist.xquery.TerminatedException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Data store for variable size values.
*
* This class maps keys to values of variable size. Keys are stored in the
* b+-tree. B+-tree values are pointers to the logical storage address of the
* value in the data section. The pointer consists of the page number and a
* logical tuple identifier.
*
* If a value is larger than the internal page size (4K), it is split into
* overflow pages. Appending data to a overflow page is very fast. Only the
* first and the last data page are loaded.
*
* Data pages are buffered.
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
*/
public class BFile extends BTree {
protected final static Logger LOGSTATS = Logger.getLogger( NativeBroker.EXIST_STATISTICS_LOGGER );
public final static short FILE_FORMAT_VERSION_ID = 13;
public final static long UNKNOWN_ADDRESS = -1;
public final static long DATA_SYNC_PERIOD = 15000;
// minimum free space a page should have to be
// considered for reusing
public final static int PAGE_MIN_FREE = 64;
// page signatures
public final static byte RECORD = 20;
public final static byte LOB = 21;
public final static byte FREE_LIST = 22;
public final static byte MULTI_PAGE = 23;
public static final int LENGTH_RECORDS_COUNT = 2; //sizeof short
public static final int LENGTH_NEXT_TID = 2; //sizeof short
/*
* Byte ids for the records written to the log file.
*/
public final static byte LOG_CREATE_PAGE = 0x30;
public final static byte LOG_STORE_VALUE = 0x31;
public final static byte LOG_REMOVE_VALUE = 0x32;
public final static byte LOG_REMOVE_PAGE = 0x33;
public final static byte LOG_OVERFLOW_APPEND = 0x34;
public final static byte LOG_OVERFLOW_STORE = 0x35;
public final static byte LOG_OVERFLOW_CREATE = 0x36;
public final static byte LOG_OVERFLOW_MODIFIED = 0x37;
public final static byte LOG_OVERFLOW_CREATE_PAGE = 0x38;
public final static byte LOG_OVERFLOW_REMOVE = 0x39;
static {
// register log entry types for this db file
LogEntryTypes.addEntryType(LOG_CREATE_PAGE, CreatePageLoggable.class);
LogEntryTypes.addEntryType(LOG_STORE_VALUE, StoreValueLoggable.class);
LogEntryTypes.addEntryType(LOG_REMOVE_VALUE, RemoveValueLoggable.class);
LogEntryTypes.addEntryType(LOG_REMOVE_PAGE, RemoveEmptyPageLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_APPEND, OverflowAppendLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_STORE, OverflowStoreLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_CREATE, OverflowCreateLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_MODIFIED, OverflowModifiedLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_CREATE_PAGE, OverflowCreatePageLoggable.class);
LogEntryTypes.addEntryType(LOG_OVERFLOW_REMOVE, OverflowRemoveLoggable.class);
}
protected BFileHeader fileHeader;
protected int minFree;
protected Cache dataCache = null;
protected Lock lock = null;
public int fixedKeyLen = -1;
protected int maxValueSize;
public BFile(BrokerPool pool, byte fileId, boolean transactional, File file, DefaultCacheManager cacheManager,
double cacheGrowth, double thresholdBTree, double thresholdData) throws DBException {
super(pool, fileId, transactional, cacheManager, file, thresholdBTree);
fileHeader = (BFileHeader) getFileHeader();
dataCache = new LRUCache(64, cacheGrowth, thresholdData, CacheManager.DATA_CACHE);
dataCache.setFileName(file.getName());
cacheManager.registerCache(dataCache);
minFree = PAGE_MIN_FREE;
lock = new ReentrantReadWriteLock(file.getName());
maxValueSize = fileHeader.getWorkSize() / 2;
if(exists()) {
open();
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating data file: " + getFile().getName());
}
create();
}
}
/**
* @return file version
*/
@Override
public short getFileVersion() {
return FILE_FORMAT_VERSION_ID;
}
/**
* Returns the Lock object responsible for this BFile.
*
* @return Lock
*/
public Lock getLock() {
return lock;
}
protected long getDataSyncPeriod() {
return DATA_SYNC_PERIOD;
}
/**
* Append the given data fragment to the value associated
* with the key. A new entry is created if the key does not
* yet exist in the database.
*
* @param key
* @param value
* @throws ReadOnlyException
* @throws IOException
*/
public long append(Value key, ByteArray value)
throws ReadOnlyException, IOException {
return append(null, key, value);
}
public long append(Txn transaction, Value key, ByteArray value) throws IOException {
if (key == null) {
LOG.debug("key is null");
return UNKNOWN_ADDRESS;
}
if (key.getLength() > fileHeader.getMaxKeySize()) {
//TODO : throw an exception ? -pb
LOG.warn("Key length exceeds page size! Skipping key ...");
return UNKNOWN_ADDRESS;
}
try {
// check if key exists already
long p = findValue(key);
if (p == KEY_NOT_FOUND) {
// key does not exist:
p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
}
// key exists: get old data
final long pnum = StorageAddress.pageFromPointer(p);
final short tid = StorageAddress.tidFromPointer(p);
final DataPage page = getDataPage(pnum);
if (page instanceof OverflowPage)
{((OverflowPage) page).append(transaction, value);}
else {
final int valueLen = value.size();
final byte[] data = page.getData();
final int offset = page.findValuePosition(tid);
if (offset < 0)
{throw new IOException("tid " + tid + " not found on page " + pnum);}
if (offset + 4 > data.length) {
LOG.error("found invalid pointer in file " + getFile().getName() +
" for page" + page.getPageInfo() + " : " +
"tid = " + tid + "; offset = " + offset);
return UNKNOWN_ADDRESS;
}
final int l = ByteConversion.byteToInt(data, offset);
//TOUNDERSTAND : unless l can be negative, we should never get there -pb
if (offset + 4 + l > data.length) {
LOG.error("found invalid data record in file " + getFile().getName() +
" for page" + page.getPageInfo() + " : " +
"length = " + data.length + "; required = " + (offset + 4 + l));
return UNKNOWN_ADDRESS;
}
final byte[] newData = new byte[l + valueLen];
System.arraycopy(data, offset + 4, newData, 0, l);
value.copyTo(newData, l);
p = update(transaction, p, page, key, new FixedByteArray(newData, 0, newData.length));
}
return p;
} catch (final BTreeException bte) {
LOG.warn("btree exception while appending value", bte);
}
return UNKNOWN_ADDRESS;
}
/**
* Close the BFile.
*
* @throws DBException
* @return always true
*/
@Override
public boolean close() throws DBException {
super.close();
return true;
}
/**
* Check, if key is contained in BFile.
*
* @param key key to look for
* @return true, if key exists
*/
public boolean containsKey(Value key) {
try {
return findValue(key) != KEY_NOT_FOUND;
} catch (final BTreeException e) {
LOG.warn(e.getMessage());
} catch (final IOException e) {
LOG.warn(e.getMessage());
}
return false;
}
@Override
public boolean create() throws DBException {
if (super.create((short) fixedKeyLen)) {
return true;
}
return false;
}
@Override
public void closeAndRemove() {
super.closeAndRemove();
cacheManager.deregisterCache(dataCache);
}
private SinglePage createDataPage() {
try {
final SinglePage page = new SinglePage();
dataCache.add(page, 2);
return page;
} catch (final IOException ioe) {
LOG.warn(ioe);
return null;
}
}
@Override
public FileHeader createFileHeader(int pageSize) {
return new BFileHeader(pageSize);
}
@Override
public PageHeader createPageHeader() {
return new BFilePageHeader();
}
/**
* Remove all entries matching the given query.
*
* @param query
* @throws IOException
* @throws BTreeException
*/
public void removeAll(Txn transaction, IndexQuery query) throws IOException, BTreeException {
// first collect the values to remove, then sort them by their page number
// and remove them.
try {
final RemoveCallback cb = new RemoveCallback();
remove(transaction, query, cb);
LOG.debug("Found " + cb.count + " items to remove.");
if (cb.count == 0)
{return;}
Arrays.sort(cb.pointers, 0, cb.count - 1);
for (int i = 0; i < cb.count; i++) {
remove(transaction, cb.pointers[i]);
}
} catch (final TerminatedException e) {
// Should never happen during remove
LOG.warn("removeAll() - method has been terminated.");
}
}
private class RemoveCallback implements BTreeCallback {
long[] pointers = new long[128];
int count = 0;
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
if (count == pointers.length) {
long[] np = new long[count * 2];
System.arraycopy(pointers, 0, np, 0, count);
pointers = np;
}
pointers[count++] = pointer;
return true;
}
}
public ArrayList<Value> findEntries(IndexQuery query) throws IOException,
BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(FindCallback.BOTH);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> findKeys(IndexQuery query)
throws IOException, BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(FindCallback.KEYS);
query(query, cb);
return cb.getValues();
}
public void find(IndexQuery query, IndexCallback callback)
throws IOException, BTreeException, TerminatedException {
final FindCallback cb = new FindCallback(callback);
query(query, cb);
}
/* Flushes {@link org.exist.storage.btree.Paged#flush()dirty data} to the disk and cleans up the cache.
* @return <code>true</code> if something has actually been cleaned
*/
@Override
public boolean flush() throws DBException {
boolean flushed = false;
//TODO : consider log operation as a flush ?
if (isTransactional)
{logManager.flushToLog(true);}
flushed = flushed | dataCache.flush();
flushed = flushed | super.flush();
return flushed;
}
public BufferStats getDataBufferStats() {
if (dataCache == null)
{return null;}
return new BufferStats(dataCache.getBuffers(), dataCache.getUsedBuffers(),
dataCache.getHits(), dataCache.getFails());
}
@Override
public void printStatistics() {
super.printStatistics();
final NumberFormat nf = NumberFormat.getPercentInstance();
final StringBuilder buf = new StringBuilder();
buf.append(getFile().getName()).append(" DATA ");
buf.append("Buffers occupation : ");
if (dataCache.getBuffers() == 0 && dataCache.getUsedBuffers() == 0)
{buf.append("N/A");}
else
{buf.append(nf.format(dataCache.getUsedBuffers()/(float)dataCache.getBuffers()));}
buf.append(" (" + dataCache.getUsedBuffers() + " out of " + dataCache.getBuffers() + ")");
//buf.append(dataCache.getBuffers()).append(" / ");
//buf.append(dataCache.getUsedBuffers()).append(" / ");
buf.append(" Cache efficiency : ");
if (dataCache.getHits() == 0 && dataCache.getFails() == 0)
{buf.append("N/A");}
else
{buf.append(nf.format(dataCache.getHits()/(float)(dataCache.getHits() + dataCache.getFails())));}
//buf.append(dataCache.getHits()).append(" / ");
//buf.append(dataCache.getFails());
LOGSTATS.info(buf.toString());
}
/**
* Get the value data associated with the specified key
* or null if the key could not be found.
*
* @param key
*/
public Value get(Value key) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return null;}
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
return get(page, p);
} catch (final BTreeException e) {
LOG.warn("An exception occurred while trying to retrieve key " + key + ": " + e.getMessage(), e);
} catch (final IOException e) {
LOG.warn(e.getMessage(), e);
}
return null;
}
/**
* Get the value data for the given key as a variable byte
* encoded input stream.
*
* @param key
* @throws IOException
*/
public VariableByteInput getAsStream(Value key) throws IOException {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return null;}
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
switch (page.getPageHeader().getStatus()) {
case MULTI_PAGE:
return ((OverflowPage) page).getDataStream(p);
default:
return getAsStream(page, p);
}
} catch (final BTreeException e) {
LOG.warn("An exception occurred while trying to retrieve key " + key + ": " + e.getMessage(), e);
}
return null;
}
/**
* Get the value located at the specified address as a
* variable byte encoded input stream.
*
* @param pointer
* @throws IOException
*/
public VariableByteInput getAsStream(long pointer) throws IOException {
final DataPage page = getDataPage(StorageAddress.pageFromPointer(pointer));
switch (page.getPageHeader().getStatus()) {
case MULTI_PAGE:
return ((OverflowPage) page).getDataStream(pointer);
default:
return getAsStream(page, pointer);
}
}
private VariableByteInput getAsStream(DataPage page, long pointer) throws IOException {
dataCache.add(page.getFirstPage(), 2);
final short tid = StorageAddress.tidFromPointer(pointer);
final int offset = page.findValuePosition(tid);
if (offset < 0)
{throw new IOException("no data found at tid " + tid + "; page " + page.getPageNum());}
final byte[] data = page.getData();
final int l = ByteConversion.byteToInt(data, offset);
final SimplePageInput input = new SimplePageInput(data, offset + 4, l, pointer);
return input;
}
/**
* Returns the value located at the specified address.
*
* @param p
* @return value located at the specified address
*/
public Value get(long p) {
try {
final long pnum = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pnum);
return get(page, p);
} catch (final IOException e) {
LOG.debug(e);
}
return null;
}
/**
* Retrieve value at logical address p from page
*/
protected Value get(DataPage page, long p) throws IOException {
final short tid = StorageAddress.tidFromPointer(p);
final int offset = page.findValuePosition(tid);
final byte[] data = page.getData();
if (offset < 0 || offset > data.length) {
LOG.error("wrong pointer (tid: " + tid + page.getPageInfo()
+ ") in file " + getFile().getName() + "; offset = "
+ offset);
return null;
}
final int l = ByteConversion.byteToInt(data, offset);
if (l + 6 > data.length) {
LOG.error(getFile().getName() + " wrong data length in page "
+ page.getPageNum() + ": expected=" + (l + 6) + "; found="
+ data.length);
return null;
}
dataCache.add(page.getFirstPage());
final Value v = new Value(data, offset + 4, l);
v.setAddress(p);
return v;
}
private DataPage getDataPage(long pos) throws IOException {
return getDataPage(pos, true);
}
private DataPage getDataPage(long pos, boolean initialize) throws IOException {
final DataPage wp = (DataPage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
if (page == null) {
LOG.debug("page " + pos + " not found!");
return null;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() == MULTI_PAGE)
{return new OverflowPage(page, data);}
return new SinglePage(page, data, initialize);
} else if (wp.getPageHeader().getStatus() == MULTI_PAGE)
{return new OverflowPage(wp);}
else
{return wp;}
}
private SinglePage getSinglePage(long pos) throws IOException {
final SinglePage wp = (SinglePage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
if (page == null) {
LOG.debug("page " + pos + " not found!");
return null;
}
final byte[] data = page.read();
return new SinglePage(page, data, false);
}
return wp;
}
public ArrayList<Value> getEntries() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.BOTH);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> getKeys() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.KEYS);
query(query, cb);
return cb.getValues();
}
public ArrayList<Value> getValues() throws IOException, BTreeException, TerminatedException {
final IndexQuery query = new IndexQuery(IndexQuery.ANY, "");
final FindCallback cb = new FindCallback(FindCallback.VALUES);
query(query, cb);
return cb.getValues();
}
public boolean open() throws DBException {
return super.open(FILE_FORMAT_VERSION_ID);
}
/**
* Put data under given key.
*
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @see BFile#put(Value,byte[],boolean)
* @param key
* @param data the data (value) to update
* @param overwrite overwrite if set to true, value will be overwritten if it already exists
* @throws ReadOnlyException
*/
public long put(Value key, byte[] data, boolean overwrite) throws ReadOnlyException {
return put(null, key, data, overwrite);
}
public long put(Txn transaction, Value key, byte[] data, boolean overwrite)
/* throws ReadOnlyException */ {
SanityCheck.THROW_ASSERT(key.getLength() <= fileHeader.getWorkSize(), "Key length exceeds page size!");
final FixedByteArray buf = new FixedByteArray(data, 0, data.length);
return put(transaction, key, buf, overwrite);
}
/**
* Convenience method for {@link BFile#put(Value, byte[], boolean)}, overwrite is true.
*
* @param key with which the data is updated
* @param value value to update
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @throws ReadOnlyException
*/
public long put(Value key, ByteArray value) throws ReadOnlyException {
return put(key, value, true);
}
/**
* Put a value under given key. The difference of this
* method and {@link BFile#append(Value, ByteArray)} is,
* that the value gets updated and not stored.
*
* @param key with which the data is updated
* @param value value to update
* @param overwrite if set to true, value will be overwritten if it already exists
* @return on success the address of the stored value, else UNKNOWN_ADDRESS
* @throws ReadOnlyException
*/
public long put(Value key, ByteArray value, boolean overwrite) throws ReadOnlyException {
return put(null, key, value, overwrite);
}
public long put(Txn transaction, Value key, ByteArray value, boolean overwrite) {
if (key == null) {
LOG.debug("key is null");
return UNKNOWN_ADDRESS;
}
if (key.getLength() > fileHeader.getWorkSize()) {
//TODO : exception ? -pb
LOG.warn("Key length exceeds page size! Skipping key ...");
return UNKNOWN_ADDRESS;
}
try {
try {
// check if key exists already
//TODO : rely on a KEY_NOT_FOUND (or maybe VALUE_NOT_FOUND) result ! -pb
long p = findValue(key);
if (p == KEY_NOT_FOUND) {
// key does not exist:
p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
}
// if exists, update value
if (overwrite) {
return update(transaction, p, key, value);
}
//TODO : throw an exception ? -pb
return UNKNOWN_ADDRESS;
//TODO : why catch an exception here ??? It costs too much ! -pb
} catch (final BTreeException bte) {
// key does not exist:
final long p = storeValue(transaction, value);
addValue(transaction, key, p);
return p;
} catch (final IOException ioe) {
ioe.printStackTrace();
LOG.warn(ioe);
return UNKNOWN_ADDRESS;
}
} catch (final IOException e) {
e.printStackTrace();
LOG.warn(e);
return UNKNOWN_ADDRESS;
} catch (final BTreeException bte) {
bte.printStackTrace();
LOG.warn(bte);
return UNKNOWN_ADDRESS;
}
}
public void remove(Value key) {
remove(null, key);
}
public void remove(Txn transaction, Value key) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return;}
final long pos = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pos);
remove(transaction, page, p);
removeValue(transaction, key);
} catch (final BTreeException bte) {
LOG.debug(bte);
} catch (final IOException ioe) {
LOG.debug(ioe);
}
}
public void remove(Txn transaction, long p) {
try {
final long pos = StorageAddress.pageFromPointer(p);
final DataPage page = getDataPage(pos);
remove(transaction, page, p);
} catch (final IOException e) {
LOG.debug("io problem", e);
}
}
private void remove(Txn transaction, DataPage page, long p) throws IOException {
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
// overflow page: simply delete the whole page
((OverflowPage)page).delete(transaction);
return;
}
final short tid = StorageAddress.tidFromPointer(p);
final int offset = page.findValuePosition(tid);
final byte[] data = page.getData();
if (offset > data.length || offset < 0) {
LOG.error("wrong pointer (tid: " + tid + ", " + page.getPageInfo() + ")");
return;
}
final int l = ByteConversion.byteToInt(data, offset);
if (isTransactional && transaction != null) {
final Loggable loggable = new RemoveValueLoggable(transaction, fileId, page.getPageNum(), tid, data, offset + 4, l);
writeToLog(loggable, page);
}
final BFilePageHeader ph = page.getPageHeader();
final int end = offset + 4 + l;
int len = ph.getDataLength();
// remove old value
System.arraycopy(data, end, data, offset - 2, len - end);
ph.setDirty(true);
ph.decRecordCount();
len = len - l - 6;
ph.setDataLength(len);
page.setDirty(true);
// if this page is empty, remove it
if (len == 0) {
if (isTransactional && transaction != null) {
final Loggable loggable = new RemoveEmptyPageLoggable(transaction, fileId, page.getPageNum());
writeToLog(loggable, page);
}
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(page.getPageNum()));
dataCache.remove(page);
page.delete();
} else {
page.removeTID(tid, l + 6);
// adjust free space data
final int newFree = fileHeader.getWorkSize() - len;
if (newFree > minFree) {
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null) {
free = new FreeSpace(page.getPageNum(), newFree);
fileHeader.addFreeSpace(free);
} else {
free.setFree(newFree);
}
}
dataCache.add(page, 2);
}
}
private final void saveFreeSpace(FreeSpace space, DataPage page) {
final int free = fileHeader.getWorkSize() - page.getPageHeader().getDataLength();
space.setFree(free);
if(free < minFree)
{fileHeader.removeFreeSpace(space);}
}
public void setLocation(String location) throws DBException {
setFile(new File(location + ".dbx"));
}
public long storeValue(Txn transaction, ByteArray value) throws IOException {
final int vlen = value.size();
// does value fit into a single page?
if (6 + vlen > maxValueSize) {
final OverflowPage page = new OverflowPage(transaction);
final byte[] data = new byte[vlen + 6];
page.getPageHeader().setDataLength(vlen + 6);
ByteConversion.shortToByte((short) 1, data, 0);
ByteConversion.intToByte(vlen, data, 2);
//System.arraycopy(value, 0, data, 6, vlen);
value.copyTo(data, 6);
page.setData(transaction, data);
page.setDirty(true);
//dataCache.add(page);
return StorageAddress.createPointer((int) page.getPageNum(),
(short) 1);
}
DataPage page = null;
short tid = -1;
FreeSpace free = null;
int realSpace = 0;
// check for available tid
while (tid < 0) {
free = fileHeader.findFreeSpace(vlen + 6);
if (free == null) {
page = createDataPage();
if (isTransactional && transaction != null) {
final Loggable loggable = new CreatePageLoggable(transaction, fileId, page.getPageNum());
writeToLog(loggable, page);
}
page.setData(new byte[fileHeader.getWorkSize()]);
free = new FreeSpace(page.getPageNum(),
fileHeader.getWorkSize() - page.getPageHeader().getDataLength());
fileHeader.addFreeSpace(free);
} else {
page = getDataPage(free.getPage());
// check if this is really a data page
if (page.getPageHeader().getStatus() != BFile.RECORD) {
LOG.warn("page " + page.getPageNum()
+ " is not a data page; removing it");
fileHeader.removeFreeSpace(free);
continue;
}
// check if the information about free space is really correct
realSpace = fileHeader.getWorkSize() - page.getPageHeader().getDataLength();
if (realSpace < 6 + vlen) {
// not correct: adjust and continue
LOG.warn("Wrong data length in list of free pages: adjusting to " + realSpace);
free.setFree(realSpace);
continue;
}
}
tid = page.getNextTID();
if (tid < 0) {
LOG.info("removing page " + page.getPageNum() + " from free pages");
fileHeader.removeFreeSpace(free);
}
}
if (isTransactional && transaction != null) {
final Loggable loggable = new StoreValueLoggable(transaction, fileId, page.getPageNum(), tid, value);
writeToLog(loggable, page);
}
int len = page.getPageHeader().getDataLength();
final byte[] data = page.getData();
// save tid
ByteConversion.shortToByte(tid, data, len);
len += 2;
page.setOffset(tid, len);
// save data length
ByteConversion.intToByte(vlen, data, len);
len += 4;
// save data
value.copyTo(data, len);
len += vlen;
page.getPageHeader().setDataLength(len);
page.getPageHeader().incRecordCount();
saveFreeSpace(free, page);
page.setDirty(true);
dataCache.add(page);
// return pointer from pageNum and offset into page
return StorageAddress.createPointer((int) page.getPageNum(), tid);
}
/**
* Update a key/value pair.
*
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public long update(Value key, ByteArray value) {
try {
final long p = findValue(key);
if (p == KEY_NOT_FOUND) {return UNKNOWN_ADDRESS;}
return update(p, key, value);
} catch (final BTreeException bte) {
LOG.debug(bte);
} catch (final IOException ioe) {
LOG.debug(ioe);
}
return UNKNOWN_ADDRESS;
}
/**
* Update the key/value pair found at the logical address p.
*
* @param p
* Description of the Parameter
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public long update(long p, Value key, ByteArray value) {
return update(null, p, key, value);
}
public long update(Txn transaction, long p, Value key, ByteArray value) {
try {
return update(transaction, p, getDataPage(StorageAddress.pageFromPointer(p)),
key, value);
} catch (final BTreeException bte) {
LOG.debug(bte);
return UNKNOWN_ADDRESS;
} catch (final IOException ioe) {
LOG.warn(ioe.getMessage(), ioe);
return UNKNOWN_ADDRESS;
}
}
/**
* Update the key/value pair with logical address p and stored in page.
*
* @param p
* Description of the Parameter
* @param page
* Description of the Parameter
* @param key
* Description of the Parameter
* @param value
* Description of the Parameter
* @exception BTreeException
* Description of the Exception
* @exception IOException
* Description of the Exception
*/
protected long update(Txn transaction, long p, DataPage page, Value key, ByteArray value)
throws BTreeException, IOException {
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
final int valueLen = value.size();
// does value fit into a single page?
if (valueLen + 6 < maxValueSize) {
// yes: remove the overflow page
remove(transaction, page, p);
final long np = storeValue(transaction, value);
addValue(transaction, key, np);
return np;
}
// this is an overflow page: simply replace the value
final byte[] data = new byte[valueLen + 6];
// save tid
ByteConversion.shortToByte((short) 1, data, 0);
// save length
ByteConversion.intToByte(valueLen, data, 2);
// save data
value.copyTo(data, 6);
((OverflowPage)page).setData(transaction, data);
return p;
}
remove(transaction, page, p);
final long np = storeValue(transaction, value);
addValue(transaction, key, np);
return np;
}
public void debugFreeList() {
fileHeader.debugFreeList();
}
/* ---------------------------------------------------------------------------------
* Methods used by recovery and transaction management
* --------------------------------------------------------------------------------- */
/**
* Write loggable to the journal and update the LSN in the page header.
*/
private void writeToLog(Loggable loggable, DataPage page) {
try {
logManager.writeToLog(loggable);
page.getPageHeader().setLsn(loggable.getLsn());
} catch (final TransactionException e) {
LOG.warn(e.getMessage(), e);
}
}
private SinglePage getSinglePageForRedo(Loggable loggable, long pos) throws IOException {
final SinglePage wp = (SinglePage) dataCache.get(pos);
if (wp == null) {
final Page page = getPage(pos);
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD)
{return null;}
if (loggable != null && isUptodate(page, loggable))
{return null;}
return new SinglePage(page, data, true);
}
return wp;
}
private boolean isUptodate(Page page, Loggable loggable) {
return page.getPageHeader().getLsn() >= loggable.getLsn();
}
private boolean requiresRedo(Loggable loggable, DataPage page) {
return loggable.getLsn() > page.getPageHeader().getLsn();
}
protected void redoStoreValue(StoreValueLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.page);
if (page != null && requiresRedo(loggable, page)) {
storeValueHelper(loggable, loggable.tid, loggable.value, page);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage());
}
}
protected void undoStoreValue(StoreValueLoggable loggable) {
try {
final SinglePage page = (SinglePage) getDataPage(loggable.page);
removeValueHelper(null, loggable.tid, page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoCreatePage(CreatePageLoggable loggable) {
createPageHelper(loggable, loggable.newPage);
}
protected void undoCreatePage(CreatePageLoggable loggable) {
try {
final SinglePage page = (SinglePage) getDataPage(loggable.newPage);
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(page.getPageNum()));
dataCache.remove(page);
page.delete();
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoRemoveValue(RemoveValueLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.page);
if (wp == null) {
final Page page = getPage(loggable.page);
if (page == null) {
LOG.warn("page " + loggable.page + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable)) {
// page is obviously deleted later
return;
}
wp = new SinglePage(page, data, true);
}
if (wp.ph.getLsn() != Page.NO_PAGE && requiresRedo(loggable, wp)) {
removeValueHelper(loggable, loggable.tid, wp);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemoveValue(RemoveValueLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.page);
final FixedByteArray data = new FixedByteArray(loggable.oldData);
storeValueHelper(null, loggable.tid, data, page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoRemovePage(RemoveEmptyPageLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.page);
if (wp == null) {
final Page page = getPage(loggable.page);
if (page == null) {
LOG.warn("page " + loggable.page + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable)) {
return;
}
wp = new SinglePage(page, data, false);
}
if (wp.getPageHeader().getLsn() == Lsn.LSN_INVALID || requiresRedo(loggable, wp)) {
fileHeader.removeFreeSpace(fileHeader.getFreeSpace(wp.getPageNum()));
dataCache.remove(wp);
wp.delete();
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemovePage(RemoveEmptyPageLoggable loggable) {
createPageHelper(loggable, loggable.page);
}
protected void redoCreateOverflow(OverflowCreateLoggable loggable) {
try {
DataPage firstPage = (DataPage) dataCache.get(loggable.pageNum);
if (firstPage == null) {
final Page page = getPage(loggable.pageNum);
byte[] data = page.read();
if (page.getPageHeader().getLsn() == Lsn.LSN_INVALID || requiresRedo(loggable, page)) {
reuseDeleted(page);
final BFilePageHeader ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(MULTI_PAGE);
ph.setNextInChain(0L);
ph.setLastInChain(0L);
ph.setDataLength(0);
ph.nextTID = 32;
data = new byte[fileHeader.getWorkSize()];
firstPage = new SinglePage(page, data, true);
firstPage.setDirty(true);
} else
{firstPage = new SinglePage(page, data, false);}
}
if (firstPage.getPageHeader().getLsn() != Page.NO_PAGE && requiresRedo(loggable, firstPage)) {
firstPage.getPageHeader().setLsn(loggable.getLsn());
firstPage.setDirty(true);
}
dataCache.add(firstPage);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoCreateOverflow(OverflowCreateLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
dataCache.remove(page);
page.delete();
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoCreateOverflowPage(OverflowCreatePageLoggable loggable) {
createPageHelper(loggable, loggable.newPage);
if (loggable.prevPage != Page.NO_PAGE) {
try {
final SinglePage page = getSinglePageForRedo(null, loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(loggable.newPage);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
}
protected void undoCreateOverflowPage(OverflowCreatePageLoggable loggable) {
try {
SinglePage page = getSinglePage(loggable.newPage);
dataCache.remove(page);
page.delete();
if (loggable.prevPage != Page.NO_PAGE) {
try {
page = getSinglePage(loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(0);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoAppendOverflow(OverflowAppendLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
loggable.data.copyTo(0, page.getData(), ph.getDataLength(), loggable.chunkSize);
ph.setDataLength(ph.getDataLength() + loggable.chunkSize);
ph.setLsn(loggable.getLsn());
page.setDirty(true);
dataCache.add(page);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoAppendOverflow(OverflowAppendLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(ph.getDataLength() - loggable.chunkSize);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoStoreOverflow(OverflowStoreLoggable loggable) {
try {
SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
try {
System.arraycopy(loggable.data, 0, page.getData(), 0, loggable.size);
} catch (final ArrayIndexOutOfBoundsException e) {
LOG.warn(loggable.data.length + "; " + page.getData().length + "; " + ph.getDataLength() + "; " + loggable.size);
throw e;
}
ph.setDataLength(loggable.size);
ph.setNextInChain(0);
ph.setLsn(loggable.getLsn());
page.setDirty(true);
dataCache.add(page);
if (loggable.prevPage != Page.NO_PAGE) {
page = getSinglePage(loggable.prevPage);
SanityCheck.ASSERT(page != null, "Previous page is null");
page.getPageHeader().setNextInChain(loggable.pageNum);
page.setDirty(true);
dataCache.add(page);
}
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void redoModifiedOverflow(OverflowModifiedLoggable loggable) {
try {
final SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum);
if (page != null && requiresRedo(loggable, page)) {
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(loggable.length);
ph.setLastInChain(loggable.lastInChain);
// adjust length field in first page
ByteConversion.intToByte(ph.getDataLength() - 6, page.getData(), 2);
page.setDirty(true);
// keep the first page in cache
dataCache.add(page, 2);
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoModifiedOverflow(OverflowModifiedLoggable loggable) {
try {
final SinglePage page = getSinglePage(loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setDataLength(loggable.oldLength);
// adjust length field in first page
ByteConversion.intToByte(ph.getDataLength() - 6, page.getData(), 2);
page.setDirty(true);
dataCache.add(page);
} catch (final IOException e) {
LOG.warn("An IOException occurred during undo: " + e.getMessage(), e);
}
}
protected void redoRemoveOverflow(OverflowRemoveLoggable loggable) {
try {
SinglePage wp = (SinglePage) dataCache.get(loggable.pageNum);
if (wp == null) {
final Page page = getPage(loggable.pageNum);
if (page == null) {
LOG.warn("page " + loggable.pageNum + " not found!");
return;
}
final byte[] data = page.read();
if (page.getPageHeader().getStatus() < RECORD || isUptodate(page, loggable))
{return;}
wp = new SinglePage(page, data, true);
}
if (requiresRedo(loggable, wp)) {
wp.setDirty(true);
dataCache.remove(wp);
wp.delete();
}
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
}
protected void undoRemoveOverflow(OverflowRemoveLoggable loggable) {
final DataPage page = createPageHelper(loggable, loggable.pageNum);
final BFilePageHeader ph = page.getPageHeader();
ph.setStatus(loggable.status);
ph.setDataLength(loggable.length);
ph.setNextInChain(loggable.nextInChain);
page.setData(loggable.data);
page.setDirty(true);
dataCache.add(page);
}
private void storeValueHelper(Loggable loggable, short tid, ByteArray value, SinglePage page) {
int len = page.ph.getDataLength();
// save tid
ByteConversion.shortToByte(tid, page.data, len);
len += 2;
page.adjustTID(tid);
page.setOffset(tid, len);
// save data length
ByteConversion.intToByte(value.size(), page.data, len);
len += 4;
// save data
try {
value.copyTo(page.data, len);
} catch (final RuntimeException e) {
LOG.warn(getFile().getName() + ": storage error in page: " + page.getPageNum() +
"; len: " + len + " ; value: " + value.size() + "; max: " + fileHeader.getWorkSize() +
"; status: " + page.ph.getStatus());
LOG.debug(page.printContents());
throw e;
}
len += value.size();
page.ph.setDataLength(len);
page.ph.incRecordCount();
if (loggable != null)
{page.ph.setLsn(loggable.getLsn());}
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null)
{free = new FreeSpace(page.getPageNum(), fileHeader.getWorkSize() - len);}
saveFreeSpace(free, page);
page.setDirty(true);
dataCache.add(page);
}
private void removeValueHelper(Loggable loggable, short tid, SinglePage page) throws IOException {
final int offset = page.findValuePosition(tid);
if (offset < 0) {
LOG.warn("TID: " + tid + " not found on page: " + page.getPageNum());
return;
}
final int l = ByteConversion.byteToInt(page.data, offset);
final int end = offset + 4 + l;
int len = page.ph.getDataLength();
// remove old value
System.arraycopy(page.data, end, page.data, offset - 2, len - end);
page.ph.setDirty(true);
page.ph.decRecordCount();
len = len - l - 6;
page.ph.setDataLength(len);
if (loggable != null)
{page.ph.setLsn(loggable.getLsn());}
page.setDirty(true);
if (len > 0) {
page.removeTID(tid, l + 6);
// adjust free space data
final int newFree = fileHeader.getWorkSize() - len;
if (newFree > minFree) {
FreeSpace free = fileHeader.getFreeSpace(page.getPageNum());
if (free == null) {
free = new FreeSpace(page.getPageNum(), newFree);
fileHeader.addFreeSpace(free);
} else {
free.setFree(newFree);
}
}
dataCache.add(page, 2);
}
}
private DataPage createPageHelper(Loggable loggable, long newPage) {
try {
DataPage dp = (DataPage) dataCache.get(newPage);
if (dp == null) {
final Page page = getPage(newPage);
byte[] data = page.read();
if (page.getPageHeader().getLsn() == Lsn.LSN_INVALID || (loggable != null && requiresRedo(loggable, page)) ) {
reuseDeleted(page);
final BFilePageHeader ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(RECORD);
ph.setDataLength(0);
ph.setDataLen(fileHeader.getWorkSize());
data = new byte[fileHeader.getWorkSize()];
ph.nextTID = 32;
dp = new SinglePage(page, data, true);
} else {
dp = new SinglePage(page, data, true);
}
}
if (loggable != null && loggable.getLsn() > dp.getPageHeader().getLsn())
{dp.getPageHeader().setLsn(loggable.getLsn());}
dp.setDirty(true);
dataCache.add(dp);
return dp;
} catch (final IOException e) {
LOG.warn("An IOException occurred during redo: " + e.getMessage(), e);
}
return null;
}
/**
* The file header. Most important, the file header stores the list of
* data pages containing unused space.
*
* @author wolf
*/
private final class BFileHeader extends BTreeFileHeader {
private FreeList freeList = new FreeList();
//public final static int MAX_FREE_LIST_LEN = 128;
public BFileHeader(int pageSize) {
super(pageSize);
}
public void addFreeSpace(FreeSpace freeSpace) {
freeList.add(freeSpace);
setDirty(true);
}
public FreeSpace findFreeSpace(int needed) {
return freeList.find(needed);
}
public FreeSpace getFreeSpace(long page) {
return freeList.retrieve(page);
}
public void removeFreeSpace(FreeSpace space) {
if (space == null) {return;}
freeList.remove(space);
setDirty(true);
}
public void debugFreeList() {
LOG.debug(getFile().getName() + ": " + freeList.toString());
}
@Override
public int read(byte[] buf) throws IOException {
final int offset = super.read(buf);
return freeList.read(buf, offset);
}
@Override
public int write(byte[] buf) throws IOException {
final int offset = super.write(buf);
return freeList.write(buf, offset);
}
}
private final class BFilePageHeader extends BTreePageHeader {
private int dataLen = 0;
private long lastInChain = -1L;
private long nextInChain = -1L;
// tuple identifier: used to identify distinct
// values inside a page
private short nextTID = -1;
private short records = 0;
public BFilePageHeader() {
super();
}
public BFilePageHeader(byte[] data, int offset) throws IOException {
super(data, offset);
}
public void decRecordCount() {
records--;
}
public int getDataLength() {
return dataLen;
}
public long getLastInChain() {
return lastInChain;
}
public long getNextInChain() {
return nextInChain;
}
public short getNextTID() {
if (nextTID == Short.MAX_VALUE) {
LOG.warn("tid limit reached");
return -1;
}
return ++nextTID;
}
public short getCurrentTID() {
if(nextTID == Short.MAX_VALUE) {
return -1;
}
return nextTID;
}
public short getRecordCount() {
return records;
}
public void incRecordCount() {
records++;
}
@Override
public int read(byte[] data, int offset) throws IOException {
offset = super.read(data, offset);
records = ByteConversion.byteToShort(data, offset);
offset += LENGTH_RECORDS_COUNT;
dataLen = ByteConversion.byteToInt(data, offset);
offset += 4;
nextTID = ByteConversion.byteToShort(data, offset);
offset += LENGTH_NEXT_TID;
nextInChain = ByteConversion.byteToLong(data, offset);
offset += 8;
lastInChain = ByteConversion.byteToLong(data, offset);
return offset + 8;
}
public void setDataLength(int len) {
dataLen = len;
}
public void setLastInChain(long p) {
lastInChain = p;
}
public void setNextInChain(long b) {
nextInChain = b;
}
public void setRecordCount(short recs) {
records = recs;
}
public void setTID(short tid) {
this.nextTID = tid;
}
@Override
public int write(byte[] data, int offset) throws IOException {
offset = super.write(data, offset);
ByteConversion.shortToByte(records, data, offset);
offset += LENGTH_RECORDS_COUNT;
ByteConversion.intToByte(dataLen, data, offset);
offset += 4;
ByteConversion.shortToByte(nextTID, data, offset);
offset += LENGTH_NEXT_TID;
ByteConversion.longToByte(nextInChain, data, offset);
offset += 8;
ByteConversion.longToByte(lastInChain, data, offset);
return offset + 8;
}
}
private abstract class DataPage implements Comparable, Cacheable {
int refCount = 0;
int timestamp = 0;
boolean saved = true;
public abstract void delete() throws IOException;
public abstract byte[] getData() throws IOException;
public abstract BFilePageHeader getPageHeader();
public abstract String getPageInfo();
public abstract long getPageNum();
public abstract int findValuePosition(short tid) throws IOException;
public abstract short getNextTID();
public abstract void removeTID(short tid, int length) throws IOException;
public abstract void setOffset(short tid, int offset);
public long getKey() {
return getPageNum();
}
public int getReferenceCount() {
return refCount;
}
public int incReferenceCount() {
if (refCount < Cacheable.MAX_REF) {++refCount;}
return refCount;
}
public int decReferenceCount() {
return refCount > 0 ? --refCount : 0;
}
public void setReferenceCount(int count) {
refCount = count;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#setTimestamp(int)
*/
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#getTimestamp()
*/
public int getTimestamp() {
return timestamp;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.cache.Cacheable#release()
*/
public boolean sync(boolean syncJournal) {
if (isDirty()) {
try {
write();
if (isTransactional && syncJournal && logManager.lastWrittenLsn() < getPageHeader().getLsn())
{logManager.flushToLog(true);}
return true;
} catch (final IOException e) {
LOG.error("IO exception occurred while saving page "
+ getPageNum());
}
}
return false;
}
public boolean isDirty() {
return !saved;
}
public boolean allowUnload() {
return true;
}
public abstract void setData(byte[] buf);
public abstract SinglePage getFirstPage();
public void setDirty(boolean dirty) {
saved = !dirty;
getPageHeader().setDirty(dirty);
}
public abstract void write() throws IOException;
public int compareTo(Object other) {
if (getPageNum() == ((DataPage) other).getPageNum())
{return Constants.EQUAL;}
else if (getPageNum() > ((DataPage) other).getPageNum())
{return Constants.SUPERIOR;}
else
{return Constants.INFERIOR;}
}
}
private final class FilterCallback implements BTreeCallback {
BFileCallback callback;
public FilterCallback(BFileCallback callback) {
this.callback = callback;
}
public boolean indexInfo(Value value, long pointer) throws TerminatedException{
try {
long pos;
short tid;
DataPage page;
int offset;
int l;
Value v;
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
offset = page.findValuePosition(tid);
final byte[] data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
callback.info(value, v);
return true;
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
return true;
}
}
}
private final class FindCallback implements BTreeCallback {
public final static int BOTH = 2;
public final static int KEYS = 1;
public final static int VALUES = 0;
private int mode = VALUES;
private IndexCallback callback = null;
private ArrayList<Value> values = null;
public FindCallback(int mode) {
this.mode = mode;
values = new ArrayList<Value>();
}
public FindCallback(IndexCallback callback) {
this.mode = BOTH;
this.callback = callback;
}
public ArrayList<Value> getValues() {
return values;
}
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
long pos;
short tid;
DataPage page;
int offset;
int l;
Value v;
byte[] data;
try {
switch (mode) {
case VALUES:
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
dataCache.add(page.getFirstPage());
offset = page.findValuePosition(tid);
data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
v.setAddress(pointer);
if (callback == null)
{values.add(v);}
else
{return callback.indexInfo(value, v);}
return true;
case KEYS:
value.setAddress(pointer);
if (callback == null)
{values.add(value);}
else
{return callback.indexInfo(value, null);}
return true;
case BOTH:
final Value[] entry = new Value[2];
entry[0] = value;
pos = StorageAddress.pageFromPointer(pointer);
tid = StorageAddress.tidFromPointer(pointer);
page = getDataPage(pos);
if (page.getPageHeader().getStatus() == MULTI_PAGE) {
data = page.getData();
}
dataCache.add(page.getFirstPage());
offset = page.findValuePosition(tid);
data = page.getData();
l = ByteConversion.byteToInt(data, offset);
v = new Value(data, offset + 4, l);
v.setAddress(pointer);
entry[1] = v;
if (callback == null) {
values.add(entry[0]);
values.add(entry[1]);
} else
{return callback.indexInfo(value, v);}
return true;
}
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
}
return false;
}
}
private final class OverflowPage extends DataPage {
byte[] data = null;
SinglePage firstPage;
public OverflowPage(Txn transaction) throws IOException {
firstPage = new SinglePage(false);
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowCreateLoggable(fileId, transaction, firstPage.getPageNum());
writeToLog(loggable, firstPage);
}
final BFilePageHeader ph = firstPage.getPageHeader();
ph.setStatus(MULTI_PAGE);
ph.setNextInChain(0L);
ph.setLastInChain(0L);
ph.setDataLength(0);
firstPage.setData(new byte[fileHeader.getWorkSize()]);
dataCache.add(firstPage, 3);
}
public OverflowPage(DataPage page) {
firstPage = (SinglePage) page;
}
public OverflowPage(Page p, byte[] data) throws IOException {
firstPage = new SinglePage(p, data, false);
firstPage.getPageHeader().setStatus(MULTI_PAGE);
}
/**
* Append a new chunk of data to the page
*
* @param chunk
* chunk of data to append
*/
public void append(Txn transaction, ByteArray chunk) throws IOException {
SinglePage nextPage;
BFilePageHeader ph = firstPage.getPageHeader();
final int newLen = ph.getDataLength() + chunk.size();
// get the last page and fill it
final long next = ph.getLastInChain();
DataPage page;
if (next > 0)
{page = getDataPage(next, false);}
else
{page = firstPage;}
ph = page.getPageHeader();
int chunkSize = fileHeader.getWorkSize() - ph.getDataLength();
final int chunkLen = chunk.size();
if (chunkLen < chunkSize) {chunkSize = chunkLen;}
// fill last page
if (isTransactional && transaction != null) {
final Loggable loggable =
new OverflowAppendLoggable(fileId, transaction, page.getPageNum(), chunk, 0, chunkSize);
writeToLog(loggable, page);
}
chunk.copyTo(0, page.getData(), ph.getDataLength(), chunkSize);
if(page != firstPage)
{ph.setDataLength(ph.getDataLength() + chunkSize);}
page.setDirty(true);
// write the remaining chunks to new pages
int remaining = chunkLen - chunkSize;
int current = chunkSize;
chunkSize = fileHeader.getWorkSize();
if (remaining > 0) {
// walk through chain of pages
while (remaining > 0) {
if (remaining < chunkSize) {chunkSize = remaining;}
// add a new page to the chain
nextPage = createDataPage();
if (isTransactional && transaction != null) {
Loggable loggable = new OverflowCreatePageLoggable(transaction, fileId, nextPage.getPageNum(),
page.getPageNum());
writeToLog(loggable, nextPage);
loggable = new OverflowAppendLoggable(fileId, transaction, nextPage.getPageNum(),
chunk, current, chunkSize);
writeToLog(loggable, page);
}
nextPage.setData(new byte[fileHeader.getWorkSize()]);
page.getPageHeader().setNextInChain(nextPage.getPageNum());
page.setDirty(true);
dataCache.add(page);
page = nextPage;
// copy next chunk of data to the page
chunk.copyTo(current, page.getData(), 0, chunkSize);
page.setDirty(true);
if (page != firstPage)
{page.getPageHeader().setDataLength(chunkSize);}
remaining = remaining - chunkSize;
current += chunkSize;
}
}
ph = firstPage.getPageHeader();
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowModifiedLoggable(fileId, transaction, firstPage.getPageNum(),
ph.getDataLength() + chunkLen, ph.getDataLength(), page == firstPage ? 0 : page.getPageNum());
writeToLog(loggable, page);
}
if (page != firstPage) {
// add link to last page
dataCache.add(page);
ph.setLastInChain(page.getPageNum());
} else
{ph.setLastInChain(0L);}
// adjust length field in first page
ph.setDataLength(newLen);
ByteConversion.intToByte(firstPage.getPageHeader().getDataLength() - 6, firstPage.getData(), 2);
firstPage.setDirty(true);
// keep the first page in cache
dataCache.add(firstPage, 2);
}
@Override
public void delete() throws IOException {
delete(null);
}
public void delete(Txn transaction) throws IOException {
long next = firstPage.getPageNum();
SinglePage page = firstPage;
do {
next = page.ph.getNextInChain();
if (isTransactional && transaction != null) {
int dataLen = page.ph.getDataLength();
if (dataLen > fileHeader.getWorkSize())
{dataLen = fileHeader.getWorkSize();}
final Loggable loggable = new OverflowRemoveLoggable(fileId, transaction,
page.ph.getStatus(), page.getPageNum(),
page.getData(), dataLen,
page.ph.getNextInChain());
writeToLog(loggable, page);
}
page.getPageHeader().setNextInChain(-1L);
page.setDirty(true);
dataCache.remove(page);
page.delete();
if (next > 0) {page = getSinglePage(next);}
} while (next > 0);
}
public VariableByteInput getDataStream(long pointer) {
final MultiPageInput input = new MultiPageInput(firstPage, pointer);
return input;
}
@Override
public byte[] getData() throws IOException {
if (data != null) {return data;}
SinglePage page = firstPage;
long next;
byte[] temp;
int len;
final ByteArrayOutputStream os = new ByteArrayOutputStream(page
.getPageHeader().getDataLength());
do {
temp = page.getData();
next = page.getPageHeader().getNextInChain();
len = next > 0 ? fileHeader.getWorkSize() : page
.getPageHeader().getDataLength();
os.write(temp, 0, len);
if (next > 0) {
page = (SinglePage) getDataPage(next, false);
dataCache.add(page);
}
} while (next > 0);
data = os.toByteArray();
if (data.length != firstPage.getPageHeader().getDataLength()) {
LOG.warn(getFile().getName() + " read=" + data.length
+ "; expected="
+ firstPage.getPageHeader().getDataLength());
}
return data;
}
@Override
public SinglePage getFirstPage() {
return firstPage;
}
@Override
public BFilePageHeader getPageHeader() {
return firstPage.getPageHeader();
}
@Override
public String getPageInfo() {
return "MULTI_PAGE: " + firstPage.getPageInfo();
}
@Override
public long getPageNum() {
return firstPage.getPageNum();
}
@Override
public void setData(byte[] buf) {
setData(null, buf);
}
public void setData(Txn transaction, byte[] data) {
this.data = data;
try {
write(transaction);
} catch (final IOException e) {
LOG.warn(e);
}
}
@Override
public void write() throws IOException {
write(null);
}
public void write(Txn transaction) throws IOException {
if (data == null) {return;}
int chunkSize = fileHeader.getWorkSize();
int remaining = data.length;
int current = 0;
long next = 0L;
SinglePage page = firstPage;
page.getPageHeader().setDataLength(remaining);
SinglePage nextPage;
long prevPageNum = Page.NO_PAGE;
// walk through chain of pages
while (remaining > 0) {
if (remaining < chunkSize) {chunkSize = remaining;}
page.clear();
// copy next chunk of data to the page
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowStoreLoggable(fileId, transaction, page.getPageNum(), prevPageNum,
data, current, chunkSize);
writeToLog(loggable, page);
}
System.arraycopy(data, current, page.getData(), 0, chunkSize);
if (page != firstPage)
{page.getPageHeader().setDataLength(chunkSize);}
page.setDirty(true);
remaining -= chunkSize;
current += chunkSize;
next = page.getPageHeader().getNextInChain();
if (remaining > 0) {
if (next > 0) {
// load next page in chain
nextPage = (SinglePage) getDataPage(next, false);
dataCache.add(page);
prevPageNum = page.getPageNum();
page = nextPage;
} else {
// add a new page to the chain
nextPage = createDataPage();
if (isTransactional && transaction != null) {
final Loggable loggable = new CreatePageLoggable(transaction, fileId, nextPage.getPageNum());
writeToLog(loggable, nextPage);
}
nextPage.setData(new byte[fileHeader.getWorkSize()]);
nextPage.getPageHeader().setNextInChain(0L);
page.getPageHeader().setNextInChain(
nextPage.getPageNum());
dataCache.add(page);
prevPageNum = page.getPageNum();
page = nextPage;
}
} else {
page.getPageHeader().setNextInChain(0L);
if (page != firstPage) {
page.setDirty(true);
dataCache.add(page);
firstPage.getPageHeader().setLastInChain(
page.getPageNum());
} else
{firstPage.getPageHeader().setLastInChain(0L);}
firstPage.setDirty(true);
dataCache.add(firstPage, 3);
}
}
if (next > 0) {
// there are more pages in the chain:
// remove them
while (next > 0) {
nextPage = (SinglePage) getDataPage(next, false);
next = nextPage.getPageHeader().getNextInChain();
if (isTransactional && transaction != null) {
final Loggable loggable = new OverflowRemoveLoggable(fileId, transaction,
nextPage.getPageHeader().getStatus(), nextPage.getPageNum(),
nextPage.getData(), nextPage.getPageHeader().getDataLength(),
nextPage.getPageHeader().getNextInChain());
writeToLog(loggable, nextPage);
}
nextPage.setDirty(true);
nextPage.delete();
dataCache.remove(nextPage);
}
}
firstPage.getPageHeader().setDataLength(data.length);
firstPage.setDirty(true);
dataCache.add(firstPage, 3);
// LOG.debug(firstPage.getPageNum() + " data length: " + firstPage.ph.getDataLength());
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#findValuePosition(short)
*/
@Override
public int findValuePosition(short tid) throws IOException {
return 2;
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#getNextTID()
*/
@Override
public short getNextTID() {
return 1;
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#removeTID(short)
*/
@Override
public void removeTID(short tid, int length) {
//
}
/* (non-Javadoc)
* @see org.exist.storage.store.BFile.DataPage#setOffset(short, int)
*/
@Override
public void setOffset(short tid, int offset) {
//
}
}
public interface PageInputStream {
public long getAddress();
public long position();
public void seek(long position) throws IOException;
}
/**
* Variable byte input stream to read data from a single page.
*
* @author wolf
*/
private final class SimplePageInput extends VariableByteArrayInput
implements PageInputStream {
private long address = 0L;
public SimplePageInput(byte[] data, int start, int len, long address) {
super(data, start, len);
this.address = address;
}
public long getAddress() {
return address;
}
public long position() {
return position;
}
public void seek(long pos) throws IOException {
this.position = (int) pos;
}
}
/**
* Variable byte input stream to read a multi-page sequences.
*
* @author wolf
*/
private final class MultiPageInput implements VariableByteInput, PageInputStream {
private SinglePage nextPage;
private int pageLen;
private short offset = 0;
private long address = 0L;
public MultiPageInput(SinglePage first, long address) {
nextPage = first;
offset = 6;
pageLen = first.ph.getDataLength();
if (pageLen > fileHeader.getWorkSize())
{pageLen = fileHeader.getWorkSize();}
dataCache.add(first, 3);
this.address = address;
}
public long getAddress() {
return address;
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read()
*/
public final int read() throws IOException {
if (offset == pageLen) {
advance();
}
return (nextPage.data[offset++] & 0xFF);
}
/*
* (non-Javadoc)
*
* @see org.exist.util.VariableInputStream#readByte()
*/
public final byte readByte() throws IOException {
if (offset == pageLen) {advance();}
return (nextPage.data[offset++]);
}
public final short readShort() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
short i = (short) (b & 0177);
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177) << shift;
}
return i;
}
public final int readInt() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
int i = b & 0177;
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177) << shift;
}
return i;
}
public int readFixedInt() throws IOException {
if (offset == pageLen) {advance();}
// do we have to read across a page boundary?
if (offset + 4 < pageLen) {
return ( nextPage.data[offset++] & 0xff ) |
( (nextPage.data[offset++] & 0xff) << 8 ) |
( (nextPage.data[offset++] & 0xff) << 16 ) |
( (nextPage.data[offset++] & 0xff) << 24 );
}
int r = nextPage.data[offset++] & 0xff;
int shift = 8;
for (int i = 0; i < 3; i++) {
if (offset == pageLen) {advance();}
r |= (nextPage.data[offset++] & 0xff) << shift;
shift += 8;
}
return r;
}
public final long readLong() throws IOException {
if (offset == pageLen) {advance();}
byte b = nextPage.data[offset++];
long i = b & 0177;
for (int shift = 7; (b & 0200) != 0; shift += 7) {
if (offset == pageLen) {advance();}
b = nextPage.data[offset++];
i |= (b & 0177L) << shift;
}
return i;
}
public final void skip(int count) throws IOException {
for (int i = 0; i < count; i++) {
do {
if (offset == pageLen) {advance();}
} while ((nextPage.data[offset++] & 0200) > 0);
}
}
public final void skipBytes(long count) throws IOException {
for(long i = 0; i < count; i++) {
if (offset == pageLen) {advance();}
offset++;
}
}
private final void advance() throws IOException {
final long next = nextPage.getPageHeader().getNextInChain();
if (next < 1) {
pageLen = -1;
offset = 0;
throw new EOFException();
}
try {
lock.acquire(Lock.READ_LOCK);
nextPage = (SinglePage) getDataPage(next, false);
pageLen = nextPage.ph.getDataLength();
offset = 0;
dataCache.add(nextPage);
} catch (final LockException e) {
throw new IOException("failed to acquire a read lock on "
+ getFile().getName());
} finally {
lock.release(Lock.READ_LOCK);
}
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#available()
*/
public final int available() throws IOException {
if (pageLen < 0)
{return 0;}
int inPage = pageLen - offset;
if (inPage == 0)
{inPage = nextPage.getPageHeader().getNextInChain() > 0 ? 1 : 0;}
return inPage;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#read(byte[])
*/
public final int read(byte[] data) throws IOException {
return read(data, 0, data.length);
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read(byte[], int, int)
*/
public final int read(byte[] b, int off, int len) throws IOException {
if (pageLen < 0) {return -1;}
for (int i = 0; i < len; i++) {
if (offset == pageLen) {
final long next = nextPage.getPageHeader().getNextInChain();
if (next < 1) {
pageLen = -1;
offset = 0;
return i;
}
nextPage = (SinglePage) getDataPage(next, false);
pageLen = nextPage.ph.getDataLength();
offset = 0;
dataCache.add(nextPage);
}
b[off + i] = nextPage.data[offset++];
}
return len;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#readUTF()
*/
public final String readUTF() throws IOException, EOFException {
final int len = readInt();
final byte data[] = new byte[len];
read(data);
String s;
try {
s = new String(data, "UTF-8");
} catch (final UnsupportedEncodingException e) {
LOG.warn(e);
s = new String(data);
}
return s;
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#copyTo(org.exist.storage.io.VariableByteOutputStream)
*/
public final void copyTo(VariableByteOutputStream os) throws IOException {
byte more;
do {
if (offset == pageLen) {advance();}
more = nextPage.data[offset++];
os.writeByte(more);
more &= 0200;
} while (more > 0);
}
/*
* (non-Javadoc)
*
* @see org.exist.storage.io.VariableByteInput#copyTo(org.exist.storage.io.VariableByteOutputStream,
* int)
*/
public final void copyTo(VariableByteOutputStream os, int count) throws IOException {
byte more;
for (int i = 0; i < count; i++) {
do {
if (offset == pageLen) {advance();}
more = nextPage.data[offset++];
os.writeByte(more);
} while ((more & 0x200) > 0);
}
}
public void copyRaw(VariableByteOutputStream os, int count) throws IOException {
for (int i = count; i != 0; ) {
if (offset == pageLen) {advance();}
int avail = pageLen - offset;
if (i >= avail) {
os.write(nextPage.data, offset, avail);
i -= avail;
offset = (short) pageLen;
} else {
os.write(nextPage.data, offset, i);
offset += i;
break;
}
//os.writeByte(nextPage.data[offset++]);
}
}
public long position() {
return StorageAddress.createPointer((int) nextPage.getPageNum(), offset);
}
public void seek(long position) throws IOException {
final int newPage = StorageAddress.pageFromPointer(position);
short newOffset = StorageAddress.tidFromPointer(position);
try {
lock.acquire(Lock.READ_LOCK);
nextPage = getSinglePage(newPage);
pageLen = nextPage.ph.getDataLength();
if (pageLen > fileHeader.getWorkSize())
{pageLen = fileHeader.getWorkSize();}
offset = newOffset;
dataCache.add(nextPage);
} catch (final LockException e) {
throw new IOException("Failed to acquire a read lock on " + getFile().getName());
} finally {
lock.release(Lock.READ_LOCK);
}
}
}
/**
* Represents a single data page (as opposed to a overflow page).
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
*/
private final class SinglePage extends DataPage {
// the raw working data of this page (without page header)
byte[] data = null;
// the low-level page
Page page;
// the page header
BFilePageHeader ph;
// table mapping record ids (tids) to offsets
short[] offsets = null;
public SinglePage() throws IOException {
this(true);
}
public SinglePage(boolean compress) throws IOException {
page = getFreePage();
ph = (BFilePageHeader) page.getPageHeader();
ph.setStatus(RECORD);
ph.setDirty(true);
ph.setDataLength(0);
//ph.setNextChunk( -1 );
data = new byte[fileHeader.getWorkSize()];
offsets = new short[32];
ph.nextTID = 32;
Arrays.fill(offsets, (short)-1);
}
public SinglePage(Page p, byte[] data, boolean initialize) throws IOException {
if (p == null) {throw new IOException("illegal page");}
if (!(p.getPageHeader().getStatus() == RECORD || p.getPageHeader()
.getStatus() == MULTI_PAGE)) {
final IOException e = new IOException("not a data-page: "
+ p.getPageHeader().getStatus());
LOG.debug("not a data-page: " + p.getPageInfo(), e);
throw e;
}
this.data = data;
page = p;
ph = (BFilePageHeader) page.getPageHeader();
if(initialize) {
offsets = new short[ph.nextTID];
if (ph.getStatus() != MULTI_PAGE)
readOffsets();
}
}
@Override
public final int findValuePosition(short tid) throws IOException {
return offsets[tid];
}
private void readOffsets() {
//if(offsets.length > 256)
//LOG.warn("TID size: " + ph.nextTID);
Arrays.fill(offsets, (short)-1);
final int dlen = ph.getDataLength();
for(short pos = 0; pos < dlen; ) {
final short tid = ByteConversion.byteToShort(data, pos);
if (tid < 0) {
LOG.error("Invalid tid found: " + tid + "; ignoring rest of page ...");
ph.setDataLength(pos);
return;
}
if(tid >= offsets.length) {
LOG.error("Problematic tid found: " + tid + "; trying to recover ...");
short[] t = new short[tid + 1];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = (short)(tid + 1);
}
offsets[tid] = (short)(pos + 2);
pos += ByteConversion.byteToInt(data, pos + 2) + 6;
}
}
@Override
public short getNextTID() {
for(short i = 0; i < offsets.length; i++) {
if(offsets[i] == -1) {
return i;
}
}
final short tid = (short)offsets.length;
short next = (short)(ph.nextTID * 2);
if(next < 0 || next < ph.nextTID) {
return -1;
}
short[] t = new short[next];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = next;
return tid;
}
public void adjustTID(short tid) {
if (tid >= ph.nextTID) {
short next = (short)(tid * 2);
short[] t = new short[next];
Arrays.fill(t, (short)-1);
System.arraycopy(offsets, 0, t, 0, offsets.length);
offsets = t;
ph.nextTID = next;
}
}
public void clear() {
Arrays.fill(data, (byte) 0);
}
private String printContents() {
final StringBuilder buf = new StringBuilder();
for(short i = 0; i < offsets.length; i++) {
if (offsets[i] > -1) {
buf.append('[').append(i).append(", ").append(offsets[i]);
final short len = ByteConversion.byteToShort(data, offsets[i]);
buf.append(", ").append(len).append(']');
}
}
return buf.toString();
}
@Override
public void setOffset(short tid, int offset) {
offsets[tid] = (short)offset;
}
@Override
public void removeTID(short tid, int length) throws IOException {
final int offset = offsets[tid] - 2;
offsets[tid] = -1;
for(short i = 0; i < offsets.length; i++) {
if(offsets[i] > offset)
{offsets[i] -= length;}
}
//readOffsets(start);
}
@Override
public void delete() throws IOException {
// reset page header fields
ph.setDataLength(0);
ph.setNextInChain(-1L);
ph.setLastInChain(-1L);
ph.setTID((short) -1);
ph.setRecordCount((short) 0);
setReferenceCount(0);
ph.setDirty(true);
unlinkPages(page);
}
@Override
public SinglePage getFirstPage() {
return this;
}
@Override
public byte[] getData() {
return data;
}
@Override
public BFilePageHeader getPageHeader() {
return ph;
}
@Override
public String getPageInfo() {
return page.getPageInfo();
}
@Override
public long getPageNum() {
return page.getPageNum();
}
@Override
public void setData(byte[] buf) {
data = buf;
}
@Override
public void write() throws IOException {
//LOG.debug(getFile().getName() + " writing page " + getPageNum());
writeValue(page, new Value(data));
setDirty(false);
}
}
}
|
[bugfix] Crash recovery: exception during transaction rollback causes recovery to abort with NPE - page was not initialized properly.
|
src/org/exist/storage/index/BFile.java
|
[bugfix] Crash recovery: exception during transaction rollback causes recovery to abort with NPE - page was not initialized properly.
|
|
Java
|
unlicense
|
152c4e26cd1a6312df2d4e7ef84161e93c203d89
| 0
|
Kramermp/FoodMood
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package userprofile.model;
import java.util.ArrayList;
/**
*
* @author Michael Kramer
*/
public class UserList {
private ArrayList<User> theListOfUsers = new ArrayList<User>();
/**
* Default Constructor of the UserList, creates an empty UserList
*/
public UserList() {
theListOfUsers.add(new User("TestUser", "pass".toCharArray()));
}
public static UserList createTestUserList() {
UserList testUserList = new UserList();
testUserList.theListOfUsers = new ArrayList<User>();
testUserList.theListOfUsers.add(new User("TestUser", "pass".toCharArray()));
return testUserList;
}
/**
* Goes through the UserList validates the provided credentials
* @param username The Username to validate
* @param password The Password to validate
* @return the boolean if it is authenticated
*/
public boolean authenticateUserCredentials(String username, char[] password) {
boolean authenticated = false;
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equalsIgnoreCase(username)){
authenticated = theListOfUsers.get(i).authenticate(username, password);
break;
}
}
return authenticated;
}
/**
* Adds a User to the UserList with the provided UserName and Password
* @param username Username of the new User
* @param password Password of the new User
*/
public void addUser(String username, char[] password) {
User newUser = new User(username, password);
theListOfUsers.add(newUser);
}
/**
* Removes a User from the UserList
* @param username The Username of the User to remove
* @param password The Password of the User to remove
*/
public void deleteUser(String username, char[] password) {
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
if(java.util.Arrays.equals(password, theListOfUsers.get(i).getPassword())){
theListOfUsers.remove(i);
}
}
}
}
/**
* Returns if a User is found with the provided Username
* @param username The Username to check for
* @return the boolean of if it has user
*/
public boolean hasUser(String username) {
boolean found = false;
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
found = true;
break;
}
}
return found;
}
/**
* Gets the User with Username from the UserList
* @param username The Username of the User to get
* @return the User
*/
public User getUser(String username) {
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
return theListOfUsers.get(i);
}
}
return null;
}
/**
* Returns the number of Users in the UserList
* @return the Count of Users
*/
public int getUserCount() {
return theListOfUsers.size();
}
}
|
src/userprofile/model/UserList.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package userprofile.model;
import java.util.ArrayList;
/**
*
* @author Michael Kramer
*/
public class UserList {
private ArrayList<User> theListOfUsers = new ArrayList<User>();
/**
* Default Constructor of the UserList, creates an empty UserList
*/
public UserList() {
theListOfUsers.add(new User("TestUser", "pass".toCharArray()));
}
public static UserList createTestUserList() {
UserList testUserList = new UserList();
testUserList.theListOfUsers = new ArrayList<User>();
testUserList.theListOfUsers.add(new User("TestUser", "pass".toCharArray()));
return testUserList;
}
/**
* Goes through the UserList validates the provided credentials
* @param username The Username to validate
* @param password The Password to validate
* @return the boolean if it is authenticated
*/
public boolean authenticateUserCredentials(String username, char[] password) {
boolean authenticated = false;
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().toLowerCase().equals(username.toLowerCase())){
authenticated = theListOfUsers.get(i).authenticate(username, password);
break;
}
}
return authenticated;
}
/**
* Adds a User to the UserList with the provided UserName and Password
* @param username Username of the new User
* @param password Password of the new User
*/
public void addUser(String username, char[] password) {
User newUser = new User(username, password);
theListOfUsers.add(newUser);
}
/**
* Removes a User from the UserList
* @param username The Username of the User to remove
* @param password The Password of the User to remove
*/
public void deleteUser(String username, char[] password) {
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
if(java.util.Arrays.equals(password, theListOfUsers.get(i).getPassword())){
theListOfUsers.remove(i);
}
}
}
}
/**
* Returns if a User is found with the provided Username
* @param username The Username to check for
* @return the boolean of if it has user
*/
public boolean hasUser(String username) {
boolean found = false;
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
found = true;
break;
}
}
return found;
}
/**
* Gets the User with Username from the UserList
* @param username The Username of the User to get
* @return the User
*/
public User getUser(String username) {
for (int i = 0; i < theListOfUsers.size(); i++) {
if(theListOfUsers.get(i).getUsername().equals(username)){
return theListOfUsers.get(i);
}
}
return null;
}
/**
* Returns the number of Users in the UserList
* @return the Count of Users
*/
public int getUserCount() {
return theListOfUsers.size();
}
}
|
Fixed authenticate to use equalsIgnoreCase instead of toLowerCase.
|
src/userprofile/model/UserList.java
|
Fixed authenticate to use equalsIgnoreCase instead of toLowerCase.
|
|
Java
|
apache-2.0
|
bd2b53efedfd706c2c02ae37be2b3c862edc2b12
| 0
|
trixon/java-mapollage
|
/*
* Copyright 2017 Patrik Karlsson.
*
* 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 se.trixon.mapollage;
import java.util.Locale;
import java.util.prefs.Preferences;
import org.apache.commons.lang3.SystemUtils;
import se.trixon.almond.util.swing.dialogs.MenuModePanel.MenuMode;
/**
*
* @author Patrik Karlsson
*/
public class Options {
public static final String KEY_AUTO_OPEN = "auto_open";
public static final String KEY_DEFAULT_LAT = "deflat";
public static final String KEY_DEFAULT_LON = "deflon";
public static final String KEY_LOCALE = "locale";
public static final String KEY_MENU_MODE = "menu_mode";
public static final String KEY_THUMBNAIL_BORDER_SIZE = "thumbnail_border_size";
public static final String KEY_THUMBNAIL_SIZE = "thumbnail_size";
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
private final boolean DEFAULT_AUTO_OPEN = true;
private final Double DEFAULT_LAT = 57.6;
private final Double DEFAULT_LON = 11.3;
private final MenuMode DEFAULT_MENU_MODE = SystemUtils.IS_OS_MAC ? MenuMode.BAR : MenuMode.BUTTON;
private final int DEFAULT_THUMBNAIL_BORDER_SIZE = 3;
private final int DEFAULT_THUMBNAIL_SIZE = 1000;
private final Preferences mPreferences = Preferences.userNodeForPackage(Options.class);
public static Options getInstance() {
return Holder.INSTANCE;
}
private Options() {
}
public Double getDefaultLat() {
return mPreferences.getDouble(KEY_DEFAULT_LAT, DEFAULT_LAT);
}
public Double getDefaultLon() {
return mPreferences.getDouble(KEY_DEFAULT_LON, DEFAULT_LON);
}
public Locale getLocale() {
return Locale.forLanguageTag(mPreferences.get(KEY_LOCALE, DEFAULT_LOCALE.toLanguageTag()));
}
public MenuMode getMenuMode() {
return MenuMode.values()[mPreferences.getInt(KEY_MENU_MODE, DEFAULT_MENU_MODE.ordinal())];
}
public Preferences getPreferences() {
return mPreferences;
}
public int getThumbnailBorderSize() {
return mPreferences.getInt(KEY_THUMBNAIL_BORDER_SIZE, DEFAULT_THUMBNAIL_BORDER_SIZE);
}
public int getThumbnailSize() {
return mPreferences.getInt(KEY_THUMBNAIL_SIZE, DEFAULT_THUMBNAIL_SIZE);
}
public boolean isAutoOpen() {
return mPreferences.getBoolean(KEY_AUTO_OPEN, DEFAULT_AUTO_OPEN);
}
public void setAutoOpen(boolean value) {
mPreferences.putBoolean(KEY_AUTO_OPEN, value);
}
public void setDefaultLat(Double value) {
mPreferences.putDouble(KEY_DEFAULT_LAT, value);
}
public void setDefaultLon(Double value) {
mPreferences.putDouble(KEY_DEFAULT_LON, value);
}
public void setLocale(Locale locale) {
mPreferences.put(KEY_LOCALE, locale.toLanguageTag());
}
public void setMenuMode(MenuMode menuMode) {
mPreferences.putInt(KEY_MENU_MODE, menuMode.ordinal());
}
public void setThumbnailBorderSize(int size) {
mPreferences.putInt(KEY_THUMBNAIL_BORDER_SIZE, size);
}
public void setThumbnailSize(int size) {
mPreferences.putInt(KEY_THUMBNAIL_SIZE, size);
}
private static class Holder {
private static final Options INSTANCE = new Options();
}
}
|
src/main/java/se/trixon/mapollage/Options.java
|
/*
* Copyright 2017 Patrik Karlsson.
*
* 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 se.trixon.mapollage;
import java.util.Locale;
import java.util.prefs.Preferences;
import org.apache.commons.lang3.SystemUtils;
import se.trixon.almond.util.swing.dialogs.MenuModePanel.MenuMode;
/**
*
* @author Patrik Karlsson
*/
public class Options {
public static final String KEY_AUTO_OPEN = "auto_open";
public static final String KEY_DEFAULT_LAT = "deflat";
public static final String KEY_DEFAULT_LON = "deflon";
public static final String KEY_LOCALE = "locale";
public static final String KEY_MENU_MODE = "menu_mode";
public static final String KEY_THUMBNAIL_BORDER_SIZE = "thumbnail_border_size";
public static final String KEY_THUMBNAIL_SIZE = "thumbnail_size";
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
private final boolean DEFAULT_AUTO_OPEN = true;
private final Double DEFAULT_LAT = 57.6;
private final Double DEFAULT_LON = 11.3;
private final MenuMode DEFAULT_MENU_MODE = SystemUtils.IS_OS_MAC ? MenuMode.BAR : MenuMode.BUTTON;
private final int DEFAULT_THUMBNAIL_BORDER_SIZE = 2;
private final int DEFAULT_THUMBNAIL_SIZE = 512;
private final Preferences mPreferences = Preferences.userNodeForPackage(Options.class);
public static Options getInstance() {
return Holder.INSTANCE;
}
private Options() {
}
public Double getDefaultLat() {
return mPreferences.getDouble(KEY_DEFAULT_LAT, DEFAULT_LAT);
}
public Double getDefaultLon() {
return mPreferences.getDouble(KEY_DEFAULT_LON, DEFAULT_LON);
}
public Locale getLocale() {
return Locale.forLanguageTag(mPreferences.get(KEY_LOCALE, DEFAULT_LOCALE.toLanguageTag()));
}
public MenuMode getMenuMode() {
return MenuMode.values()[mPreferences.getInt(KEY_MENU_MODE, DEFAULT_MENU_MODE.ordinal())];
}
public Preferences getPreferences() {
return mPreferences;
}
public int getThumbnailBorderSize() {
return mPreferences.getInt(KEY_THUMBNAIL_BORDER_SIZE, DEFAULT_THUMBNAIL_BORDER_SIZE);
}
public int getThumbnailSize() {
return mPreferences.getInt(KEY_THUMBNAIL_SIZE, DEFAULT_THUMBNAIL_SIZE);
}
public boolean isAutoOpen() {
return mPreferences.getBoolean(KEY_AUTO_OPEN, DEFAULT_AUTO_OPEN);
}
public void setAutoOpen(boolean value) {
mPreferences.putBoolean(KEY_AUTO_OPEN, value);
}
public void setDefaultLat(Double value) {
mPreferences.putDouble(KEY_DEFAULT_LAT, value);
}
public void setDefaultLon(Double value) {
mPreferences.putDouble(KEY_DEFAULT_LON, value);
}
public void setLocale(Locale locale) {
mPreferences.put(KEY_LOCALE, locale.toLanguageTag());
}
public void setMenuMode(MenuMode menuMode) {
mPreferences.putInt(KEY_MENU_MODE, menuMode.ordinal());
}
public void setThumbnailBorderSize(int size) {
mPreferences.putInt(KEY_THUMBNAIL_BORDER_SIZE, size);
}
public void setThumbnailSize(int size) {
mPreferences.putInt(KEY_THUMBNAIL_SIZE, size);
}
private static class Holder {
private static final Options INSTANCE = new Options();
}
}
|
Change defaults
|
src/main/java/se/trixon/mapollage/Options.java
|
Change defaults
|
|
Java
|
apache-2.0
|
afc92e4f9871aeee8e30b50dbe073ad25c39b6e5
| 0
|
lucafavatella/intellij-community,tmpgit/intellij-community,allotria/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,caot/intellij-community,petteyg/intellij-community,signed/intellij-community,petteyg/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,izonder/intellij-community,signed/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,asedunov/intellij-community,asedunov/intellij-community,kdwink/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,consulo/consulo,xfournet/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,youdonghai/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ernestp/consulo,youdonghai/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,joewalnes/idea-community,samthor/intellij-community,FHannes/intellij-community,dslomov/intellij-community,samthor/intellij-community,semonte/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,dslomov/intellij-community,hurricup/intellij-community,samthor/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,slisson/intellij-community,allotria/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,semonte/intellij-community,kool79/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,kdwink/intellij-community,adedayo/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,slisson/intellij-community,holmes/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,kool79/intellij-community,holmes/intellij-community,slisson/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,semonte/intellij-community,da1z/intellij-community,caot/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,da1z/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fitermay/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,retomerz/intellij-community,holmes/intellij-community,amith01994/intellij-community,ryano144/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,kool79/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,blademainer/intellij-community,retomerz/intellij-community,da1z/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,clumsy/intellij-community,ibinti/intellij-community,jexp/idea2,blademainer/intellij-community,vladmm/intellij-community,apixandru/intellij-community,ibinti/intellij-community,slisson/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,slisson/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,hurricup/intellij-community,fitermay/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,supersven/intellij-community,asedunov/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,hurricup/intellij-community,kdwink/intellij-community,consulo/consulo,TangHao1987/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,jagguli/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,da1z/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,asedunov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,da1z/intellij-community,diorcety/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,signed/intellij-community,robovm/robovm-studio,slisson/intellij-community,adedayo/intellij-community,joewalnes/idea-community,xfournet/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,Lekanich/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,signed/intellij-community,jagguli/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,signed/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,adedayo/intellij-community,clumsy/intellij-community,da1z/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,jagguli/intellij-community,FHannes/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,blademainer/intellij-community,ernestp/consulo,retomerz/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,ibinti/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,izonder/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,kdwink/intellij-community,signed/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,xfournet/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,kool79/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,blademainer/intellij-community,holmes/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,allotria/intellij-community,clumsy/intellij-community,izonder/intellij-community,consulo/consulo,signed/intellij-community,fnouama/intellij-community,holmes/intellij-community,jexp/idea2,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,joewalnes/idea-community,semonte/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,vladmm/intellij-community,izonder/intellij-community,clumsy/intellij-community,fitermay/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ryano144/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,ernestp/consulo,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,supersven/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,clumsy/intellij-community,semonte/intellij-community,asedunov/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,fnouama/intellij-community,kool79/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,semonte/intellij-community,izonder/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,samthor/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,semonte/intellij-community,robovm/robovm-studio,apixandru/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,diorcety/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,jagguli/intellij-community,slisson/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,allotria/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,hurricup/intellij-community,supersven/intellij-community,clumsy/intellij-community,amith01994/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,izonder/intellij-community,amith01994/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,blademainer/intellij-community,consulo/consulo,joewalnes/idea-community,blademainer/intellij-community,slisson/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,signed/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,caot/intellij-community,holmes/intellij-community,fitermay/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,caot/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,jagguli/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ernestp/consulo,caot/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,retomerz/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fnouama/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,vladmm/intellij-community,jexp/idea2,allotria/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,kool79/intellij-community,semonte/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,caot/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,diorcety/intellij-community,supersven/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,kool79/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,da1z/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,petteyg/intellij-community,supersven/intellij-community,fnouama/intellij-community,jagguli/intellij-community,izonder/intellij-community,apixandru/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,jexp/idea2,akosyakov/intellij-community,kdwink/intellij-community,jexp/idea2,fnouama/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,jexp/idea2,blademainer/intellij-community,ibinti/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,adedayo/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kool79/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,samthor/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,supersven/intellij-community,vladmm/intellij-community,xfournet/intellij-community,xfournet/intellij-community,diorcety/intellij-community,samthor/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,consulo/consulo,kool79/intellij-community,caot/intellij-community,xfournet/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,signed/intellij-community
|
/**
* created at Sep 17, 2001
* @author Jeka
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.util.*;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo;
import com.intellij.refactoring.ui.ConflictsDialog;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorUsageCollector;
import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import com.intellij.javaee.ejb.role.*;
import com.intellij.javaee.model.common.ejb.EjbPsiMethodUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class ChangeSignatureProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.changeSignature.ChangeSignatureProcessor");
private final String myNewVisibility;
private ChangeInfo myChangeInfo;
private PsiManager myManager;
private PsiElementFactory myFactory;
private final boolean myGenerateDelegate;
private final Set<PsiMethod> myPropagateParametersMethods;
private final Set<PsiMethod> myPropagateExceptionsMethods;
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
String newVisibility,
String newName,
PsiType newType,
@NotNull ParameterInfo[] parameterInfo) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, null, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
String newVisibility,
String newName,
PsiType newType,
ParameterInfo[] parameterInfo,
ThrownExceptionInfo[] exceptionInfos) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, exceptionInfos, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
boolean generateDelegate,
String newVisibility,
String newName,
CanonicalTypes.Type newType,
@NotNull ParameterInfo[] parameterInfo,
ThrownExceptionInfo[] thrownExceptions,
Set<PsiMethod> propagateParametersMethods,
Set<PsiMethod> propagateExceptionsMethods) {
super(project);
myManager = PsiManager.getInstance(project);
myFactory = myManager.getElementFactory();
myGenerateDelegate = generateDelegate;
myPropagateParametersMethods = propagateParametersMethods != null ? propagateParametersMethods : new HashSet<PsiMethod>();
myPropagateExceptionsMethods = propagateExceptionsMethods != null ? propagateExceptionsMethods : new HashSet<PsiMethod>();
LOG.assertTrue(method.isValid());
if (newVisibility == null) {
myNewVisibility = VisibilityUtil.getVisibilityModifier(method.getModifierList());
} else {
myNewVisibility = newVisibility;
}
myChangeInfo = new ChangeInfo(myNewVisibility, method, newName, newType, parameterInfo, thrownExceptions);
LOG.assertTrue(myChangeInfo.getMethod().isValid());
}
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
return new ChangeSignatureViewDescriptor(myChangeInfo.getMethod());
}
@NotNull
protected UsageInfo[] findUsages() {
ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
final PsiMethod method = myChangeInfo.getMethod();
findSimpleUsages(method, result);
findEjbUsages(result);
final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
private void findSimpleUsages(final PsiMethod method, final ArrayList<UsageInfo> result) {
PsiMethod[] overridingMethods = findSimpleUsagesWithoutParameters(method, result, true, true, true);
findUsagesInCallers (result);
//Parameter name changes are not propagated
findParametersUsage(method, result, overridingMethods);
}
private PsiMethod[] findSimpleUsagesWithoutParameters(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isToModifyArgs,
boolean isToThrowExceptions,
boolean isOriginal) {
PsiManager manager = method.getManager();
PsiSearchHelper helper = manager.getSearchHelper();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myProject);
PsiMethod[] overridingMethods = helper.findOverridingMethods(method, projectScope, true);
for (PsiMethod overridingMethod : overridingMethods) {
result.add(new OverriderUsageInfo(overridingMethod, method, isOriginal, isToModifyArgs, isToThrowExceptions));
}
boolean needToChangeCalls = !myGenerateDelegate && (myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged || myChangeInfo.isVisibilityChanged/*for checking inaccessible*/);
if (needToChangeCalls) {
List<PsiReference> l = new ArrayList<PsiReference>();
PsiReference[] refs = helper.findReferencesIncludingOverriding(method, projectScope, true);
for (PsiReference reference : refs) {
l.add(reference);
}
int parameterCount = method.getParameterList().getParameters().length;
for (PsiReference ref : l) {
PsiElement element = ref.getElement();
boolean isToCatchExceptions = isToThrowExceptions && needToCatchExceptions(RefactoringUtil.getEnclosingMethod(element));
if (!isToCatchExceptions) {
if (RefactoringUtil.isMethodUsage(element)) {
PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(element);
if (!method.isVarArgs() && list.getExpressions().length != parameterCount) continue;
}
}
if (RefactoringUtil.isMethodUsage(element)) {
result.add(new MethodCallUsageInfo(element, isToModifyArgs, isToCatchExceptions));
}
else {
result.add(new MoveRenameUsageInfo(element, ref, method));
}
}
if (method.isConstructor() && parameterCount == 0) {
RefactoringUtil.visitImplicitConstructorUsages(method.getContainingClass(),
new DefaultConstructorUsageCollector(result));
}
} else if (myChangeInfo.isParameterTypesChanged) {
PsiReference[] refs = helper.findReferencesIncludingOverriding(method, projectScope, true);
for (PsiReference reference : refs) {
if (reference.getElement() instanceof PsiDocTagValue) { //types are mentioned in e.g @link, see SCR 40895
result.add(new UsageInfo(reference.getElement()));
}
}
}
// Conflicts
detectLocalsCollisionsInMethod(method, result, isOriginal);
for (final PsiMethod overridingMethod : overridingMethods) {
detectLocalsCollisionsInMethod(overridingMethod, result, isOriginal);
}
return overridingMethods;
}
private void findUsagesInCallers(final ArrayList<UsageInfo> usages) {
for (PsiMethod caller : myPropagateParametersMethods) {
usages.add(new CallerUsageInfo(caller, true, myPropagateExceptionsMethods.contains(caller)));
}
for (PsiMethod caller : myPropagateExceptionsMethods) {
usages.add(new CallerUsageInfo(caller, myPropagateParametersMethods.contains(caller), true));
}
Set<PsiMethod> merged = new HashSet<PsiMethod>();
merged.addAll(myPropagateParametersMethods);
merged.addAll(myPropagateExceptionsMethods);
for (final PsiMethod method : merged) {
findSimpleUsagesWithoutParameters(method, usages, myPropagateParametersMethods.contains(method),
myPropagateExceptionsMethods.contains(method), false);
}
}
private boolean needToChangeCalls() {
return myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged;
}
private boolean needToCatchExceptions(PsiMethod caller) {
return myChangeInfo.isExceptionSetOrOrderChanged && !myPropagateExceptionsMethods.contains(caller);
}
private void detectLocalsCollisionsInMethod(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isOriginal) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final Set<PsiParameter> deletedOrRenamedParameters = new HashSet<PsiParameter>();
if (isOriginal) {
deletedOrRenamedParameters.addAll(Arrays.asList(parameters));
for (ParameterInfo parameterInfo : myChangeInfo.newParms) {
if (parameterInfo.oldParameterIndex >= 0) {
final PsiParameter parameter = parameters[parameterInfo.oldParameterIndex];
if (parameterInfo.getName().equals(parameter.getName())) {
deletedOrRenamedParameters.remove(parameter);
}
}
}
}
for (ParameterInfo parameterInfo : myChangeInfo.newParms) {
final int oldParameterIndex = parameterInfo.oldParameterIndex;
final String newName = parameterInfo.getName();
if (oldParameterIndex >= 0) {
if (isOriginal) { //Name changes take place only in primary method
final PsiParameter parameter = parameters[oldParameterIndex];
if (!newName.equals(parameter.getName())) {
RenameUtil.visitLocalsCollisions(parameter, newName, method.getBody(), null, new RenameUtil.CollidingVariableVisitor() {
public void visitCollidingElement(final PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedOrRenamedParameters.contains(collidingVariable)) {
result.add(new RenamedParameterCollidesWithLocalUsageInfo(parameter, collidingVariable, method));
}
}
});
}
}
}
else {
RenameUtil.visitLocalsCollisions(method, newName, method.getBody(), null, new RenameUtil.CollidingVariableVisitor() {
public void visitCollidingElement(PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedOrRenamedParameters.contains(collidingVariable)) {
result.add(new NewParameterCollidesWithLocalUsageInfo(collidingVariable, collidingVariable, method));
}
}
});
}
}
}
private void findParametersUsage(final PsiMethod method, ArrayList<UsageInfo> result, PsiMethod[] overriders) {
PsiParameter[] parameters = method.getParameterList().getParameters();
for (ParameterInfo info : myChangeInfo.newParms) {
if (info.oldParameterIndex >= 0) {
PsiParameter parameter = parameters[info.oldParameterIndex];
if (!info.getName().equals(parameter.getName())) {
addParameterUsages(parameter, result, info);
for (PsiMethod overrider : overriders) {
PsiParameter parameter1 = overrider.getParameterList().getParameters()[info.oldParameterIndex];
if (parameter.getName().equals(parameter1.getName())) {
addParameterUsages(parameter1, result, info);
}
}
}
}
}
}
private void findEjbUsages(ArrayList<UsageInfo> result) {
if (!(myChangeInfo.ejbRole instanceof EjbDeclMethodRole)) return;
for (PsiMethod implementation : ((EjbDeclMethodRole) myChangeInfo.ejbRole).findAllImplementations()) {
result.add(new UsageInfo(implementation));
findSimpleUsages(implementation, result);
}
}
protected void refreshElements(PsiElement[] elements) {
boolean condition = elements.length == 1 && elements[0] instanceof PsiMethod;
LOG.assertTrue(condition);
myChangeInfo.updateMethod((PsiMethod) elements[0]);
}
private void addMethodConflicts(Collection<String> conflicts) {
String newMethodName = myChangeInfo.newName;
try {
PsiMethod prototype;
PsiManager manager = PsiManager.getInstance(myProject);
PsiElementFactory factory = manager.getElementFactory();
final PsiMethod method = myChangeInfo.getMethod();
final CanonicalTypes.Type returnType = myChangeInfo.newReturnType;
if (returnType != null) {
prototype = factory.createMethod(newMethodName, returnType.getType(method, manager));
}
else {
prototype = factory.createConstructor();
prototype.setName(newMethodName);
}
ParameterInfo[] parameters = myChangeInfo.newParms;
for (ParameterInfo info : parameters) {
final PsiType parameterType = info.createType(method, manager);
PsiParameter param = factory.createParameter(info.getName(), parameterType);
prototype.getParameterList().add(param);
}
ConflictsUtil.checkMethodConflicts(
method.getContainingClass(),
method,
prototype, conflicts);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
Set<String> conflictDescriptions = new HashSet<String>();
UsageInfo[] usagesIn = refUsages.get();
addMethodConflicts(conflictDescriptions);
conflictDescriptions.addAll(RenameUtil.getConflictDescriptions(usagesIn));
Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(usagesIn));
RenameUtil.removeConflictUsages(usagesSet);
if (myChangeInfo.isVisibilityChanged) {
try {
addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
if (myPrepareSuccessfulSwingThreadCallback != null && conflictDescriptions.size() > 0) {
ConflictsDialog dialog = new ConflictsDialog(myProject, conflictDescriptions);
dialog.show();
if (!dialog.isOK()) return false;
}
if (myChangeInfo.isReturnTypeChanged) {
askToRemoveCovariantOverriders (usagesSet);
}
refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()]));
prepareSuccessful();
return true;
}
private void addInaccessibilityDescriptions(Set<UsageInfo> usages, Set<String> conflictDescriptions) throws IncorrectOperationException {
PsiMethod method = myChangeInfo.getMethod();
PsiModifierList modifierList = (PsiModifierList)method.getModifierList().copy();
RefactoringUtil.setVisibility(modifierList, myNewVisibility);
for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext();) {
UsageInfo usageInfo = iterator.next();
PsiElement element = usageInfo.getElement();
if (element != null) {
if (element instanceof PsiReferenceExpression) {
PsiClass accessObjectClass = null;
PsiExpression qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
if (qualifier != null) {
accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement();
}
if (!element.getManager().getResolveHelper().isAccessible(method, modifierList, element, accessObjectClass, null)) {
String message =
RefactoringBundle.message("0.with.1.visibility.is.not.accesible.from.2",
ConflictsUtil.getDescription(method, true),
myNewVisibility,
ConflictsUtil.getDescription(ConflictsUtil.getContainer(element), true));
conflictDescriptions.add(message);
if (!needToChangeCalls()) {
iterator.remove();
}
}
}
}
}
}
private void askToRemoveCovariantOverriders(Set<UsageInfo> usages) {
if (myManager.getEffectiveLanguageLevel().compareTo(LanguageLevel.JDK_1_5) >= 0) {
List<UsageInfo> covariantOverriderInfos = new ArrayList<UsageInfo>();
for (UsageInfo usageInfo : usages) {
if (usageInfo instanceof OverriderUsageInfo) {
final OverriderUsageInfo info = (OverriderUsageInfo)usageInfo;
PsiMethod overrider = info.getElement();
PsiMethod baseMethod = info.getBaseMethod();
PsiSubstitutor substitutor = calculateSubstitutor(overrider, baseMethod);
PsiType type;
try {
type = substitutor.substitute(myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager));
}
catch (IncorrectOperationException e) {
LOG.error(e);
return;
}
if (type.isAssignableFrom(overrider.getReturnType())) {
covariantOverriderInfos.add(usageInfo);
}
}
}
if (covariantOverriderInfos.size() > 0) {
if (ApplicationManager.getApplication().isUnitTestMode() ||
Messages.showYesNoDialog(myProject, RefactoringBundle.message("do.you.want.to.process.overriding.methods.with.covariant.return.type"),
ChangeSignatureHandler.REFACTORING_NAME, Messages.getQuestionIcon())
!= DialogWrapper.OK_EXIT_CODE) {
for (UsageInfo usageInfo : covariantOverriderInfos) {
usages.remove(usageInfo);
}
}
}
}
}
protected void performRefactoring(UsageInfo[] usages) {
PsiElementFactory factory = myManager.getElementFactory();
try {
if (myChangeInfo.isNameChanged) {
myChangeInfo.newNameIdentifier = factory.createIdentifier(myChangeInfo.newName);
}
if (myChangeInfo.isReturnTypeChanged) {
myChangeInfo.newTypeElement = myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager);
}
if (myGenerateDelegate) {
generateDelegate();
}
for (UsageInfo usage : usages) {
if (usage instanceof CallerUsageInfo) {
final CallerUsageInfo callerUsageInfo = (CallerUsageInfo)usage;
processCallerMethod(callerUsageInfo.getMethod(), null, callerUsageInfo.isToInsertParameter(),
callerUsageInfo.isToInsertException());
}
else if (usage instanceof OverriderUsageInfo) {
OverriderUsageInfo info = (OverriderUsageInfo)usage;
final PsiMethod method = info.getElement();
final PsiMethod baseMethod = info.getBaseMethod();
if (info.isOriginalOverrider()) {
processPrimaryMethod(method, baseMethod, false);
}
else {
processCallerMethod(method, baseMethod, info.isToInsertArgs(), info.isToCatchExceptions());
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
processPrimaryMethod(myChangeInfo.getMethod(), null, true);
List<UsageInfo> postponedUsages = new ArrayList<UsageInfo>();
for (UsageInfo usage : usages) {
if (usage.getElement() == null) continue;
if (usage instanceof DefaultConstructorImplicitUsageInfo) {
final DefaultConstructorImplicitUsageInfo defConstructorUsage = (DefaultConstructorImplicitUsageInfo)usage;
addSuperCall(defConstructorUsage.getConstructor(), defConstructorUsage.getBaseConstructor());
}
else if (usage instanceof NoConstructorClassUsageInfo) {
addDefaultConstructor(((NoConstructorClassUsageInfo)usage).getPsiClass());
}
else if (usage.getElement() instanceof PsiJavaCodeReferenceElement) {
if (usage instanceof MethodCallUsageInfo) {
final MethodCallUsageInfo methodCallInfo = (MethodCallUsageInfo)usage;
processMethodUsage(methodCallInfo.getElement(), myChangeInfo, methodCallInfo.isToChangeArguments(),
methodCallInfo.isToCatchExceptions(), methodCallInfo.getReferencedMethod());
}
else {
String newName = ((MyParameterUsageInfo)usage).newParameterName;
String oldName = ((MyParameterUsageInfo)usage).oldParameterName;
processParameterUsage((PsiReferenceExpression)usage.getElement(), oldName, newName);
}
}
else if (usage.getElement() instanceof PsiEnumConstant) {
fixActualArgumentsList(((PsiEnumConstant)usage.getElement()).getArgumentList(), myChangeInfo, true);
}
else if (!(usage instanceof OverriderUsageInfo)) {
postponedUsages.add(usage);
}
}
for (UsageInfo usageInfo : postponedUsages) {
PsiElement element = usageInfo.getElement();
if (element == null) continue;
PsiReference reference = usageInfo instanceof MoveRenameUsageInfo ?
((MoveRenameUsageInfo)usageInfo).getReference() :
element.getReference();
if (reference != null) {
PsiElement target = null;
if (usageInfo instanceof MyParameterUsageInfo) {
String newParameterName = ((MyParameterUsageInfo)usageInfo).newParameterName;
PsiParameter[] newParams = myChangeInfo.getMethod().getParameterList().getParameters();
for (PsiParameter newParam : newParams) {
if (newParam.getName().equals(newParameterName)) {
target = newParam;
break;
}
}
}
else {
target = myChangeInfo.getMethod();
}
if (target != null) {
reference.bindToElement(target);
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private void generateDelegate() throws IncorrectOperationException {
final PsiMethod delegate = (PsiMethod)myChangeInfo.getMethod().copy();
final PsiClass targetClass = myChangeInfo.getMethod().getContainingClass();
LOG.assertTrue(!targetClass.isInterface());
makeEmptyBody(delegate);
final PsiCallExpression callExpression = addDelegatingCallTemplate(delegate);
addDelegateArguments(callExpression);
targetClass.addBefore(delegate, myChangeInfo.getMethod());
}
private void addDelegateArguments(final PsiCallExpression callExpression) throws IncorrectOperationException {
final ParameterInfo[] newParms = myChangeInfo.newParms;
for (int i = 0; i < newParms.length; i++) {
ParameterInfo newParm = newParms[i];
final PsiExpression actualArg;
if (newParm.oldParameterIndex >= 0) {
actualArg = myFactory.createExpressionFromText(myChangeInfo.oldParameterNames[newParm.oldParameterIndex], callExpression);
}
else {
actualArg = myChangeInfo.defaultValues[i];
}
callExpression.getArgumentList().add(actualArg);
}
}
private void makeEmptyBody(final PsiMethod delegate) throws IncorrectOperationException {
PsiCodeBlock body = delegate.getBody();
if (body != null) {
body.replace(myFactory.createCodeBlock());
}
else {
delegate.add(myFactory.createCodeBlock());
}
delegate.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);
}
private PsiCallExpression addDelegatingCallTemplate(final PsiMethod delegate) throws IncorrectOperationException {
final PsiCallExpression callExpression;
PsiCodeBlock body = delegate.getBody();
assert body != null;
if (delegate.isConstructor()) {
PsiElement callStatement = myFactory.createStatementFromText("this();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
} else {
if (PsiType.VOID.equals(delegate.getReturnType())) {
PsiElement callStatement = myFactory.createStatementFromText(myChangeInfo.newName + "();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
}
else {
PsiElement callStatement = myFactory.createStatementFromText("return " + myChangeInfo.newName + "();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiReturnStatement) callStatement).getReturnValue();
}
}
return callExpression;
}
private void addDefaultConstructor(PsiClass aClass) throws IncorrectOperationException {
if (!(aClass instanceof PsiAnonymousClass)) {
PsiMethod defaultConstructor = myFactory.createMethodFromText(aClass.getName() + "(){}", aClass);
defaultConstructor = (PsiMethod) CodeStyleManager.getInstance(myProject).reformat(defaultConstructor);
defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
defaultConstructor.getModifierList().setModifierProperty(VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
addSuperCall(defaultConstructor, null);
} else {
final PsiElement parent = aClass.getParent();
if (parent instanceof PsiNewExpression) {
final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
fixActualArgumentsList(argumentList, myChangeInfo, true);
}
}
}
private void addSuperCall(PsiMethod constructor, PsiMethod callee) throws IncorrectOperationException {
PsiExpressionStatement superCall = (PsiExpressionStatement) myFactory.createStatementFromText("super();", constructor);
PsiCodeBlock body = constructor.getBody();
assert body != null;
PsiStatement[] statements = body.getStatements();
if (statements.length > 0) {
superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]);
} else {
superCall = (PsiExpressionStatement) body.add(superCall);
}
PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression();
processMethodUsage(callExpression.getMethodExpression(), myChangeInfo, true, false, callee);
}
private PsiParameter createNewParameter(ParameterInfo newParm,
PsiSubstitutor substitutor) throws IncorrectOperationException {
final PsiElementFactory factory = PsiManager.getInstance(myProject).getElementFactory();
final PsiType type = substitutor.substitute(newParm.createType(myChangeInfo.getMethod().getParameterList(), myManager));
return factory.createParameter(newParm.getName(), type);
}
protected String getCommandName() {
return RefactoringBundle.message("changing.signature.of.0", UsageViewUtil.getDescriptiveName(myChangeInfo.getMethod()));
}
private void processMethodUsage(PsiElement ref,
ChangeInfo changeInfo,
boolean toChangeArguments,
boolean toCatchExceptions,
PsiMethod callee)
throws IncorrectOperationException {
if (changeInfo.isNameChanged) {
if (ref instanceof PsiJavaCodeReferenceElement) {
PsiElement last = ((PsiJavaCodeReferenceElement)ref).getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(changeInfo.oldName)) {
last.replace(changeInfo.newNameIdentifier);
}
}
}
final PsiMethod caller = RefactoringUtil.getEnclosingMethod(ref);
if (toChangeArguments) {
final PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(ref);
boolean toInsertDefaultValue = !myPropagateParametersMethods.contains(caller);
if (toInsertDefaultValue && ref instanceof PsiReferenceExpression) {
final PsiExpression qualifierExpression = ((PsiReferenceExpression) ref).getQualifierExpression();
if (qualifierExpression instanceof PsiSuperExpression) {
toInsertDefaultValue = false;
}
}
fixActualArgumentsList(list, changeInfo, toInsertDefaultValue);
}
if (toCatchExceptions) {
if (!(ref instanceof PsiReferenceExpression && ((PsiReferenceExpression)ref).getQualifierExpression() instanceof PsiSuperExpression)) {
if (needToCatchExceptions(caller)) {
PsiClassType[] newExceptions = callee != null ? getCalleeChangedExceptionInfo(callee) : getPrimaryChangedExceptionInfo(changeInfo);
fixExceptions(ref, newExceptions);
}
}
}
}
private static PsiClassType[] getCalleeChangedExceptionInfo(final PsiMethod callee) {
return callee.getThrowsList().getReferencedTypes(); //Callee method's throws list is already modified!
}
private PsiClassType[] getPrimaryChangedExceptionInfo(ChangeInfo changeInfo) throws IncorrectOperationException {
PsiClassType[] newExceptions = new PsiClassType[changeInfo.newExceptions.length];
for (int i = 0; i < newExceptions.length; i++) {
newExceptions[i] = (PsiClassType)changeInfo.newExceptions[i].myType.getType(myChangeInfo.getMethod(), myManager); //context really does not matter here
}
return newExceptions;
}
private void fixExceptions(PsiElement ref, PsiClassType[] newExceptions) throws IncorrectOperationException {
//methods' throws lists are already modified, may use ExceptionUtil.collectUnhandledExceptions
newExceptions = filterCheckedExceptions(newExceptions);
PsiElement context = PsiTreeUtil.getParentOfType(ref, PsiTryStatement.class, PsiMethod.class);
if (context instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)context;
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
//Remove unused catches
PsiClassType[] classes = ExceptionUtil.collectUnhandledExceptions(tryBlock, tryBlock);
PsiParameter[] catchParameters = tryStatement.getCatchBlockParameters();
for (PsiParameter parameter : catchParameters) {
final PsiType caughtType = parameter.getType();
if (!(caughtType instanceof PsiClassType)) continue;
if (ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)caughtType)) continue;
if (!isCatchParameterRedundant((PsiClassType)caughtType, classes)) continue;
parameter.getParent().delete(); //delete catch section
}
PsiClassType[] exceptionsToAdd = filterUnhandledExceptions(newExceptions, tryBlock);
addExceptions(exceptionsToAdd, tryStatement);
adjustPossibleEmptyTryStatement(tryStatement);
}
else {
newExceptions = filterUnhandledExceptions(newExceptions, ref);
if (newExceptions.length > 0) {
//Add new try statement
PsiElementFactory elementFactory = myManager.getElementFactory();
PsiTryStatement tryStatement = (PsiTryStatement)elementFactory.createStatementFromText("try {} catch (Exception e) {}", null);
PsiStatement anchor = PsiTreeUtil.getParentOfType(ref, PsiStatement.class);
LOG.assertTrue(anchor != null);
tryStatement.getTryBlock().add(anchor);
tryStatement = (PsiTryStatement)anchor.getParent().addAfter(tryStatement, anchor);
addExceptions(newExceptions, tryStatement);
anchor.delete();
tryStatement.getCatchSections()[0].delete(); //Delete dummy catch section
}
}
}
private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exceptionType : exceptions) {
if (!ExceptionUtil.isUncheckedException(exceptionType)) result.add(exceptionType);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static void adjustPossibleEmptyTryStatement(PsiTryStatement tryStatement) throws IncorrectOperationException {
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
if (tryBlock != null) {
if (tryStatement.getCatchSections().length == 0 &&
tryStatement.getFinallyBlock() == null) {
PsiElement firstBodyElement = tryBlock.getFirstBodyElement();
if (firstBodyElement != null) {
tryStatement.getParent().addRangeAfter(firstBodyElement, tryBlock.getLastBodyElement(), tryStatement);
}
tryStatement.delete();
}
}
}
private static void addExceptions(PsiClassType[] exceptionsToAdd, PsiTryStatement tryStatement) throws IncorrectOperationException {
for (PsiClassType type : exceptionsToAdd) {
final CodeStyleManager styleManager = tryStatement.getManager().getCodeStyleManager();
String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type).names[0];
name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
PsiCatchSection catchSection = tryStatement.getManager().getElementFactory().createCatchSection(type, name, tryStatement);
tryStatement.add(catchSection);
}
}
private void fixPrimaryThrowsLists(PsiMethod method, PsiClassType[] newExceptions) throws IncorrectOperationException {
PsiElementFactory elementFactory = myManager.getElementFactory();
PsiJavaCodeReferenceElement[] refs = new PsiJavaCodeReferenceElement[newExceptions.length];
for (int i = 0; i < refs.length; i++) {
refs[i] = elementFactory.createReferenceElementByType(newExceptions[i]);
}
PsiReferenceList throwsList = elementFactory.createReferenceList(refs);
replaceThrowsList(method, throwsList);
}
private void replaceThrowsList(PsiMethod method, PsiReferenceList throwsList) throws IncorrectOperationException {
PsiReferenceList methodThrowsList = (PsiReferenceList)method.getThrowsList().replace(throwsList);
methodThrowsList = (PsiReferenceList)myManager.getCodeStyleManager().shortenClassReferences(methodThrowsList);
myManager.getCodeStyleManager().reformatRange(method, method.getParameterList().getTextRange().getEndOffset(),
methodThrowsList.getTextRange().getEndOffset());
}
private static PsiClassType[] filterUnhandledExceptions(PsiClassType[] exceptions, PsiElement place) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exception : exceptions) {
if (!ExceptionUtil.isHandled(exception, place)) result.add(exception);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static boolean isCatchParameterRedundant (PsiClassType catchParamType, PsiType[] thrownTypes) {
for (PsiType exceptionType : thrownTypes) {
if (exceptionType.isConvertibleFrom(catchParamType)) return false;
}
return true;
}
private static int getNonVarargCount(ChangeInfo changeInfo, PsiExpression[] args) {
if (!changeInfo.wasVararg) return args.length;
return changeInfo.oldParameterTypes.length - 1;
}
//This methods works equally well for primary usages as well as for propagated callers' usages
private void fixActualArgumentsList(PsiExpressionList list,
ChangeInfo changeInfo,
boolean toInsertDefaultValue) throws IncorrectOperationException {
final PsiElementFactory factory = list.getManager().getElementFactory();
if (changeInfo.isParameterSetOrOrderChanged) {
if (changeInfo.isPropagationEnabled) {
final ParameterInfo[] createdParmsInfo = changeInfo.getCreatedParmsInfoWithoutVarargs();
for (ParameterInfo info : createdParmsInfo) {
PsiExpression newArg;
if (toInsertDefaultValue) {
newArg = createDefaultValue(factory, info, list);
}
else {
newArg = factory.createExpressionFromText(info.getName(), list);
}
list.add(newArg);
}
}
else {
final PsiExpression[] args = list.getExpressions();
final int nonVarargCount = getNonVarargCount(changeInfo, args);
final int varargCount = args.length - nonVarargCount;
final int newArgsLength;
final int newNonVarargCount;
if (changeInfo.retainsVarargs) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount + varargCount;
}
else if (changeInfo.obtainsVarags) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount;
}
else {
newNonVarargCount = changeInfo.newParms.length;
newArgsLength = changeInfo.newParms.length;
}
final PsiExpression[] newArgs = new PsiExpression[newArgsLength];
for (int i = 0; i < newNonVarargCount; i++) {
final ParameterInfo info = changeInfo.newParms[i];
final int index = info.oldParameterIndex;
if (index >= 0) {
newArgs[i] = args[index];
} else {
if (toInsertDefaultValue) {
newArgs[i] = createDefaultValue(factory, info, list);
} else {
newArgs[i] = factory.createExpressionFromText(info.getName(), list);
}
}
}
final int newVarargCount = newArgsLength - newNonVarargCount;
LOG.assertTrue(newVarargCount == 0 || newVarargCount == varargCount);
for (int i = 0; i < newVarargCount; i++) {
newArgs[newNonVarargCount + i] = args[nonVarargCount + i];
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newArgs), ExpressionList.INSTANCE, changeInfo.toRemoveParm);
}
}
}
private PsiExpression createDefaultValue(final PsiElementFactory factory, final ParameterInfo info, final PsiExpressionList list)
throws IncorrectOperationException {
if (info.useAnySingleVariable) {
final PsiResolveHelper resolveHelper = list.getManager().getResolveHelper();
final PsiType type = info.getTypeWrapper().getType(myChangeInfo.getMethod(), myManager);
final VariablesProcessor processor = new VariablesProcessor(false) {
protected boolean check(PsiVariable var, PsiSubstitutor substitutor) {
if (var instanceof PsiField && !resolveHelper.isAccessible((PsiField)var, list, null)) return false;
final PsiType varType = substitutor.substitute(var.getType());
return type.isAssignableFrom(varType);
}
public boolean execute(PsiElement pe, PsiSubstitutor substitutor) {
super.execute(pe, substitutor);
return size() < 2;
}
};
PsiScopesUtil.treeWalkUp(processor, list, null);
if (processor.size() == 1) {
final PsiVariable result = processor.getResult(0);
return factory.createExpressionFromText(result.getName(), list);
}
}
return factory.createExpressionFromText(info.defaultValue, list);
}
private static void addParameterUsages(PsiParameter parameter,
ArrayList<UsageInfo> results,
ParameterInfo info) {
PsiManager manager = parameter.getManager();
PsiSearchHelper helper = manager.getSearchHelper();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
PsiReference[] parmRefs = helper.findReferences(parameter, projectScope, false);
for (PsiReference psiReference : parmRefs) {
PsiElement parmRef = psiReference.getElement();
UsageInfo usageInfo = new MyParameterUsageInfo(parmRef, parameter.getName(), info.getName());
results.add(usageInfo);
}
}
private void processCallerMethod(PsiMethod caller,
PsiMethod baseMethod,
boolean toInsertParams,
boolean toInsertThrows) throws IncorrectOperationException {
LOG.assertTrue(toInsertParams || toInsertThrows);
if (toInsertParams) {
List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
newParameters.addAll(Arrays.asList(caller.getParameterList().getParameters()));
final ParameterInfo[] primaryNewParms = myChangeInfo.newParms;
PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(caller, baseMethod);
for (ParameterInfo info : primaryNewParms) {
if (info.oldParameterIndex < 0) newParameters.add(createNewParameter(info, substitutor));
}
PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
}
if (toInsertThrows) {
List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
final PsiReferenceList throwsList = caller.getThrowsList();
newThrowns.addAll(Arrays.asList(throwsList.getReferenceElements()));
final ThrownExceptionInfo[] primaryNewExns = myChangeInfo.newExceptions;
for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
if (thrownExceptionInfo.oldIndex < 0) {
final PsiClassType type = (PsiClassType)thrownExceptionInfo.createType(caller, myManager);
final PsiJavaCodeReferenceElement ref = caller.getManager().getElementFactory().createReferenceElementByType(type);
newThrowns.add(ref);
}
}
PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
ChangeSignatureUtil.synchronizeList(throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
}
}
private void processPrimaryMethod(PsiMethod method,
PsiMethod baseMethod,
boolean isOriginal) throws IncorrectOperationException {
PsiElementFactory factory = method.getManager().getElementFactory();
if (myChangeInfo.isVisibilityChanged) {
PsiModifierList modifierList = method.getModifierList();
final String highestVisibility = isOriginal ?
myNewVisibility :
VisibilityUtil.getHighestVisibility(myNewVisibility, VisibilityUtil.getVisibilityModifier(modifierList));
RefactoringUtil.setVisibility(modifierList, highestVisibility);
}
if (myChangeInfo.isNameChanged) {
final EjbMethodRole role = com.intellij.javaee.ejb.role.EjbRolesUtil.getEjbRolesUtil().getEjbRole(method);
if (role instanceof EjbImplMethodRole && myChangeInfo.ejbRole instanceof EjbDeclMethodRole) {
EjbDeclMethodRole declRole = (EjbDeclMethodRole) myChangeInfo.ejbRole;
String newName = myChangeInfo.newName;
for (PsiMethod oldMethod : declRole.suggestImplementations()) {
if (oldMethod.getName().equals(method.getName())) {
PsiMethod newDeclMethod = (PsiMethod)method.copy();
newDeclMethod.getNameIdentifier().replace(myChangeInfo.newNameIdentifier);
newName = EjbPsiMethodUtil.suggestImplNames(newDeclMethod.getName(), declRole.getType(), declRole.getEnterpriseBean())[0];
break;
}
}
method.getNameIdentifier().replace(factory.createIdentifier(newName));
} else {
method.getNameIdentifier().replace(myChangeInfo.newNameIdentifier);
}
}
final PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(method, baseMethod);
if (myChangeInfo.isReturnTypeChanged) {
final PsiType returnType = substitutor.substitute(myChangeInfo.newTypeElement);
method.getReturnTypeElement().replace(factory.createTypeElement(returnType));
}
PsiParameterList list = method.getParameterList();
PsiParameter[] parameters = list.getParameters();
PsiParameter[] newParms = new PsiParameter[myChangeInfo.newParms.length];
for (int i = 0; i < newParms.length; i++) {
ParameterInfo info = myChangeInfo.newParms[i];
int index = info.oldParameterIndex;
if (index >= 0) {
PsiParameter parameter = parameters[index];
newParms[i] = parameter;
String oldName = myChangeInfo.oldParameterNames[index];
if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) {
PsiIdentifier newIdentifier = factory.createIdentifier(info.getName());
parameter.getNameIdentifier().replace(newIdentifier);
}
String oldType = myChangeInfo.oldParameterTypes[index];
if (!oldType.equals(info.getTypeText())) {
parameter.normalizeDeclaration();
PsiType newType = substitutor.substitute(info.createType(myChangeInfo.getMethod().getParameterList(), myManager));
parameter.getTypeElement().replace(factory.createTypeElement(newType));
}
} else {
newParms[i] = createNewParameter(info, substitutor);
}
}
resolveParameterVsFieldsConflicts(newParms, method, list, myChangeInfo.toRemoveParm);
fixJavadocsForChangedMethod(method);
if (myChangeInfo.isExceptionSetOrOrderChanged) {
final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(myChangeInfo);
fixPrimaryThrowsLists(method, newExceptions);
}
}
private static void resolveParameterVsFieldsConflicts(final PsiParameter[] newParms,
final PsiMethod method,
final PsiParameterList list,
boolean[] toRemoveParm) throws IncorrectOperationException {
List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>();
for (PsiParameter parameter : newParms) {
conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody()));
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm);
for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) {
fieldConflictsResolver.fix();
}
}
private static PsiSubstitutor calculateSubstitutor(PsiMethod derivedMethod, PsiMethod baseMethod) {
PsiSubstitutor substitutor;
if (derivedMethod.getManager().areElementsEquivalent(derivedMethod, baseMethod)) {
substitutor = PsiSubstitutor.EMPTY;
} else {
final PsiClass baseClass = baseMethod.getContainingClass();
final PsiClass derivedClass = derivedMethod.getContainingClass();
if(baseClass != null && derivedClass != null && InheritanceUtil.isInheritorOrSelf(derivedClass, baseClass, true)) {
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, derivedClass, PsiSubstitutor.EMPTY);
final MethodSignature superMethodSignature = baseMethod.getSignature(superClassSubstitutor);
final MethodSignature methodSignature = derivedMethod.getSignature(PsiSubstitutor.EMPTY);
final PsiSubstitutor superMethodSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature, superMethodSignature);
substitutor = superMethodSubstitutor != null ? superMethodSubstitutor : superClassSubstitutor;
} else {
substitutor = PsiSubstitutor.EMPTY;
}
}
return substitutor;
}
private static void processParameterUsage(PsiReferenceExpression ref, String oldName, String newName)
throws IncorrectOperationException {
PsiElement last = ref.getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(oldName)) {
PsiElementFactory factory = ref.getManager().getElementFactory();
PsiIdentifier newNameIdentifier = factory.createIdentifier(newName);
last.replace(newNameIdentifier);
}
}
private static class MyParameterUsageInfo extends UsageInfo {
final String oldParameterName;
final String newParameterName;
public MyParameterUsageInfo(PsiElement element, String oldParameterName, String newParameterName) {
super(element);
this.oldParameterName = oldParameterName;
this.newParameterName = newParameterName;
}
}
public static PsiElement normalizeResolutionContext(PsiElement resolutionContext) {
PsiElement result = PsiTreeUtil.getNonStrictParentOfType(resolutionContext, PsiStatement.class, PsiClass.class, PsiFile.class);
if (result != null) return result;
return resolutionContext;
}
private static class RenamedParameterCollidesWithLocalUsageInfo extends UnresolvableCollisionUsageInfo {
private final PsiElement myCollidingElement;
private final PsiMethod myMethod;
public RenamedParameterCollidesWithLocalUsageInfo(PsiParameter parameter, PsiElement collidingElement, PsiMethod method) {
super(parameter, collidingElement);
myCollidingElement = collidingElement;
myMethod = method;
}
public String getDescription() {
return RefactoringBundle.message("there.is.already.a.0.in.the.1.it.will.conflict.with.the.renamed.parameter",
ConflictsUtil.getDescription(myCollidingElement, true),
ConflictsUtil.getDescription(myMethod, true));
}
}
private void fixJavadocsForChangedMethod(PsiMethod method) throws IncorrectOperationException {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final ParameterInfo[] newParms = myChangeInfo.newParms;
LOG.assertTrue(parameters.length == newParms.length);
final Set<PsiParameter> newParameters = new HashSet<PsiParameter>();
for (int i = 0; i < newParms.length; i++) {
ParameterInfo newParm = newParms[i];
if (newParm.oldParameterIndex < 0 ||
!newParm.getName().equals(myChangeInfo.oldParameterNames[newParm.oldParameterIndex])) {
newParameters.add(parameters[i]);
}
}
RefactoringUtil.fixJavadocsForParams(method, newParameters);
}
private static class ExpressionList implements ChangeSignatureUtil.ChildrenGenerator<PsiExpressionList, PsiExpression> {
public static final ExpressionList INSTANCE = new ExpressionList();
public List<PsiExpression> getChildren(PsiExpressionList psiExpressionList) {
return Arrays.asList(psiExpressionList.getExpressions());
}
}
private static class ParameterList implements ChangeSignatureUtil.ChildrenGenerator<PsiParameterList, PsiParameter> {
public static final ParameterList INSTANCE = new ParameterList();
public List<PsiParameter> getChildren(PsiParameterList psiParameterList) {
return Arrays.asList(psiParameterList.getParameters());
}
}
private static class ThrowsList implements ChangeSignatureUtil.ChildrenGenerator<PsiReferenceList, PsiJavaCodeReferenceElement> {
public static final ThrowsList INSTANCE = new ThrowsList();
public List<PsiJavaCodeReferenceElement> getChildren(PsiReferenceList throwsList) {
return Arrays.asList(throwsList.getReferenceElements());
}
}
}
|
refactoring/impl/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java
|
/**
* created at Sep 17, 2001
* @author Jeka
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.util.*;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo;
import com.intellij.refactoring.ui.ConflictsDialog;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorUsageCollector;
import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import com.intellij.javaee.ejb.role.*;
import com.intellij.javaee.model.common.ejb.EjbPsiMethodUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class ChangeSignatureProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.changeSignature.ChangeSignatureProcessor");
private final String myNewVisibility;
private ChangeInfo myChangeInfo;
private PsiManager myManager;
private PsiElementFactory myFactory;
private final boolean myGenerateDelegate;
private final Set<PsiMethod> myPropagateParametersMethods;
private final Set<PsiMethod> myPropagateExceptionsMethods;
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
String newVisibility,
String newName,
PsiType newType,
@NotNull ParameterInfo[] parameterInfo) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, null, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
String newVisibility,
String newName,
PsiType newType,
ParameterInfo[] parameterInfo,
ThrownExceptionInfo[] exceptionInfos) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, exceptionInfos, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
boolean generateDelegate,
String newVisibility,
String newName,
CanonicalTypes.Type newType,
@NotNull ParameterInfo[] parameterInfo,
ThrownExceptionInfo[] thrownExceptions,
Set<PsiMethod> propagateParametersMethods,
Set<PsiMethod> propagateExceptionsMethods) {
super(project);
myManager = PsiManager.getInstance(project);
myFactory = myManager.getElementFactory();
myGenerateDelegate = generateDelegate;
myPropagateParametersMethods = propagateParametersMethods != null ? propagateParametersMethods : new HashSet<PsiMethod>();
myPropagateExceptionsMethods = propagateExceptionsMethods != null ? propagateExceptionsMethods : new HashSet<PsiMethod>();
LOG.assertTrue(method.isValid());
if (newVisibility == null) {
myNewVisibility = VisibilityUtil.getVisibilityModifier(method.getModifierList());
} else {
myNewVisibility = newVisibility;
}
myChangeInfo = new ChangeInfo(myNewVisibility, method, newName, newType, parameterInfo, thrownExceptions);
LOG.assertTrue(myChangeInfo.getMethod().isValid());
}
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
return new ChangeSignatureViewDescriptor(myChangeInfo.getMethod());
}
@NotNull
protected UsageInfo[] findUsages() {
ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
final PsiMethod method = myChangeInfo.getMethod();
findSimpleUsages(method, result);
findEjbUsages(result);
final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
private void findSimpleUsages(final PsiMethod method, final ArrayList<UsageInfo> result) {
PsiMethod[] overridingMethods = findSimpleUsagesWithoutParameters(method, result, true, true, true);
findUsagesInCallers (result);
//Parameter name changes are not propagated
findParametersUsage(method, result, overridingMethods);
}
private PsiMethod[] findSimpleUsagesWithoutParameters(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isToModifyArgs,
boolean isToThrowExceptions,
boolean isOriginal) {
PsiManager manager = method.getManager();
PsiSearchHelper helper = manager.getSearchHelper();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myProject);
PsiMethod[] overridingMethods = helper.findOverridingMethods(method, projectScope, true);
for (PsiMethod overridingMethod : overridingMethods) {
result.add(new OverriderUsageInfo(overridingMethod, method, isOriginal, isToModifyArgs, isToThrowExceptions));
}
boolean needToChangeCalls = !myGenerateDelegate && (myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged || myChangeInfo.isVisibilityChanged/*for checking inaccessible*/);
if (needToChangeCalls) {
List<PsiReference> l = new ArrayList<PsiReference>();
PsiReference[] refs = helper.findReferencesIncludingOverriding(method, projectScope, true);
for (PsiReference reference : refs) {
l.add(reference);
}
int parameterCount = method.getParameterList().getParameters().length;
for (PsiReference ref : l) {
PsiElement element = ref.getElement();
boolean isToCatchExceptions = isToThrowExceptions && needToCatchExceptions(RefactoringUtil.getEnclosingMethod(element));
if (!isToCatchExceptions) {
if (RefactoringUtil.isMethodUsage(element)) {
PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(element);
if (!method.isVarArgs() && list.getExpressions().length != parameterCount) continue;
}
}
if (RefactoringUtil.isMethodUsage(element)) {
result.add(new MethodCallUsageInfo(element, isToModifyArgs, isToCatchExceptions));
}
else {
result.add(new MoveRenameUsageInfo(element, ref, method));
}
}
if (method.isConstructor() && parameterCount == 0) {
RefactoringUtil.visitImplicitConstructorUsages(method.getContainingClass(),
new DefaultConstructorUsageCollector(result));
}
} else if (myChangeInfo.isParameterTypesChanged) {
PsiReference[] refs = helper.findReferencesIncludingOverriding(method, projectScope, true);
for (PsiReference reference : refs) {
if (reference.getElement() instanceof PsiDocTagValue) { //types are mentioned in e.g @link, see SCR 40895
result.add(new UsageInfo(reference.getElement()));
}
}
}
// Conflicts
detectLocalsCollisionsInMethod(method, result, isOriginal);
for (final PsiMethod overridingMethod : overridingMethods) {
detectLocalsCollisionsInMethod(overridingMethod, result, isOriginal);
}
return overridingMethods;
}
private void findUsagesInCallers(final ArrayList<UsageInfo> usages) {
for (PsiMethod caller : myPropagateParametersMethods) {
usages.add(new CallerUsageInfo(caller, true, myPropagateExceptionsMethods.contains(caller)));
}
for (PsiMethod caller : myPropagateExceptionsMethods) {
usages.add(new CallerUsageInfo(caller, myPropagateParametersMethods.contains(caller), true));
}
Set<PsiMethod> merged = new HashSet<PsiMethod>();
merged.addAll(myPropagateParametersMethods);
merged.addAll(myPropagateExceptionsMethods);
for (final PsiMethod method : merged) {
findSimpleUsagesWithoutParameters(method, usages, myPropagateParametersMethods.contains(method),
myPropagateExceptionsMethods.contains(method), false);
}
}
private boolean needToChangeCalls() {
return myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged;
}
private boolean needToCatchExceptions(PsiMethod caller) {
return myChangeInfo.isExceptionSetOrOrderChanged && !myPropagateExceptionsMethods.contains(caller);
}
private void detectLocalsCollisionsInMethod(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isOriginal) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final Set<PsiParameter> deletedParameters = new HashSet<PsiParameter>();
if (isOriginal) {
deletedParameters.addAll(Arrays.asList(parameters));
for (ParameterInfo parameterInfo : myChangeInfo.newParms) {
if (parameterInfo.oldParameterIndex >= 0) {
deletedParameters.remove(parameters[parameterInfo.oldParameterIndex]);
}
}
}
for (ParameterInfo parameterInfo : myChangeInfo.newParms) {
final int oldParameterIndex = parameterInfo.oldParameterIndex;
final String newName = parameterInfo.getName();
if (oldParameterIndex >= 0) {
if (isOriginal) { //Name changes take place only in primary method
final PsiParameter parameter = parameters[oldParameterIndex];
if (!newName.equals(parameter.getName())) {
RenameUtil.visitLocalsCollisions(parameter, newName, method.getBody(), null, new RenameUtil.CollidingVariableVisitor() {
public void visitCollidingElement(final PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedParameters.contains(collidingVariable)) {
result.add(new RenamedParameterCollidesWithLocalUsageInfo(parameter, collidingVariable, method));
}
}
});
}
}
}
else {
RenameUtil.visitLocalsCollisions(method, newName, method.getBody(), null, new RenameUtil.CollidingVariableVisitor() {
public void visitCollidingElement(PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedParameters.contains(collidingVariable)) {
result.add(new NewParameterCollidesWithLocalUsageInfo(collidingVariable, collidingVariable, method));
}
}
});
}
}
}
private void findParametersUsage(final PsiMethod method, ArrayList<UsageInfo> result, PsiMethod[] overriders) {
PsiParameter[] parameters = method.getParameterList().getParameters();
for (ParameterInfo info : myChangeInfo.newParms) {
if (info.oldParameterIndex >= 0) {
PsiParameter parameter = parameters[info.oldParameterIndex];
if (!info.getName().equals(parameter.getName())) {
addParameterUsages(parameter, result, info);
for (PsiMethod overrider : overriders) {
PsiParameter parameter1 = overrider.getParameterList().getParameters()[info.oldParameterIndex];
if (parameter.getName().equals(parameter1.getName())) {
addParameterUsages(parameter1, result, info);
}
}
}
}
}
}
private void findEjbUsages(ArrayList<UsageInfo> result) {
if (!(myChangeInfo.ejbRole instanceof EjbDeclMethodRole)) return;
for (PsiMethod implementation : ((EjbDeclMethodRole) myChangeInfo.ejbRole).findAllImplementations()) {
result.add(new UsageInfo(implementation));
findSimpleUsages(implementation, result);
}
}
protected void refreshElements(PsiElement[] elements) {
boolean condition = elements.length == 1 && elements[0] instanceof PsiMethod;
LOG.assertTrue(condition);
myChangeInfo.updateMethod((PsiMethod) elements[0]);
}
private void addMethodConflicts(Collection<String> conflicts) {
String newMethodName = myChangeInfo.newName;
try {
PsiMethod prototype;
PsiManager manager = PsiManager.getInstance(myProject);
PsiElementFactory factory = manager.getElementFactory();
final PsiMethod method = myChangeInfo.getMethod();
final CanonicalTypes.Type returnType = myChangeInfo.newReturnType;
if (returnType != null) {
prototype = factory.createMethod(newMethodName, returnType.getType(method, manager));
}
else {
prototype = factory.createConstructor();
prototype.setName(newMethodName);
}
ParameterInfo[] parameters = myChangeInfo.newParms;
for (ParameterInfo info : parameters) {
final PsiType parameterType = info.createType(method, manager);
PsiParameter param = factory.createParameter(info.getName(), parameterType);
prototype.getParameterList().add(param);
}
ConflictsUtil.checkMethodConflicts(
method.getContainingClass(),
method,
prototype, conflicts);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
Set<String> conflictDescriptions = new HashSet<String>();
UsageInfo[] usagesIn = refUsages.get();
addMethodConflicts(conflictDescriptions);
conflictDescriptions.addAll(RenameUtil.getConflictDescriptions(usagesIn));
Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(usagesIn));
RenameUtil.removeConflictUsages(usagesSet);
if (myChangeInfo.isVisibilityChanged) {
try {
addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
if (myPrepareSuccessfulSwingThreadCallback != null && conflictDescriptions.size() > 0) {
ConflictsDialog dialog = new ConflictsDialog(myProject, conflictDescriptions);
dialog.show();
if (!dialog.isOK()) return false;
}
if (myChangeInfo.isReturnTypeChanged) {
askToRemoveCovariantOverriders (usagesSet);
}
refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()]));
prepareSuccessful();
return true;
}
private void addInaccessibilityDescriptions(Set<UsageInfo> usages, Set<String> conflictDescriptions) throws IncorrectOperationException {
PsiMethod method = myChangeInfo.getMethod();
PsiModifierList modifierList = (PsiModifierList)method.getModifierList().copy();
RefactoringUtil.setVisibility(modifierList, myNewVisibility);
for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext();) {
UsageInfo usageInfo = iterator.next();
PsiElement element = usageInfo.getElement();
if (element != null) {
if (element instanceof PsiReferenceExpression) {
PsiClass accessObjectClass = null;
PsiExpression qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
if (qualifier != null) {
accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement();
}
if (!element.getManager().getResolveHelper().isAccessible(method, modifierList, element, accessObjectClass, null)) {
String message =
RefactoringBundle.message("0.with.1.visibility.is.not.accesible.from.2",
ConflictsUtil.getDescription(method, true),
myNewVisibility,
ConflictsUtil.getDescription(ConflictsUtil.getContainer(element), true));
conflictDescriptions.add(message);
if (!needToChangeCalls()) {
iterator.remove();
}
}
}
}
}
}
private void askToRemoveCovariantOverriders(Set<UsageInfo> usages) {
if (myManager.getEffectiveLanguageLevel().compareTo(LanguageLevel.JDK_1_5) >= 0) {
List<UsageInfo> covariantOverriderInfos = new ArrayList<UsageInfo>();
for (UsageInfo usageInfo : usages) {
if (usageInfo instanceof OverriderUsageInfo) {
final OverriderUsageInfo info = (OverriderUsageInfo)usageInfo;
PsiMethod overrider = info.getElement();
PsiMethod baseMethod = info.getBaseMethod();
PsiSubstitutor substitutor = calculateSubstitutor(overrider, baseMethod);
PsiType type;
try {
type = substitutor.substitute(myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager));
}
catch (IncorrectOperationException e) {
LOG.error(e);
return;
}
if (type.isAssignableFrom(overrider.getReturnType())) {
covariantOverriderInfos.add(usageInfo);
}
}
}
if (covariantOverriderInfos.size() > 0) {
if (ApplicationManager.getApplication().isUnitTestMode() ||
Messages.showYesNoDialog(myProject, RefactoringBundle.message("do.you.want.to.process.overriding.methods.with.covariant.return.type"),
ChangeSignatureHandler.REFACTORING_NAME, Messages.getQuestionIcon())
!= DialogWrapper.OK_EXIT_CODE) {
for (UsageInfo usageInfo : covariantOverriderInfos) {
usages.remove(usageInfo);
}
}
}
}
}
protected void performRefactoring(UsageInfo[] usages) {
PsiElementFactory factory = myManager.getElementFactory();
try {
if (myChangeInfo.isNameChanged) {
myChangeInfo.newNameIdentifier = factory.createIdentifier(myChangeInfo.newName);
}
if (myChangeInfo.isReturnTypeChanged) {
myChangeInfo.newTypeElement = myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager);
}
if (myGenerateDelegate) {
generateDelegate();
}
for (UsageInfo usage : usages) {
if (usage instanceof CallerUsageInfo) {
final CallerUsageInfo callerUsageInfo = (CallerUsageInfo)usage;
processCallerMethod(callerUsageInfo.getMethod(), null, callerUsageInfo.isToInsertParameter(),
callerUsageInfo.isToInsertException());
}
else if (usage instanceof OverriderUsageInfo) {
OverriderUsageInfo info = (OverriderUsageInfo)usage;
final PsiMethod method = info.getElement();
final PsiMethod baseMethod = info.getBaseMethod();
if (info.isOriginalOverrider()) {
processPrimaryMethod(method, baseMethod, false);
}
else {
processCallerMethod(method, baseMethod, info.isToInsertArgs(), info.isToCatchExceptions());
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
processPrimaryMethod(myChangeInfo.getMethod(), null, true);
List<UsageInfo> postponedUsages = new ArrayList<UsageInfo>();
for (UsageInfo usage : usages) {
if (usage.getElement() == null) continue;
if (usage instanceof DefaultConstructorImplicitUsageInfo) {
final DefaultConstructorImplicitUsageInfo defConstructorUsage = (DefaultConstructorImplicitUsageInfo)usage;
addSuperCall(defConstructorUsage.getConstructor(), defConstructorUsage.getBaseConstructor());
}
else if (usage instanceof NoConstructorClassUsageInfo) {
addDefaultConstructor(((NoConstructorClassUsageInfo)usage).getPsiClass());
}
else if (usage.getElement() instanceof PsiJavaCodeReferenceElement) {
if (usage instanceof MethodCallUsageInfo) {
final MethodCallUsageInfo methodCallInfo = (MethodCallUsageInfo)usage;
processMethodUsage(methodCallInfo.getElement(), myChangeInfo, methodCallInfo.isToChangeArguments(),
methodCallInfo.isToCatchExceptions(), methodCallInfo.getReferencedMethod());
}
else {
String newName = ((MyParameterUsageInfo)usage).newParameterName;
String oldName = ((MyParameterUsageInfo)usage).oldParameterName;
processParameterUsage((PsiReferenceExpression)usage.getElement(), oldName, newName);
}
}
else if (usage.getElement() instanceof PsiEnumConstant) {
fixActualArgumentsList(((PsiEnumConstant)usage.getElement()).getArgumentList(), myChangeInfo, true);
}
else if (!(usage instanceof OverriderUsageInfo)) {
postponedUsages.add(usage);
}
}
for (UsageInfo usageInfo : postponedUsages) {
PsiElement element = usageInfo.getElement();
if (element == null) continue;
PsiReference reference = usageInfo instanceof MoveRenameUsageInfo ?
((MoveRenameUsageInfo)usageInfo).getReference() :
element.getReference();
if (reference != null) {
PsiElement target = null;
if (usageInfo instanceof MyParameterUsageInfo) {
String newParameterName = ((MyParameterUsageInfo)usageInfo).newParameterName;
PsiParameter[] newParams = myChangeInfo.getMethod().getParameterList().getParameters();
for (PsiParameter newParam : newParams) {
if (newParam.getName().equals(newParameterName)) {
target = newParam;
break;
}
}
}
else {
target = myChangeInfo.getMethod();
}
if (target != null) {
reference.bindToElement(target);
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private void generateDelegate() throws IncorrectOperationException {
final PsiMethod delegate = (PsiMethod)myChangeInfo.getMethod().copy();
final PsiClass targetClass = myChangeInfo.getMethod().getContainingClass();
LOG.assertTrue(!targetClass.isInterface());
makeEmptyBody(delegate);
final PsiCallExpression callExpression = addDelegatingCallTemplate(delegate);
addDelegateArguments(callExpression);
targetClass.addBefore(delegate, myChangeInfo.getMethod());
}
private void addDelegateArguments(final PsiCallExpression callExpression) throws IncorrectOperationException {
final ParameterInfo[] newParms = myChangeInfo.newParms;
for (int i = 0; i < newParms.length; i++) {
ParameterInfo newParm = newParms[i];
final PsiExpression actualArg;
if (newParm.oldParameterIndex >= 0) {
actualArg = myFactory.createExpressionFromText(myChangeInfo.oldParameterNames[newParm.oldParameterIndex], callExpression);
}
else {
actualArg = myChangeInfo.defaultValues[i];
}
callExpression.getArgumentList().add(actualArg);
}
}
private void makeEmptyBody(final PsiMethod delegate) throws IncorrectOperationException {
PsiCodeBlock body = delegate.getBody();
if (body != null) {
body.replace(myFactory.createCodeBlock());
}
else {
delegate.add(myFactory.createCodeBlock());
}
delegate.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);
}
private PsiCallExpression addDelegatingCallTemplate(final PsiMethod delegate) throws IncorrectOperationException {
final PsiCallExpression callExpression;
PsiCodeBlock body = delegate.getBody();
assert body != null;
if (delegate.isConstructor()) {
PsiElement callStatement = myFactory.createStatementFromText("this();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
} else {
if (PsiType.VOID.equals(delegate.getReturnType())) {
PsiElement callStatement = myFactory.createStatementFromText(myChangeInfo.newName + "();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
}
else {
PsiElement callStatement = myFactory.createStatementFromText("return " + myChangeInfo.newName + "();", null);
callStatement = CodeStyleManager.getInstance(myProject).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiReturnStatement) callStatement).getReturnValue();
}
}
return callExpression;
}
private void addDefaultConstructor(PsiClass aClass) throws IncorrectOperationException {
if (!(aClass instanceof PsiAnonymousClass)) {
PsiMethod defaultConstructor = myFactory.createMethodFromText(aClass.getName() + "(){}", aClass);
defaultConstructor = (PsiMethod) CodeStyleManager.getInstance(myProject).reformat(defaultConstructor);
defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
defaultConstructor.getModifierList().setModifierProperty(VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
addSuperCall(defaultConstructor, null);
} else {
final PsiElement parent = aClass.getParent();
if (parent instanceof PsiNewExpression) {
final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
fixActualArgumentsList(argumentList, myChangeInfo, true);
}
}
}
private void addSuperCall(PsiMethod constructor, PsiMethod callee) throws IncorrectOperationException {
PsiExpressionStatement superCall = (PsiExpressionStatement) myFactory.createStatementFromText("super();", constructor);
PsiCodeBlock body = constructor.getBody();
assert body != null;
PsiStatement[] statements = body.getStatements();
if (statements.length > 0) {
superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]);
} else {
superCall = (PsiExpressionStatement) body.add(superCall);
}
PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression();
processMethodUsage(callExpression.getMethodExpression(), myChangeInfo, true, false, callee);
}
private PsiParameter createNewParameter(ParameterInfo newParm,
PsiSubstitutor substitutor) throws IncorrectOperationException {
final PsiElementFactory factory = PsiManager.getInstance(myProject).getElementFactory();
final PsiType type = substitutor.substitute(newParm.createType(myChangeInfo.getMethod().getParameterList(), myManager));
return factory.createParameter(newParm.getName(), type);
}
protected String getCommandName() {
return RefactoringBundle.message("changing.signature.of.0", UsageViewUtil.getDescriptiveName(myChangeInfo.getMethod()));
}
private void processMethodUsage(PsiElement ref,
ChangeInfo changeInfo,
boolean toChangeArguments,
boolean toCatchExceptions,
PsiMethod callee)
throws IncorrectOperationException {
if (changeInfo.isNameChanged) {
if (ref instanceof PsiJavaCodeReferenceElement) {
PsiElement last = ((PsiJavaCodeReferenceElement)ref).getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(changeInfo.oldName)) {
last.replace(changeInfo.newNameIdentifier);
}
}
}
final PsiMethod caller = RefactoringUtil.getEnclosingMethod(ref);
if (toChangeArguments) {
final PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(ref);
boolean toInsertDefaultValue = !myPropagateParametersMethods.contains(caller);
if (toInsertDefaultValue && ref instanceof PsiReferenceExpression) {
final PsiExpression qualifierExpression = ((PsiReferenceExpression) ref).getQualifierExpression();
if (qualifierExpression instanceof PsiSuperExpression) {
toInsertDefaultValue = false;
}
}
fixActualArgumentsList(list, changeInfo, toInsertDefaultValue);
}
if (toCatchExceptions) {
if (!(ref instanceof PsiReferenceExpression && ((PsiReferenceExpression)ref).getQualifierExpression() instanceof PsiSuperExpression)) {
if (needToCatchExceptions(caller)) {
PsiClassType[] newExceptions = callee != null ? getCalleeChangedExceptionInfo(callee) : getPrimaryChangedExceptionInfo(changeInfo);
fixExceptions(ref, newExceptions);
}
}
}
}
private static PsiClassType[] getCalleeChangedExceptionInfo(final PsiMethod callee) {
return callee.getThrowsList().getReferencedTypes(); //Callee method's throws list is already modified!
}
private PsiClassType[] getPrimaryChangedExceptionInfo(ChangeInfo changeInfo) throws IncorrectOperationException {
PsiClassType[] newExceptions = new PsiClassType[changeInfo.newExceptions.length];
for (int i = 0; i < newExceptions.length; i++) {
newExceptions[i] = (PsiClassType)changeInfo.newExceptions[i].myType.getType(myChangeInfo.getMethod(), myManager); //context really does not matter here
}
return newExceptions;
}
private void fixExceptions(PsiElement ref, PsiClassType[] newExceptions) throws IncorrectOperationException {
//methods' throws lists are already modified, may use ExceptionUtil.collectUnhandledExceptions
newExceptions = filterCheckedExceptions(newExceptions);
PsiElement context = PsiTreeUtil.getParentOfType(ref, PsiTryStatement.class, PsiMethod.class);
if (context instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)context;
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
//Remove unused catches
PsiClassType[] classes = ExceptionUtil.collectUnhandledExceptions(tryBlock, tryBlock);
PsiParameter[] catchParameters = tryStatement.getCatchBlockParameters();
for (PsiParameter parameter : catchParameters) {
final PsiType caughtType = parameter.getType();
if (!(caughtType instanceof PsiClassType)) continue;
if (ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)caughtType)) continue;
if (!isCatchParameterRedundant((PsiClassType)caughtType, classes)) continue;
parameter.getParent().delete(); //delete catch section
}
PsiClassType[] exceptionsToAdd = filterUnhandledExceptions(newExceptions, tryBlock);
addExceptions(exceptionsToAdd, tryStatement);
adjustPossibleEmptyTryStatement(tryStatement);
}
else {
newExceptions = filterUnhandledExceptions(newExceptions, ref);
if (newExceptions.length > 0) {
//Add new try statement
PsiElementFactory elementFactory = myManager.getElementFactory();
PsiTryStatement tryStatement = (PsiTryStatement)elementFactory.createStatementFromText("try {} catch (Exception e) {}", null);
PsiStatement anchor = PsiTreeUtil.getParentOfType(ref, PsiStatement.class);
LOG.assertTrue(anchor != null);
tryStatement.getTryBlock().add(anchor);
tryStatement = (PsiTryStatement)anchor.getParent().addAfter(tryStatement, anchor);
addExceptions(newExceptions, tryStatement);
anchor.delete();
tryStatement.getCatchSections()[0].delete(); //Delete dummy catch section
}
}
}
private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exceptionType : exceptions) {
if (!ExceptionUtil.isUncheckedException(exceptionType)) result.add(exceptionType);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static void adjustPossibleEmptyTryStatement(PsiTryStatement tryStatement) throws IncorrectOperationException {
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
if (tryBlock != null) {
if (tryStatement.getCatchSections().length == 0 &&
tryStatement.getFinallyBlock() == null) {
PsiElement firstBodyElement = tryBlock.getFirstBodyElement();
if (firstBodyElement != null) {
tryStatement.getParent().addRangeAfter(firstBodyElement, tryBlock.getLastBodyElement(), tryStatement);
}
tryStatement.delete();
}
}
}
private static void addExceptions(PsiClassType[] exceptionsToAdd, PsiTryStatement tryStatement) throws IncorrectOperationException {
for (PsiClassType type : exceptionsToAdd) {
final CodeStyleManager styleManager = tryStatement.getManager().getCodeStyleManager();
String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type).names[0];
name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
PsiCatchSection catchSection = tryStatement.getManager().getElementFactory().createCatchSection(type, name, tryStatement);
tryStatement.add(catchSection);
}
}
private void fixPrimaryThrowsLists(PsiMethod method, PsiClassType[] newExceptions) throws IncorrectOperationException {
PsiElementFactory elementFactory = myManager.getElementFactory();
PsiJavaCodeReferenceElement[] refs = new PsiJavaCodeReferenceElement[newExceptions.length];
for (int i = 0; i < refs.length; i++) {
refs[i] = elementFactory.createReferenceElementByType(newExceptions[i]);
}
PsiReferenceList throwsList = elementFactory.createReferenceList(refs);
replaceThrowsList(method, throwsList);
}
private void replaceThrowsList(PsiMethod method, PsiReferenceList throwsList) throws IncorrectOperationException {
PsiReferenceList methodThrowsList = (PsiReferenceList)method.getThrowsList().replace(throwsList);
methodThrowsList = (PsiReferenceList)myManager.getCodeStyleManager().shortenClassReferences(methodThrowsList);
myManager.getCodeStyleManager().reformatRange(method, method.getParameterList().getTextRange().getEndOffset(),
methodThrowsList.getTextRange().getEndOffset());
}
private static PsiClassType[] filterUnhandledExceptions(PsiClassType[] exceptions, PsiElement place) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exception : exceptions) {
if (!ExceptionUtil.isHandled(exception, place)) result.add(exception);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static boolean isCatchParameterRedundant (PsiClassType catchParamType, PsiType[] thrownTypes) {
for (PsiType exceptionType : thrownTypes) {
if (exceptionType.isConvertibleFrom(catchParamType)) return false;
}
return true;
}
private static int getNonVarargCount(ChangeInfo changeInfo, PsiExpression[] args) {
if (!changeInfo.wasVararg) return args.length;
return changeInfo.oldParameterTypes.length - 1;
}
//This methods works equally well for primary usages as well as for propagated callers' usages
private void fixActualArgumentsList(PsiExpressionList list,
ChangeInfo changeInfo,
boolean toInsertDefaultValue) throws IncorrectOperationException {
final PsiElementFactory factory = list.getManager().getElementFactory();
if (changeInfo.isParameterSetOrOrderChanged) {
if (changeInfo.isPropagationEnabled) {
final ParameterInfo[] createdParmsInfo = changeInfo.getCreatedParmsInfoWithoutVarargs();
for (ParameterInfo info : createdParmsInfo) {
PsiExpression newArg;
if (toInsertDefaultValue) {
newArg = createDefaultValue(factory, info, list);
}
else {
newArg = factory.createExpressionFromText(info.getName(), list);
}
list.add(newArg);
}
}
else {
final PsiExpression[] args = list.getExpressions();
final int nonVarargCount = getNonVarargCount(changeInfo, args);
final int varargCount = args.length - nonVarargCount;
final int newArgsLength;
final int newNonVarargCount;
if (changeInfo.retainsVarargs) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount + varargCount;
}
else if (changeInfo.obtainsVarags) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount;
}
else {
newNonVarargCount = changeInfo.newParms.length;
newArgsLength = changeInfo.newParms.length;
}
final PsiExpression[] newArgs = new PsiExpression[newArgsLength];
for (int i = 0; i < newNonVarargCount; i++) {
final ParameterInfo info = changeInfo.newParms[i];
final int index = info.oldParameterIndex;
if (index >= 0) {
newArgs[i] = args[index];
} else {
if (toInsertDefaultValue) {
newArgs[i] = createDefaultValue(factory, info, list);
} else {
newArgs[i] = factory.createExpressionFromText(info.getName(), list);
}
}
}
final int newVarargCount = newArgsLength - newNonVarargCount;
LOG.assertTrue(newVarargCount == 0 || newVarargCount == varargCount);
for (int i = 0; i < newVarargCount; i++) {
newArgs[newNonVarargCount + i] = args[nonVarargCount + i];
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newArgs), ExpressionList.INSTANCE, changeInfo.toRemoveParm);
}
}
}
private PsiExpression createDefaultValue(final PsiElementFactory factory, final ParameterInfo info, final PsiExpressionList list)
throws IncorrectOperationException {
if (info.useAnySingleVariable) {
final PsiResolveHelper resolveHelper = list.getManager().getResolveHelper();
final PsiType type = info.getTypeWrapper().getType(myChangeInfo.getMethod(), myManager);
final VariablesProcessor processor = new VariablesProcessor(false) {
protected boolean check(PsiVariable var, PsiSubstitutor substitutor) {
if (var instanceof PsiField && !resolveHelper.isAccessible((PsiField)var, list, null)) return false;
final PsiType varType = substitutor.substitute(var.getType());
return type.isAssignableFrom(varType);
}
public boolean execute(PsiElement pe, PsiSubstitutor substitutor) {
super.execute(pe, substitutor);
return size() < 2;
}
};
PsiScopesUtil.treeWalkUp(processor, list, null);
if (processor.size() == 1) {
final PsiVariable result = processor.getResult(0);
return factory.createExpressionFromText(result.getName(), list);
}
}
return factory.createExpressionFromText(info.defaultValue, list);
}
private static void addParameterUsages(PsiParameter parameter,
ArrayList<UsageInfo> results,
ParameterInfo info) {
PsiManager manager = parameter.getManager();
PsiSearchHelper helper = manager.getSearchHelper();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
PsiReference[] parmRefs = helper.findReferences(parameter, projectScope, false);
for (PsiReference psiReference : parmRefs) {
PsiElement parmRef = psiReference.getElement();
UsageInfo usageInfo = new MyParameterUsageInfo(parmRef, parameter.getName(), info.getName());
results.add(usageInfo);
}
}
private void processCallerMethod(PsiMethod caller,
PsiMethod baseMethod,
boolean toInsertParams,
boolean toInsertThrows) throws IncorrectOperationException {
LOG.assertTrue(toInsertParams || toInsertThrows);
if (toInsertParams) {
List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
newParameters.addAll(Arrays.asList(caller.getParameterList().getParameters()));
final ParameterInfo[] primaryNewParms = myChangeInfo.newParms;
PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(caller, baseMethod);
for (ParameterInfo info : primaryNewParms) {
if (info.oldParameterIndex < 0) newParameters.add(createNewParameter(info, substitutor));
}
PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
}
if (toInsertThrows) {
List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
final PsiReferenceList throwsList = caller.getThrowsList();
newThrowns.addAll(Arrays.asList(throwsList.getReferenceElements()));
final ThrownExceptionInfo[] primaryNewExns = myChangeInfo.newExceptions;
for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
if (thrownExceptionInfo.oldIndex < 0) {
final PsiClassType type = (PsiClassType)thrownExceptionInfo.createType(caller, myManager);
final PsiJavaCodeReferenceElement ref = caller.getManager().getElementFactory().createReferenceElementByType(type);
newThrowns.add(ref);
}
}
PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
ChangeSignatureUtil.synchronizeList(throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
}
}
private void processPrimaryMethod(PsiMethod method,
PsiMethod baseMethod,
boolean isOriginal) throws IncorrectOperationException {
PsiElementFactory factory = method.getManager().getElementFactory();
if (myChangeInfo.isVisibilityChanged) {
PsiModifierList modifierList = method.getModifierList();
final String highestVisibility = isOriginal ?
myNewVisibility :
VisibilityUtil.getHighestVisibility(myNewVisibility, VisibilityUtil.getVisibilityModifier(modifierList));
RefactoringUtil.setVisibility(modifierList, highestVisibility);
}
if (myChangeInfo.isNameChanged) {
final EjbMethodRole role = com.intellij.javaee.ejb.role.EjbRolesUtil.getEjbRolesUtil().getEjbRole(method);
if (role instanceof EjbImplMethodRole && myChangeInfo.ejbRole instanceof EjbDeclMethodRole) {
EjbDeclMethodRole declRole = (EjbDeclMethodRole) myChangeInfo.ejbRole;
String newName = myChangeInfo.newName;
for (PsiMethod oldMethod : declRole.suggestImplementations()) {
if (oldMethod.getName().equals(method.getName())) {
PsiMethod newDeclMethod = (PsiMethod)method.copy();
newDeclMethod.getNameIdentifier().replace(myChangeInfo.newNameIdentifier);
newName = EjbPsiMethodUtil.suggestImplNames(newDeclMethod.getName(), declRole.getType(), declRole.getEnterpriseBean())[0];
break;
}
}
method.getNameIdentifier().replace(factory.createIdentifier(newName));
} else {
method.getNameIdentifier().replace(myChangeInfo.newNameIdentifier);
}
}
final PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(method, baseMethod);
if (myChangeInfo.isReturnTypeChanged) {
final PsiType returnType = substitutor.substitute(myChangeInfo.newTypeElement);
method.getReturnTypeElement().replace(factory.createTypeElement(returnType));
}
PsiParameterList list = method.getParameterList();
PsiParameter[] parameters = list.getParameters();
PsiParameter[] newParms = new PsiParameter[myChangeInfo.newParms.length];
for (int i = 0; i < newParms.length; i++) {
ParameterInfo info = myChangeInfo.newParms[i];
int index = info.oldParameterIndex;
if (index >= 0) {
PsiParameter parameter = parameters[index];
newParms[i] = parameter;
String oldName = myChangeInfo.oldParameterNames[index];
if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) {
PsiIdentifier newIdentifier = factory.createIdentifier(info.getName());
parameter.getNameIdentifier().replace(newIdentifier);
}
String oldType = myChangeInfo.oldParameterTypes[index];
if (!oldType.equals(info.getTypeText())) {
parameter.normalizeDeclaration();
PsiType newType = substitutor.substitute(info.createType(myChangeInfo.getMethod().getParameterList(), myManager));
parameter.getTypeElement().replace(factory.createTypeElement(newType));
}
} else {
newParms[i] = createNewParameter(info, substitutor);
}
}
resolveParameterVsFieldsConflicts(newParms, method, list, myChangeInfo.toRemoveParm);
fixJavadocsForChangedMethod(method);
if (myChangeInfo.isExceptionSetOrOrderChanged) {
final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(myChangeInfo);
fixPrimaryThrowsLists(method, newExceptions);
}
}
private static void resolveParameterVsFieldsConflicts(final PsiParameter[] newParms,
final PsiMethod method,
final PsiParameterList list,
boolean[] toRemoveParm) throws IncorrectOperationException {
List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>();
for (PsiParameter parameter : newParms) {
conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody()));
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm);
for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) {
fieldConflictsResolver.fix();
}
}
private static PsiSubstitutor calculateSubstitutor(PsiMethod derivedMethod, PsiMethod baseMethod) {
PsiSubstitutor substitutor;
if (derivedMethod.getManager().areElementsEquivalent(derivedMethod, baseMethod)) {
substitutor = PsiSubstitutor.EMPTY;
} else {
final PsiClass baseClass = baseMethod.getContainingClass();
final PsiClass derivedClass = derivedMethod.getContainingClass();
if(baseClass != null && derivedClass != null && InheritanceUtil.isInheritorOrSelf(derivedClass, baseClass, true)) {
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, derivedClass, PsiSubstitutor.EMPTY);
final MethodSignature superMethodSignature = baseMethod.getSignature(superClassSubstitutor);
final MethodSignature methodSignature = derivedMethod.getSignature(PsiSubstitutor.EMPTY);
final PsiSubstitutor superMethodSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature, superMethodSignature);
substitutor = superMethodSubstitutor != null ? superMethodSubstitutor : superClassSubstitutor;
} else {
substitutor = PsiSubstitutor.EMPTY;
}
}
return substitutor;
}
private static void processParameterUsage(PsiReferenceExpression ref, String oldName, String newName)
throws IncorrectOperationException {
PsiElement last = ref.getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(oldName)) {
PsiElementFactory factory = ref.getManager().getElementFactory();
PsiIdentifier newNameIdentifier = factory.createIdentifier(newName);
last.replace(newNameIdentifier);
}
}
private static class MyParameterUsageInfo extends UsageInfo {
final String oldParameterName;
final String newParameterName;
public MyParameterUsageInfo(PsiElement element, String oldParameterName, String newParameterName) {
super(element);
this.oldParameterName = oldParameterName;
this.newParameterName = newParameterName;
}
}
public static PsiElement normalizeResolutionContext(PsiElement resolutionContext) {
PsiElement result = PsiTreeUtil.getNonStrictParentOfType(resolutionContext, PsiStatement.class, PsiClass.class, PsiFile.class);
if (result != null) return result;
return resolutionContext;
}
private static class RenamedParameterCollidesWithLocalUsageInfo extends UnresolvableCollisionUsageInfo {
private final PsiElement myCollidingElement;
private final PsiMethod myMethod;
public RenamedParameterCollidesWithLocalUsageInfo(PsiParameter parameter, PsiElement collidingElement, PsiMethod method) {
super(parameter, collidingElement);
myCollidingElement = collidingElement;
myMethod = method;
}
public String getDescription() {
return RefactoringBundle.message("there.is.already.a.0.in.the.1.it.will.conflict.with.the.renamed.parameter",
ConflictsUtil.getDescription(myCollidingElement, true),
ConflictsUtil.getDescription(myMethod, true));
}
}
private void fixJavadocsForChangedMethod(PsiMethod method) throws IncorrectOperationException {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final ParameterInfo[] newParms = myChangeInfo.newParms;
LOG.assertTrue(parameters.length == newParms.length);
final Set<PsiParameter> newParameters = new HashSet<PsiParameter>();
for (int i = 0; i < newParms.length; i++) {
ParameterInfo newParm = newParms[i];
if (newParm.oldParameterIndex < 0 ||
!newParm.getName().equals(myChangeInfo.oldParameterNames[newParm.oldParameterIndex])) {
newParameters.add(parameters[i]);
}
}
RefactoringUtil.fixJavadocsForParams(method, newParameters);
}
private static class ExpressionList implements ChangeSignatureUtil.ChildrenGenerator<PsiExpressionList, PsiExpression> {
public static final ExpressionList INSTANCE = new ExpressionList();
public List<PsiExpression> getChildren(PsiExpressionList psiExpressionList) {
return Arrays.asList(psiExpressionList.getExpressions());
}
}
private static class ParameterList implements ChangeSignatureUtil.ChildrenGenerator<PsiParameterList, PsiParameter> {
public static final ParameterList INSTANCE = new ParameterList();
public List<PsiParameter> getChildren(PsiParameterList psiParameterList) {
return Arrays.asList(psiParameterList.getParameters());
}
}
private static class ThrowsList implements ChangeSignatureUtil.ChildrenGenerator<PsiReferenceList, PsiJavaCodeReferenceElement> {
public static final ThrowsList INSTANCE = new ThrowsList();
public List<PsiJavaCodeReferenceElement> getChildren(PsiReferenceList throwsList) {
return Arrays.asList(throwsList.getReferenceElements());
}
}
}
|
IDEADEV-3685
|
refactoring/impl/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java
|
IDEADEV-3685
|
|
Java
|
apache-2.0
|
13dafb93054094f1804a29226e7aed0094c9337b
| 0
|
ModeShape/modeshape-performance,ModeShape/modeshape-performance,ModeShape/modeshape-performance
|
/*
* JBoss, Home of Professional Open Source
* Copyright [2011], Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.modeshape.jcr.perftests.imprt;
import javax.jcr.*;
import org.modeshape.jcr.perftests.AbstractPerformanceTestSuite;
import org.modeshape.jcr.perftests.BigSet;
import org.modeshape.jcr.perftests.SuiteConfiguration;
/**
* <code>ManyNodesImportTestSuite</code>
* implements a performance test, which imports
* repository with many nodes from external file.
*/
public class BigSetCloneTestSuite extends AbstractPerformanceTestSuite {
private static final int NODE_COUNT = 10;
private static String ROOT_NODE = "ROOT_NODE";
private Session srcSession, dstSession;
private int i =0;
public BigSetCloneTestSuite( SuiteConfiguration suiteConfiguration ) {
super(suiteConfiguration);
}
@Override
public void beforeSuite() throws Exception {
//create first session and pre-fill the repo
srcSession = newSession();
BigSet.fillRepository(srcSession, ROOT_NODE, NODE_COUNT, 4);
srcSession.save();
//create another workspace and session
Workspace def = srcSession.getWorkspace();
def.createWorkspace("test-clone");
dstSession = srcSession.getRepository().login("test-clone");
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
dstSession.save();
}
@Override
public void runTest() throws Exception {
dstSession.getWorkspace().clone(srcSession.getWorkspace().getName(), "/" + ROOT_NODE, "/" + ROOT_NODE, false);
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
}
@Override
public void afterSuite() throws Exception {
BigSet.cleanWorkspace(srcSession, ROOT_NODE);
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
dstSession.logout();
try {
srcSession.getWorkspace().deleteWorkspace("test-clone");
} catch (Exception e) {
//may be not implemented
}
srcSession.logout();
}
}
|
perf-tests-api/src/main/java/org/modeshape/jcr/perftests/imprt/BigSetCloneTestSuite.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright [2011], Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.modeshape.jcr.perftests.imprt;
import javax.jcr.*;
import org.modeshape.jcr.perftests.AbstractPerformanceTestSuite;
import org.modeshape.jcr.perftests.BigSet;
import org.modeshape.jcr.perftests.SuiteConfiguration;
/**
* <code>ManyNodesImportTestSuite</code>
* implements a performance test, which imports
* repository with many nodes from external file.
*/
public class BigSetCloneTestSuite extends AbstractPerformanceTestSuite {
private static final int NODE_COUNT = 10;
private static String ROOT_NODE = "ROOT_NODE";
private Session srcSession, dstSession;
private int i =0;
public BigSetCloneTestSuite( SuiteConfiguration suiteConfiguration ) {
super(suiteConfiguration);
}
@Override
public void beforeSuite() throws Exception {
//create first session and pre-fill the repo
srcSession = newSession();
BigSet.fillRepository(srcSession, ROOT_NODE, NODE_COUNT, 4);
srcSession.save();
//create another workspace and session
Workspace def = srcSession.getWorkspace();
def.createWorkspace("test");
dstSession = srcSession.getRepository().login("test");
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
dstSession.save();
}
@Override
public void runTest() throws Exception {
dstSession.getWorkspace().clone(srcSession.getWorkspace().getName(), "/" + ROOT_NODE, "/" + ROOT_NODE, false);
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
}
@Override
public void afterSuite() throws Exception {
BigSet.cleanWorkspace(srcSession, ROOT_NODE);
BigSet.cleanWorkspace(dstSession, ROOT_NODE);
dstSession.logout();
srcSession.getWorkspace().deleteWorkspace("test");
srcSession.logout();
}
}
|
MODE-1620 Rename test workspace to allow execute jackrabbit tests
|
perf-tests-api/src/main/java/org/modeshape/jcr/perftests/imprt/BigSetCloneTestSuite.java
|
MODE-1620 Rename test workspace to allow execute jackrabbit tests
|
|
Java
|
apache-2.0
|
042439f08b53a3268551e97012c658e310ef59c4
| 0
|
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <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.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.base.Strings;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.api.ConfigMapContext;
import io.shardingsphere.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.api.config.RuleConfiguration;
import io.shardingsphere.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.ShardingConstant;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant;
import io.shardingsphere.core.constant.transaction.TransactionType;
import io.shardingsphere.core.event.ShardingEventBusInstance;
import io.shardingsphere.core.rule.Authentication;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.orchestration.internal.event.config.AuthenticationChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.DataSourceChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.MasterSlaveRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.PropertiesChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.ShardingRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.state.CircuitStateEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.DisabledStateEventBusEvent;
import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule;
import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule;
import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration;
import io.shardingsphere.shardingproxy.util.DataSourceConverter;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Global registry.
*
* @author chenqingyang
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public final class GlobalRegistry {
private static final GlobalRegistry INSTANCE = new GlobalRegistry();
private final List<String> schemaNames = new LinkedList<>();
private final Map<String, LogicSchema> logicSchemas = new ConcurrentHashMap<>();
private ShardingProperties shardingProperties;
private BackendNIOConfiguration backendNIOConfig;
private Authentication authentication;
private boolean isCircuitBreak;
/**
* Get instance of proxy context.
*
* @return instance of proxy context.
*/
public static GlobalRegistry getInstance() {
return INSTANCE;
}
/**
* Register listener.
*/
public void register() {
ShardingEventBusInstance.getInstance().register(this);
}
/**
* Initialize proxy context.
*
* @param schemaDataSources data source map
* @param schemaRules schema rule map
* @param authentication authentication
* @param configMap config map
* @param props properties
*/
public void init(final Map<String, Map<String, DataSourceParameter>> schemaDataSources,
final Map<String, RuleConfiguration> schemaRules, final Authentication authentication, final Map<String, Object> configMap, final Properties props) {
init(schemaDataSources, schemaRules, authentication, configMap, props, false);
}
/**
* Initialize proxy context.
*
* @param schemaDataSources data source map
* @param schemaRules schema rule map
* @param authentication authentication
* @param configMap config map
* @param props properties
* @param isUsingRegistry is using registry or not
*/
public void init(final Map<String, Map<String, DataSourceParameter>> schemaDataSources,
final Map<String, RuleConfiguration> schemaRules, final Authentication authentication, final Map<String, Object> configMap, final Properties props, final boolean isUsingRegistry) {
if (!configMap.isEmpty()) {
ConfigMapContext.getInstance().getConfigMap().putAll(configMap);
}
shardingProperties = new ShardingProperties(null == props ? new Properties() : props);
this.authentication = authentication;
initSchema(schemaDataSources, schemaRules, isUsingRegistry);
initBackendNIOConfig();
}
private void initSchema(final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules, final boolean isUsingRegistry) {
for (Entry<String, RuleConfiguration> entry : schemaRules.entrySet()) {
String schemaName = entry.getKey();
schemaNames.add(schemaName);
logicSchemas.put(schemaName, getLogicSchema(schemaName, schemaDataSources, entry.getValue(), isUsingRegistry));
}
}
private LogicSchema getLogicSchema(final String schemaName, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final RuleConfiguration ruleConfiguration, final boolean isUsingRegistry) {
return ruleConfiguration instanceof ShardingRuleConfiguration ? new ShardingSchema(schemaName, schemaDataSources.get(schemaName), (ShardingRuleConfiguration) ruleConfiguration, isUsingRegistry)
: new MasterSlaveSchema(schemaName, schemaDataSources.get(schemaName), (MasterSlaveRuleConfiguration) ruleConfiguration, isUsingRegistry);
}
private void initBackendNIOConfig() {
int databaseConnectionCount = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_MAX_CONNECTIONS);
int connectionTimeoutSeconds = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_CONNECTION_TIMEOUT_SECONDS);
backendNIOConfig = new BackendNIOConfiguration(databaseConnectionCount, connectionTimeoutSeconds);
}
/**
* Get max connections size per query.
*
* @return max connections size per query
*/
public int getMaxConnectionsSizePerQuery() {
return shardingProperties.getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY);
}
/**
* Get transaction type.
*
* @return transaction type
*/
// TODO just config proxy.transaction.enable here, in future(3.1.0)
public TransactionType getTransactionType() {
return shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_TRANSACTION_ENABLED) ? TransactionType.XA : TransactionType.LOCAL;
}
/**
* Is open tracing enable.
*
* @return is or not
*/
public boolean isOpenTracingEnable() {
return shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_OPENTRACING_ENABLED);
}
/**
* Is show SQL.
*
* @return show or not
*/
public boolean isShowSQL() {
return shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
}
/**
* Get acceptor size.
*
* @return acceptor size
*/
public int getAcceptorSize() {
return shardingProperties.getValue(ShardingPropertiesConstant.ACCEPTOR_SIZE);
}
/**
* Get executor size.
*
* @return executor size
*/
public int getExecutorSize() {
return shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
}
/**
* Is use NIO.
*
* @return use or not
*/
// TODO :jiaqi force off use NIO for backend, this feature is not complete yet
public boolean isUseNIO() {
return false;
}
/**
* Check schema exists.
*
* @param schema schema
* @return schema exists or not
*/
public boolean schemaExists(final String schema) {
return schemaNames.contains(schema);
}
/**
* Get sharding schema.
*
* @param schemaName schema name
* @return sharding schema
*/
public ShardingSchema getShardingSchema(final String schemaName) {
return Strings.isNullOrEmpty(schemaName) ? null : logicSchemas.get(schemaName);
}
/**
* Renew sharding rule.
*
* @param shardingEvent sharding event.
*/
@Subscribe
public void renew(final ShardingRuleChangedEvent shardingEvent) {
logicSchemas.put(shardingEvent.getShardingSchemaName(), new ShardingSchema(shardingEvent.getShardingSchemaName(),
logicSchemas.get(shardingEvent.getShardingSchemaName()).getDataSources(), shardingEvent.getShardingRuleConfiguration(), true));
}
/**
* Renew master-slave rule.
*
* @param masterSlaveEvent master-slave event.
*/
@Subscribe
public void renew(final MasterSlaveRuleChangedEvent masterSlaveEvent) {
logicSchemas.put(masterSlaveEvent.getShardingSchemaName(), new ShardingSchema(masterSlaveEvent.getShardingSchemaName(),
logicSchemas.get(masterSlaveEvent.getShardingSchemaName()).getDataSources(), masterSlaveEvent.getMasterSlaveRuleConfig(), true));
}
/**
* Renew data source configuration.
*
* @param dataSourceEvent data source event.
*/
@Subscribe
public void renew(final DataSourceChangedEvent dataSourceEvent) {
ShardingSchema shardingSchema = logicSchemas.get(dataSourceEvent.getSchemaName());
shardingSchema.getBackendDataSource().close();
logicSchemas.put(dataSourceEvent.getSchemaName(), new ShardingSchema(dataSourceEvent.getSchemaName(),
DataSourceConverter.getDataSourceParameterMap(dataSourceEvent.getDataSourceConfigurations()), shardingSchema.getShardingRule(), shardingSchema.getMasterSlaveRule()));
}
/**
* Renew properties.
*
* @param propertiesEvent properties event
*/
@Subscribe
public void renew(final PropertiesChangedEvent propertiesEvent) {
shardingProperties = new ShardingProperties(propertiesEvent.getProps());
}
/**
* Renew authentication.
*
* @param authenticationEvent authe
*/
@Subscribe
public void renew(final AuthenticationChangedEvent authenticationEvent) {
authentication = authenticationEvent.getAuthentication();
}
/**
* Renew circuit breaker dataSource names.
*
* @param circuitStateEventBusEvent jdbc circuit event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final DisabledStateEventBusEvent disabledStateEventBusEvent) {
Map<String, Collection<String>> disabledSchemaDataSourceMap = disabledStateEventBusEvent.getDisabledSchemaDataSourceMap();
for (String each : disabledSchemaDataSourceMap.keySet()) {
DisabledStateEventBusEvent eventBusEvent = new DisabledStateEventBusEvent(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, disabledSchemaDataSourceMap.get(each)));
renewShardingSchema(each, eventBusEvent);
}
}
private void renewShardingSchema(final String each, final DisabledStateEventBusEvent eventBusEvent) {
if (logicSchemas.get(each).isMasterSlaveOnly()) {
renewShardingSchemaWithMasterSlaveRule(logicSchemas.get(each), eventBusEvent);
} else {
renewShardingSchemaWithShardingRule(logicSchemas.get(each), eventBusEvent);
}
}
private void renewShardingSchemaWithShardingRule(final ShardingSchema shardingSchema, final DisabledStateEventBusEvent disabledEvent) {
for (MasterSlaveRule each : ((OrchestrationShardingRule) shardingSchema.getShardingRule()).getMasterSlaveRules()) {
((OrchestrationMasterSlaveRule) each).renew(disabledEvent);
}
}
private void renewShardingSchemaWithMasterSlaveRule(final ShardingSchema shardingSchema, final DisabledStateEventBusEvent disabledEvent) {
((OrchestrationMasterSlaveRule) shardingSchema.getMasterSlaveRule()).renew(disabledEvent);
}
}
|
sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <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.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.base.Strings;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.api.ConfigMapContext;
import io.shardingsphere.api.config.MasterSlaveRuleConfiguration;
import io.shardingsphere.api.config.RuleConfiguration;
import io.shardingsphere.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.ShardingConstant;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant;
import io.shardingsphere.core.constant.transaction.TransactionType;
import io.shardingsphere.core.event.ShardingEventBusInstance;
import io.shardingsphere.core.rule.Authentication;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.orchestration.internal.event.config.AuthenticationChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.DataSourceChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.MasterSlaveRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.PropertiesChangedEvent;
import io.shardingsphere.orchestration.internal.event.config.ShardingRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.state.CircuitStateEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.DisabledStateEventBusEvent;
import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule;
import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule;
import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration;
import io.shardingsphere.shardingproxy.util.DataSourceConverter;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Global registry.
*
* @author chenqingyang
* @author panjuan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public final class GlobalRegistry {
private static final GlobalRegistry INSTANCE = new GlobalRegistry();
private final List<String> schemaNames = new LinkedList<>();
private final Map<String, LogicSchema> logicSchemas = new ConcurrentHashMap<>();
private ShardingProperties shardingProperties;
private BackendNIOConfiguration backendNIOConfig;
private Authentication authentication;
private boolean isCircuitBreak;
/**
* Get instance of proxy context.
*
* @return instance of proxy context.
*/
public static GlobalRegistry getInstance() {
return INSTANCE;
}
/**
* Register listener.
*/
public void register() {
ShardingEventBusInstance.getInstance().register(this);
}
/**
* Initialize proxy context.
*
* @param schemaDataSources data source map
* @param schemaRules schema rule map
* @param authentication authentication
* @param configMap config map
* @param props properties
*/
public void init(final Map<String, Map<String, DataSourceParameter>> schemaDataSources,
final Map<String, RuleConfiguration> schemaRules, final Authentication authentication, final Map<String, Object> configMap, final Properties props) {
init(schemaDataSources, schemaRules, authentication, configMap, props, false);
}
/**
* Initialize proxy context.
*
* @param schemaDataSources data source map
* @param schemaRules schema rule map
* @param authentication authentication
* @param configMap config map
* @param props properties
* @param isUsingRegistry is using registry or not
*/
public void init(final Map<String, Map<String, DataSourceParameter>> schemaDataSources,
final Map<String, RuleConfiguration> schemaRules, final Authentication authentication, final Map<String, Object> configMap, final Properties props, final boolean isUsingRegistry) {
if (!configMap.isEmpty()) {
ConfigMapContext.getInstance().getConfigMap().putAll(configMap);
}
shardingProperties = new ShardingProperties(null == props ? new Properties() : props);
this.authentication = authentication;
initSchema(schemaDataSources, schemaRules, isUsingRegistry);
initBackendNIOConfig();
}
private void initSchema(final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules, final boolean isUsingRegistry) {
for (Entry<String, RuleConfiguration> entry : schemaRules.entrySet()) {
String schemaName = entry.getKey();
schemaNames.add(schemaName);
logicSchemas.put(schemaName, getLogicSchema(schemaDataSources, isUsingRegistry, entry, schemaName));
}
}
private LogicSchema getLogicSchema(final String schemaName, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final RuleConfiguration ruleConfiguration, final boolean isUsingRegistry) {
return ruleConfiguration instanceof ShardingRuleConfiguration ? new ShardingSchema(schemaName, schemaDataSources.get(schemaName), (ShardingRuleConfiguration) ruleConfiguration, isUsingRegistry)
: new MasterSlaveSchema(schemaName, schemaDataSources.get(schemaName), (MasterSlaveRuleConfiguration) ruleConfiguration, isUsingRegistry);
}
private void initBackendNIOConfig() {
int databaseConnectionCount = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_MAX_CONNECTIONS);
int connectionTimeoutSeconds = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_CONNECTION_TIMEOUT_SECONDS);
backendNIOConfig = new BackendNIOConfiguration(databaseConnectionCount, connectionTimeoutSeconds);
}
/**
* Get max connections size per query.
*
* @return max connections size per query
*/
public int getMaxConnectionsSizePerQuery() {
return shardingProperties.getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY);
}
/**
* Get transaction type.
*
* @return transaction type
*/
// TODO just config proxy.transaction.enable here, in future(3.1.0)
public TransactionType getTransactionType() {
return shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_TRANSACTION_ENABLED) ? TransactionType.XA : TransactionType.LOCAL;
}
/**
* Is open tracing enable.
*
* @return is or not
*/
public boolean isOpenTracingEnable() {
return shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_OPENTRACING_ENABLED);
}
/**
* Is show SQL.
*
* @return show or not
*/
public boolean isShowSQL() {
return shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
}
/**
* Get acceptor size.
*
* @return acceptor size
*/
public int getAcceptorSize() {
return shardingProperties.getValue(ShardingPropertiesConstant.ACCEPTOR_SIZE);
}
/**
* Get executor size.
*
* @return executor size
*/
public int getExecutorSize() {
return shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
}
/**
* Is use NIO.
*
* @return use or not
*/
// TODO :jiaqi force off use NIO for backend, this feature is not complete yet
public boolean isUseNIO() {
return false;
}
/**
* Check schema exists.
*
* @param schema schema
* @return schema exists or not
*/
public boolean schemaExists(final String schema) {
return schemaNames.contains(schema);
}
/**
* Get sharding schema.
*
* @param schemaName schema name
* @return sharding schema
*/
public ShardingSchema getShardingSchema(final String schemaName) {
return Strings.isNullOrEmpty(schemaName) ? null : logicSchemas.get(schemaName);
}
/**
* Renew sharding rule.
*
* @param shardingEvent sharding event.
*/
@Subscribe
public void renew(final ShardingRuleChangedEvent shardingEvent) {
logicSchemas.put(shardingEvent.getShardingSchemaName(), new ShardingSchema(shardingEvent.getShardingSchemaName(),
logicSchemas.get(shardingEvent.getShardingSchemaName()).getDataSources(), shardingEvent.getShardingRuleConfiguration(), true));
}
/**
* Renew master-slave rule.
*
* @param masterSlaveEvent master-slave event.
*/
@Subscribe
public void renew(final MasterSlaveRuleChangedEvent masterSlaveEvent) {
logicSchemas.put(masterSlaveEvent.getShardingSchemaName(), new ShardingSchema(masterSlaveEvent.getShardingSchemaName(),
logicSchemas.get(masterSlaveEvent.getShardingSchemaName()).getDataSources(), masterSlaveEvent.getMasterSlaveRuleConfig(), true));
}
/**
* Renew data source configuration.
*
* @param dataSourceEvent data source event.
*/
@Subscribe
public void renew(final DataSourceChangedEvent dataSourceEvent) {
ShardingSchema shardingSchema = logicSchemas.get(dataSourceEvent.getSchemaName());
shardingSchema.getBackendDataSource().close();
logicSchemas.put(dataSourceEvent.getSchemaName(), new ShardingSchema(dataSourceEvent.getSchemaName(),
DataSourceConverter.getDataSourceParameterMap(dataSourceEvent.getDataSourceConfigurations()), shardingSchema.getShardingRule(), shardingSchema.getMasterSlaveRule()));
}
/**
* Renew properties.
*
* @param propertiesEvent properties event
*/
@Subscribe
public void renew(final PropertiesChangedEvent propertiesEvent) {
shardingProperties = new ShardingProperties(propertiesEvent.getProps());
}
/**
* Renew authentication.
*
* @param authenticationEvent authe
*/
@Subscribe
public void renew(final AuthenticationChangedEvent authenticationEvent) {
authentication = authenticationEvent.getAuthentication();
}
/**
* Renew circuit breaker dataSource names.
*
* @param circuitStateEventBusEvent jdbc circuit event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final DisabledStateEventBusEvent disabledStateEventBusEvent) {
Map<String, Collection<String>> disabledSchemaDataSourceMap = disabledStateEventBusEvent.getDisabledSchemaDataSourceMap();
for (String each : disabledSchemaDataSourceMap.keySet()) {
DisabledStateEventBusEvent eventBusEvent = new DisabledStateEventBusEvent(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, disabledSchemaDataSourceMap.get(each)));
renewShardingSchema(each, eventBusEvent);
}
}
private void renewShardingSchema(final String each, final DisabledStateEventBusEvent eventBusEvent) {
if (logicSchemas.get(each).isMasterSlaveOnly()) {
renewShardingSchemaWithMasterSlaveRule(logicSchemas.get(each), eventBusEvent);
} else {
renewShardingSchemaWithShardingRule(logicSchemas.get(each), eventBusEvent);
}
}
private void renewShardingSchemaWithShardingRule(final ShardingSchema shardingSchema, final DisabledStateEventBusEvent disabledEvent) {
for (MasterSlaveRule each : ((OrchestrationShardingRule) shardingSchema.getShardingRule()).getMasterSlaveRules()) {
((OrchestrationMasterSlaveRule) each).renew(disabledEvent);
}
}
private void renewShardingSchemaWithMasterSlaveRule(final ShardingSchema shardingSchema, final DisabledStateEventBusEvent disabledEvent) {
((OrchestrationMasterSlaveRule) shardingSchema.getMasterSlaveRule()).renew(disabledEvent);
}
}
|
modify initSchema()
|
sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java
|
modify initSchema()
|
|
Java
|
apache-2.0
|
a5d0c7ba53d6bee5824e071290d54cb1308d4c2e
| 0
|
googleinterns/step64-2020,googleinterns/step64-2020,googleinterns/step64-2020
|
@@ -0,0 +1,32 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package
com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that returns some example content. TODO: modify this file to handle
* comments data
*/
@WebServlet("/data")
public class DataServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
}
}
|
src/main/java/com/google/sps/servlets/DataServlet.java
|
@@ -0,0 +1,32 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that returns some example content. TODO: modify this file to handle
* comments data
*/
@WebServlet("/data")
public class DataServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
}
}
|
Fix DataServlet formatting.
|
src/main/java/com/google/sps/servlets/DataServlet.java
|
Fix DataServlet formatting.
|
|
Java
|
apache-2.0
|
ed56932087bc6451cda2013fc687d988bf008213
| 0
|
danbernier/WordCram,danbernier/WordCram,danbernier/WordCram
|
package example;
/*
Copyright 2010 Daniel Bernier
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.FileNotFoundException;
import java.util.*;
import processing.core.PApplet;
import processing.core.PFont;
import wordcram.*;
public class Main extends PApplet {
WordCram wordcram;
public void setup() {
// destination.image.getGraphics():
// P2D -> sun.awt.image.ToolkitImage, JAVA2D -> java.awt.image.BufferedImage.
// parent.getGraphics():
// P2D -> sun.java2d.SunGraphics2D, JAVA2D -> same thing.
// P2D can't draw to destination.image.getGraphics(). Interesting.
size(700, 400); // (int)random(300, 800)); //1200, 675); //1600, 900);
smooth();
colorMode(HSB);
try {
initWordCram();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//frameRate(1);
}
private PFont randomFont() {
String[] fonts = PFont.list();
String noGoodFontNames = "Dingbats|Standard Symbols L";
String blockFontNames = "OpenSymbol|Mallige Bold|Mallige Normal|Lohit Bengali|Lohit Punjabi|Webdings";
Set<String> noGoodFonts = new HashSet<String>(Arrays.asList((noGoodFontNames+"|"+blockFontNames).split("|")));
String fontName;
do {
fontName = fonts[(int)random(fonts.length)];
} while (fontName == null || noGoodFonts.contains(fontName));
System.out.println(fontName);
return createFont(fontName, 1);
//return createFont("Molengo", 1);
}
//PGraphics pg;
private void initWordCram() throws FileNotFoundException {
background(100);
//pg = createGraphics(800, 600, JAVA2D);
//pg.beginDraw();
wordcram = new WordCram(this)
// .toCanvas(pg)
.fromTextFile(textFilePath())
// .fromWords(alphabet())
// .upperCase()
// .excludeNumbers()
.withFonts(randomFont())
// .withColorer(Colorers.twoHuesRandomSats(this))
// .withColorer(Colorers.complement(this, random(255), 200, 220))
.withAngler(Anglers.mostlyHoriz())
.withPlacer(Placers.horizLine())
// .withPlacer(Placers.centerClump())
.withSizer(Sizers.byWeight(5, 90))
.withWordPadding(1)
// .minShapeSize(0)
// .withMaxAttemptsForPlacement(10)
.maxNumberOfWordsToDraw(1000)
.toSvg("test.svg", 1000, 1000)
// .withNudger(new PlottingWordNudger(this, new SpiralWordNudger()))
// .withNudger(new RandomWordNudger())
;
}
private void finishUp() {
//pg.endDraw();
//image(pg, 0, 0);
//println(wordcram.getSkippedWords());
println("Done");
save("wordcram.png");
noLoop();
}
public void draw() {
//fill(55);
//rect(0, 0, width, height);
boolean allAtOnce = true;
if (allAtOnce) {
wordcram.drawAll();
finishUp();
}
else {
int wordsPerFrame = 1;
while (wordcram.hasMore() && wordsPerFrame-- > 0) {
wordcram.drawNext();
}
if (!wordcram.hasMore()) {
finishUp();
}
}
}
public void mouseMoved() {
/*
Word word = wordcram.getWordAt(mouseX, mouseY);
if (word != null) {
System.out.println(round(mouseX) + "," + round(mouseY) + " -> " + word.word);
}
*/
}
public void mouseClicked() {
try {
initWordCram();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loop();
}
public void keyPressed() {
if (keyCode == ' ') {
saveFrame("wordcram-##.png");
}
}
private String textFilePath() {
return "../ideExample/tao-te-ching.txt";
}
private Word[] alphabet() {
Word[] w = new Word[26];
for (int i = 0; i < w.length; i++) {
w[i] = new Word(new String(new char[]{(char)(i+65)}), 26-i);
}
return w;
}
}
|
ideExample/example/Main.java
|
package example;
/*
Copyright 2010 Daniel Bernier
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.FileNotFoundException;
import java.util.*;
import processing.core.PApplet;
import processing.core.PFont;
import wordcram.Anglers;
import wordcram.Placers;
import wordcram.PrintStreamObserver;
import wordcram.Sizers;
import wordcram.Word;
import wordcram.WordCram;
public class Main extends PApplet {
WordCram wordcram;
public void setup() {
// destination.image.getGraphics():
// P2D -> sun.awt.image.ToolkitImage, JAVA2D -> java.awt.image.BufferedImage.
// parent.getGraphics():
// P2D -> sun.java2d.SunGraphics2D, JAVA2D -> same thing.
// P2D can't draw to destination.image.getGraphics(). Interesting.
size(700, 400); // (int)random(300, 800)); //1200, 675); //1600, 900);
smooth();
colorMode(HSB);
try {
initWordCram();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//frameRate(1);
}
private PFont randomFont() {
String[] fonts = PFont.list();
String noGoodFontNames = "Dingbats|Standard Symbols L";
String blockFontNames = "OpenSymbol|Mallige Bold|Mallige Normal|Lohit Bengali|Lohit Punjabi|Webdings";
Set<String> noGoodFonts = new HashSet<String>(Arrays.asList((noGoodFontNames+"|"+blockFontNames).split("|")));
String fontName;
do {
fontName = fonts[(int)random(fonts.length)];
} while (fontName == null || noGoodFonts.contains(fontName));
System.out.println(fontName);
return createFont(fontName, 1);
//return createFont("Molengo", 1);
}
//PGraphics pg;
private void initWordCram() throws FileNotFoundException {
background(100);
//pg = createGraphics(800, 600, JAVA2D);
//pg.beginDraw();
wordcram = new WordCram(this)
// .toCanvas(pg)
.fromTextFile(textFilePath())
// .fromWords(alphabet())
// .upperCase()
// .excludeNumbers()
.withFonts(randomFont())
// .withColorer(Colorers.twoHuesRandomSats(this))
// .withColorer(Colorers.complement(this, random(255), 200, 220))
.withAngler(Anglers.mostlyHoriz())
.withPlacer(Placers.horizLine())
// .withPlacer(Placers.centerClump())
.withSizer(Sizers.byWeight(5, 90))
.withObserver(new PrintStreamObserver())
.withWordPadding(1)
// .minShapeSize(0)
// .withMaxAttemptsForPlacement(10)
.maxNumberOfWordsToDraw(1000)
.toSvg("test.svg", 1000, 1000)
// .withNudger(new PlottingWordNudger(this, new SpiralWordNudger()))
// .withNudger(new RandomWordNudger())
;
}
private void finishUp() {
//pg.endDraw();
//image(pg, 0, 0);
//println(wordcram.getSkippedWords());
println("Done");
save("wordcram.png");
noLoop();
}
public void draw() {
//fill(55);
//rect(0, 0, width, height);
boolean allAtOnce = true;
if (allAtOnce) {
wordcram.drawAll();
finishUp();
}
else {
int wordsPerFrame = 1;
while (wordcram.hasMore() && wordsPerFrame-- > 0) {
wordcram.drawNext();
}
if (!wordcram.hasMore()) {
finishUp();
}
}
}
public void mouseMoved() {
/*
Word word = wordcram.getWordAt(mouseX, mouseY);
if (word != null) {
System.out.println(round(mouseX) + "," + round(mouseY) + " -> " + word.word);
}
*/
}
public void mouseClicked() {
try {
initWordCram();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loop();
}
public void keyPressed() {
if (keyCode == ' ') {
saveFrame("wordcram-##.png");
}
}
private String textFilePath() {
return "../ideExample/tao-te-ching.txt";
}
private Word[] alphabet() {
Word[] w = new Word[26];
for (int i = 0; i < w.length; i++) {
w[i] = new Word(new String(new char[]{(char)(i+65)}), 26-i);
}
return w;
}
}
|
Clean up example/Main.java
|
ideExample/example/Main.java
|
Clean up example/Main.java
|
|
Java
|
apache-2.0
|
8de7ea8c8605db8bf40d80340d904e92985e9451
| 0
|
rpelisse/JGroups,belaban/JGroups,danberindei/JGroups,Sanne/JGroups,ligzy/JGroups,Sanne/JGroups,dimbleby/JGroups,kedzie/JGroups,deepnarsay/JGroups,dimbleby/JGroups,belaban/JGroups,Sanne/JGroups,dimbleby/JGroups,rpelisse/JGroups,kedzie/JGroups,danberindei/JGroups,kedzie/JGroups,rvansa/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,pferraro/JGroups,pruivo/JGroups,slaskawi/JGroups,rhusar/JGroups,ligzy/JGroups,danberindei/JGroups,vjuranek/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,deepnarsay/JGroups,ligzy/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,slaskawi/JGroups,pferraro/JGroups,rhusar/JGroups,vjuranek/JGroups,pruivo/JGroups,ibrahimshbat/JGroups,pruivo/JGroups,pferraro/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,tristantarrant/JGroups,deepnarsay/JGroups,tristantarrant/JGroups,slaskawi/JGroups,rvansa/JGroups
|
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Simple flow control protocol. After max_credits bytes sent to the group (or an individual member), the sender blocks
* until it receives an ack from all members that they indeed received max_credits bytes.
* Design in doc/design/SimpleFlowControl.txt<br/>
* <em>Note that SFC supports only flow control for multicast messages; unicast flow control is not supported ! Use FC if
* unicast flow control is required.</em>
* @author Bela Ban
*/
@Experimental
@MBean(description="Simple flow control protocol")
public class SFC extends Protocol {
/* ----------------------------------------- Properties -------------------------------------------------- */
@Property(description="Max number of bytes to send per receiver until an ack must be received to proceed. Default is 2000000 bytes")
private long max_credits=2000000;
@Property(description="Max time (in milliseconds) to block. Default is 5000 msec")
private long max_block_time=5000;
private Long MAX_CREDITS;
private static final Long ZERO_CREDITS=new Long(0);
/** Current number of credits available to send */
@GuardedBy("lock")
private long curr_credits_available;
/** Map which keeps track of bytes received from senders */
@GuardedBy("received_lock")
private final Map<Address,Long> received=new HashMap<Address,Long>(12);
/** Set of members which have requested credits but from whom we have not yet received max_credits bytes */
@GuardedBy("received_lock")
private final Set<Address> pending_requesters=new HashSet<Address>();
/** Set of members from whom we haven't yet received credits */
@GuardedBy("lock")
private final Set<Address> pending_creditors=new HashSet<Address>();
private final Lock lock=new ReentrantLock();
/** Lock protecting access to received and pending_requesters */
private final Lock received_lock=new ReentrantLock();
/** Used to wait for and signal when credits become available again */
private final Condition credits_available=lock.newCondition();
/** Last time a thread woke up from blocking and had to request credit */
private long last_blocked_request=0L;
private final List<Address> members=new LinkedList<Address>();
private boolean running=true;
private boolean frag_size_received=false;
@GuardedBy("lock") long start, stop;
// ---------------------- Management information -----------------------
long num_blockings=0;
long num_bytes_sent=0;
long num_credit_requests_sent=0;
long num_credit_requests_received=0;
long num_replenishments_received=0;
long num_replenishments_sent=0;
long total_block_time=0;
final BoundedList<Long> blockings=new BoundedList<Long>(50);
public void resetStats() {
super.resetStats();
num_blockings=total_block_time=num_replenishments_received=num_credit_requests_sent=num_bytes_sent=0;
num_replenishments_sent=num_credit_requests_received=0;
blockings.clear();
}
public long getMaxCredits() {return max_credits;}
@ManagedAttribute
public long getCredits() {return curr_credits_available;}
@ManagedAttribute
public long getBytesSent() {return num_bytes_sent;}
@ManagedAttribute
public long getBlockings() {return num_blockings;}
@ManagedAttribute
public long getCreditRequestsSent() {return num_credit_requests_sent;}
@ManagedAttribute
public long getCreditRequestsReceived() {return num_credit_requests_received;}
@ManagedAttribute
public long getReplenishmentsReceived() {return num_replenishments_received;}
@ManagedAttribute
public long getReplenishmentsSent() {return num_replenishments_sent;}
@ManagedAttribute
public long getTotalBlockingTime() {return total_block_time;}
@ManagedAttribute
public double getAverageBlockingTime() {return num_blockings == 0? 0 : total_block_time / num_blockings;}
@ManagedOperation
public String printBlockingTimes() {
return blockings.toString();
}
@ManagedOperation
public String printReceived() {
received_lock.lock();
try {
return received.toString();
}
finally {
received_lock.unlock();
}
}
@ManagedOperation
public String printPendingCreditors() {
lock.lock();
try {
return pending_creditors.toString();
}
finally {
lock.unlock();
}
}
@ManagedOperation
public String printPendingRequesters() {
received_lock.lock();
try {
return pending_requesters.toString();
}
finally {
received_lock.unlock();
}
}
@ManagedOperation
public void unblock() {
lock.lock();
try {
curr_credits_available=max_credits;
credits_available.signalAll();
}
finally {
lock.unlock();
}
}
// ------------------- End of management information ----------------------
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) // only handle multicast messages
break;
boolean send_credit_request=false;
lock.lock();
try {
while(curr_credits_available <=0 && running) {
if(log.isTraceEnabled())
log.trace("blocking (current credits=" + curr_credits_available + ")");
try {
num_blockings++;
// will be signalled when we have credit responses from all members
boolean rc=credits_available.await(max_block_time, TimeUnit.MILLISECONDS);
if(rc || (curr_credits_available <=0 && running)) {
if(log.isTraceEnabled())
log.trace("returned from await but credits still unavailable (credits=" +curr_credits_available +")");
long now=System.currentTimeMillis();
if(now - last_blocked_request >= max_block_time) {
last_blocked_request=now;
lock.unlock(); // send the credit request without holding the lock
try {
sendCreditRequest(true);
}
finally {
lock.lock(); // now acquire the lock again
}
}
}
else {
// reset the last_blocked_request stamp so the
// next timed out block will for sure send a request
last_blocked_request=0;
}
}
catch(InterruptedException e) {
// bela June 16 2007: http://jira.jboss.com/jira/browse/JGRP-536
// if(log.isWarnEnabled())
// log.warn("thread was interrupted", e);
// Thread.currentThread().interrupt(); // pass the exception on to the caller
// return null;
}
}
// when we get here, curr_credits_available is guaranteed to be > 0
int len=msg.getLength();
num_bytes_sent+=len;
curr_credits_available-=len; // we'll block on insufficient credits on the next down() call
if(curr_credits_available <=0) {
pending_creditors.clear();
synchronized(members) {
pending_creditors.addAll(members);
}
send_credit_request=true;
}
}
finally {
lock.unlock();
}
// we don't need to protect send_credit_request because a thread above either (a) decrements the credits
// by the msg length and sets send_credit_request to true or (b) blocks because there are no credits
// available. So only 1 thread can ever set send_credit_request at any given time
if(send_credit_request) {
if(log.isTraceEnabled())
log.trace("sending credit request to group");
start=System.nanoTime(); // only 1 thread is here at any given time
Object ret=down_prot.down(evt); // send the message before the credit request
sendCreditRequest(false); // do this outside of the lock
return ret;
}
break;
case Event.VIEW_CHANGE:
handleViewChange((View)evt.getArg());
break;
case Event.SUSPECT:
handleSuspect((Address)evt.getArg());
break;
case Event.CONFIG:
Map<String,Object> map=(Map<String,Object>)evt.getArg();
handleConfigEvent(map);
break;
}
return down_prot.down(evt);
}
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Header hdr=(Header)msg.getHeader(this.id);
Address sender=msg.getSrc();
if(hdr != null) {
switch(hdr.type) {
case Header.CREDIT_REQUEST:
handleCreditRequest(sender, false);
break;
case Header.URGENT_CREDIT_REQUEST:
handleCreditRequest(sender, true);
break;
case Header.REPLENISH:
handleCreditResponse(sender);
break;
default:
if(log.isErrorEnabled())
log.error("unknown header type " + hdr.type);
break;
}
return null; // we don't pass the request further up
}
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) // we don't handle unicast messages
break;
handleMessage(msg, sender);
break;
case Event.VIEW_CHANGE:
handleViewChange((View)evt.getArg());
break;
case Event.SUSPECT:
handleSuspect((Address)evt.getArg());
break;
case Event.CONFIG:
Map<String,Object> map=(Map<String,Object>)evt.getArg();
handleConfigEvent(map);
break;
}
return up_prot.up(evt);
}
public void init() throws Exception{
MAX_CREDITS=new Long(max_credits);
curr_credits_available=max_credits;
}
public void start() throws Exception {
super.start();
if(!frag_size_received) {
log.warn("No fragmentation protocol was found. When flow control (e.g. FC or SFC) is used, we recommend " +
"a fragmentation protocol, due to http://jira.jboss.com/jira/browse/JGRP-590");
}
running=true;
}
public void stop() {
super.stop();
running=false;
lock.lock();
try {
credits_available.signalAll();
}
finally {
lock.unlock();
}
}
private void handleConfigEvent(Map<String,Object> map) {
if(map != null) {
Integer frag_size=(Integer)map.get("frag_size");
if(frag_size != null) {
if(frag_size > max_credits) {
log.warn("The fragmentation size of the fragmentation protocol is " + frag_size +
", which is greater than the max credits. While this is not incorrect, " +
"it may lead to long blockings. Frag size should be less than max_credits " +
"(http://jira.jboss.com/jira/browse/JGRP-590)");
}
frag_size_received=true;
}
}
}
private void handleMessage(Message msg, Address sender) {
int len=msg.getLength(); // we don't care about headers, this is faster than size()
Long new_val;
boolean send_credit_response=false;
received_lock.lock();
try {
Long credits=received.get(sender);
if(credits == null) {
new_val=MAX_CREDITS;
received.put(sender, new_val);
}
else {
new_val=credits.longValue() + len;
received.put(sender, new_val);
}
// if(log.isTraceEnabled())
// log.trace("received " + len + " bytes from " + sender + ": total=" + new_val + " bytes");
// see whether we have any pending credit requests
if(!pending_requesters.isEmpty()
&& pending_requesters.contains(sender)
&& new_val.longValue() >= max_credits) {
pending_requesters.remove(sender);
if(log.isTraceEnabled())
log.trace("removed " + sender + " from credit requesters; sending credits");
received.put(sender, ZERO_CREDITS);
send_credit_response=true;
}
}
finally {
received_lock.unlock();
}
if(send_credit_response) // send outside of the monitor
sendCreditResponse(sender);
}
private void handleCreditRequest(Address sender, boolean urgent) {
boolean send_credit_response=false;
received_lock.lock();
try {
num_credit_requests_received++;
Long bytes=received.get(sender);
if(log.isTraceEnabled())
log.trace("received credit request from " + sender + " (total received: " + bytes + " bytes");
if(bytes == null) {
if(log.isErrorEnabled())
log.error("received credit request from " + sender + ", but sender is not in received hashmap;" +
" adding it");
send_credit_response=true;
}
else {
if(bytes.longValue() < max_credits && !urgent) {
if(log.isTraceEnabled())
log.trace("adding " + sender + " to pending credit requesters");
pending_requesters.add(sender);
}
else {
send_credit_response=true;
}
}
if(send_credit_response)
received.put(sender, ZERO_CREDITS);
}
finally{
received_lock.unlock();
}
if(send_credit_response) {
sendCreditResponse(sender);
}
}
private void handleCreditResponse(Address sender) {
lock.lock();
try {
num_replenishments_received++;
if(pending_creditors.remove(sender) && pending_creditors.isEmpty()) {
curr_credits_available=max_credits;
stop=System.nanoTime();
long diff=(stop-start)/1000000L;
if(log.isTraceEnabled())
log.trace("replenished credits to " + curr_credits_available +
" (total blocking time=" + diff + " ms)");
blockings.add(new Long(diff));
total_block_time+=diff;
credits_available.signalAll();
}
}
finally{
lock.unlock();
}
}
private void handleViewChange(View view) {
List<Address> mbrs=view != null? view.getMembers() : null;
if(mbrs != null) {
synchronized(members) {
members.clear();
members.addAll(mbrs);
}
}
lock.lock();
try {
// remove all members which left from pending_creditors
if(pending_creditors.retainAll(members) && pending_creditors.isEmpty()) {
// the collection was changed and is empty now as a result of retainAll()
curr_credits_available=max_credits;
if(log.isTraceEnabled())
log.trace("replenished credits to " + curr_credits_available);
credits_available.signalAll();
}
}
finally {
lock.unlock();
}
received_lock.lock();
try {
// remove left members
received.keySet().retainAll(members);
// add new members with *full* credits (see doc/design/SimpleFlowControl.txt for reason)
for(Address mbr: members) {
if(!received.containsKey(mbr))
received.put(mbr, MAX_CREDITS);
}
// remove left members from pending credit requesters
pending_requesters.retainAll(members);
}
finally{
received_lock.unlock();
}
}
private void handleSuspect(Address suspected_mbr) {
// this is the same as a credit response - we cannot block forever for a crashed member
handleCreditResponse(suspected_mbr);
}
private void sendCreditRequest(boolean urgent) {
Message credit_req=new Message();
// credit_req.setFlag(Message.OOB); // we need to receive the credit request after regular messages
byte type=urgent? Header.URGENT_CREDIT_REQUEST : Header.CREDIT_REQUEST;
credit_req.putHeader(this.id, new Header(type));
num_credit_requests_sent++;
down_prot.down(new Event(Event.MSG, credit_req));
}
private void sendCreditResponse(Address dest) {
Message credit_rsp=new Message(dest);
credit_rsp.setFlag(Message.OOB);
Header hdr=new Header(Header.REPLENISH);
credit_rsp.putHeader(this.id, hdr);
if(log.isTraceEnabled())
log.trace("sending credit response to " + dest);
num_replenishments_sent++;
down_prot.down(new Event(Event.MSG, credit_rsp));
}
public static class Header extends org.jgroups.Header {
public static final byte CREDIT_REQUEST = 1; // the sender of the message is the requester
public static final byte REPLENISH = 2; // the sender of the message is the creditor
public static final byte URGENT_CREDIT_REQUEST = 3;
byte type=CREDIT_REQUEST;
public Header() {
}
public Header(byte type) {
this.type=type;
}
public int size() {
return Global.BYTE_SIZE;
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeByte(type);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readByte();
}
public String toString() {
switch(type) {
case REPLENISH: return "REPLENISH";
case CREDIT_REQUEST: return "CREDIT_REQUEST";
case URGENT_CREDIT_REQUEST: return "URGENT_CREDIT_REQUEST";
default: return "<invalid type>";
}
}
}
}
|
src/org/jgroups/protocols/SFC.java
|
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Simple flow control protocol. After max_credits bytes sent to the group (or an individual member), the sender blocks
* until it receives an ack from all members that they indeed received max_credits bytes.
* Design in doc/design/SimpleFlowControl.txt<br/>
* <em>Note that SFC supports only flow control for multicast messages; unicast flow control is not supported ! Use FC if
* unicast flow control is required.</em>
* @author Bela Ban
*/
@MBean(description="Simple flow control protocol")
public class SFC extends Protocol {
/* ----------------------------------------- Properties -------------------------------------------------- */
@Property(description="Max number of bytes to send per receiver until an ack must be received to proceed. Default is 2000000 bytes")
private long max_credits=2000000;
@Property(description="Max time (in milliseconds) to block. Default is 5000 msec")
private long max_block_time=5000;
private Long MAX_CREDITS;
private static final Long ZERO_CREDITS=new Long(0);
/** Current number of credits available to send */
@GuardedBy("lock")
private long curr_credits_available;
/** Map which keeps track of bytes received from senders */
@GuardedBy("received_lock")
private final Map<Address,Long> received=new HashMap<Address,Long>(12);
/** Set of members which have requested credits but from whom we have not yet received max_credits bytes */
@GuardedBy("received_lock")
private final Set<Address> pending_requesters=new HashSet<Address>();
/** Set of members from whom we haven't yet received credits */
@GuardedBy("lock")
private final Set<Address> pending_creditors=new HashSet<Address>();
private final Lock lock=new ReentrantLock();
/** Lock protecting access to received and pending_requesters */
private final Lock received_lock=new ReentrantLock();
/** Used to wait for and signal when credits become available again */
private final Condition credits_available=lock.newCondition();
/** Last time a thread woke up from blocking and had to request credit */
private long last_blocked_request=0L;
private final List<Address> members=new LinkedList<Address>();
private boolean running=true;
private boolean frag_size_received=false;
@GuardedBy("lock") long start, stop;
// ---------------------- Management information -----------------------
long num_blockings=0;
long num_bytes_sent=0;
long num_credit_requests_sent=0;
long num_credit_requests_received=0;
long num_replenishments_received=0;
long num_replenishments_sent=0;
long total_block_time=0;
final BoundedList<Long> blockings=new BoundedList<Long>(50);
public void resetStats() {
super.resetStats();
num_blockings=total_block_time=num_replenishments_received=num_credit_requests_sent=num_bytes_sent=0;
num_replenishments_sent=num_credit_requests_received=0;
blockings.clear();
}
public long getMaxCredits() {return max_credits;}
@ManagedAttribute
public long getCredits() {return curr_credits_available;}
@ManagedAttribute
public long getBytesSent() {return num_bytes_sent;}
@ManagedAttribute
public long getBlockings() {return num_blockings;}
@ManagedAttribute
public long getCreditRequestsSent() {return num_credit_requests_sent;}
@ManagedAttribute
public long getCreditRequestsReceived() {return num_credit_requests_received;}
@ManagedAttribute
public long getReplenishmentsReceived() {return num_replenishments_received;}
@ManagedAttribute
public long getReplenishmentsSent() {return num_replenishments_sent;}
@ManagedAttribute
public long getTotalBlockingTime() {return total_block_time;}
@ManagedAttribute
public double getAverageBlockingTime() {return num_blockings == 0? 0 : total_block_time / num_blockings;}
@ManagedOperation
public String printBlockingTimes() {
return blockings.toString();
}
@ManagedOperation
public String printReceived() {
received_lock.lock();
try {
return received.toString();
}
finally {
received_lock.unlock();
}
}
@ManagedOperation
public String printPendingCreditors() {
lock.lock();
try {
return pending_creditors.toString();
}
finally {
lock.unlock();
}
}
@ManagedOperation
public String printPendingRequesters() {
received_lock.lock();
try {
return pending_requesters.toString();
}
finally {
received_lock.unlock();
}
}
@ManagedOperation
public void unblock() {
lock.lock();
try {
curr_credits_available=max_credits;
credits_available.signalAll();
}
finally {
lock.unlock();
}
}
// ------------------- End of management information ----------------------
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) // only handle multicast messages
break;
boolean send_credit_request=false;
lock.lock();
try {
while(curr_credits_available <=0 && running) {
if(log.isTraceEnabled())
log.trace("blocking (current credits=" + curr_credits_available + ")");
try {
num_blockings++;
// will be signalled when we have credit responses from all members
boolean rc=credits_available.await(max_block_time, TimeUnit.MILLISECONDS);
if(rc || (curr_credits_available <=0 && running)) {
if(log.isTraceEnabled())
log.trace("returned from await but credits still unavailable (credits=" +curr_credits_available +")");
long now=System.currentTimeMillis();
if(now - last_blocked_request >= max_block_time) {
last_blocked_request=now;
lock.unlock(); // send the credit request without holding the lock
try {
sendCreditRequest(true);
}
finally {
lock.lock(); // now acquire the lock again
}
}
}
else {
// reset the last_blocked_request stamp so the
// next timed out block will for sure send a request
last_blocked_request=0;
}
}
catch(InterruptedException e) {
// bela June 16 2007: http://jira.jboss.com/jira/browse/JGRP-536
// if(log.isWarnEnabled())
// log.warn("thread was interrupted", e);
// Thread.currentThread().interrupt(); // pass the exception on to the caller
// return null;
}
}
// when we get here, curr_credits_available is guaranteed to be > 0
int len=msg.getLength();
num_bytes_sent+=len;
curr_credits_available-=len; // we'll block on insufficient credits on the next down() call
if(curr_credits_available <=0) {
pending_creditors.clear();
synchronized(members) {
pending_creditors.addAll(members);
}
send_credit_request=true;
}
}
finally {
lock.unlock();
}
// we don't need to protect send_credit_request because a thread above either (a) decrements the credits
// by the msg length and sets send_credit_request to true or (b) blocks because there are no credits
// available. So only 1 thread can ever set send_credit_request at any given time
if(send_credit_request) {
if(log.isTraceEnabled())
log.trace("sending credit request to group");
start=System.nanoTime(); // only 1 thread is here at any given time
Object ret=down_prot.down(evt); // send the message before the credit request
sendCreditRequest(false); // do this outside of the lock
return ret;
}
break;
case Event.VIEW_CHANGE:
handleViewChange((View)evt.getArg());
break;
case Event.SUSPECT:
handleSuspect((Address)evt.getArg());
break;
case Event.CONFIG:
Map<String,Object> map=(Map<String,Object>)evt.getArg();
handleConfigEvent(map);
break;
}
return down_prot.down(evt);
}
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Header hdr=(Header)msg.getHeader(this.id);
Address sender=msg.getSrc();
if(hdr != null) {
switch(hdr.type) {
case Header.CREDIT_REQUEST:
handleCreditRequest(sender, false);
break;
case Header.URGENT_CREDIT_REQUEST:
handleCreditRequest(sender, true);
break;
case Header.REPLENISH:
handleCreditResponse(sender);
break;
default:
if(log.isErrorEnabled())
log.error("unknown header type " + hdr.type);
break;
}
return null; // we don't pass the request further up
}
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) // we don't handle unicast messages
break;
handleMessage(msg, sender);
break;
case Event.VIEW_CHANGE:
handleViewChange((View)evt.getArg());
break;
case Event.SUSPECT:
handleSuspect((Address)evt.getArg());
break;
case Event.CONFIG:
Map<String,Object> map=(Map<String,Object>)evt.getArg();
handleConfigEvent(map);
break;
}
return up_prot.up(evt);
}
public void init() throws Exception{
MAX_CREDITS=new Long(max_credits);
curr_credits_available=max_credits;
}
public void start() throws Exception {
super.start();
if(!frag_size_received) {
log.warn("No fragmentation protocol was found. When flow control (e.g. FC or SFC) is used, we recommend " +
"a fragmentation protocol, due to http://jira.jboss.com/jira/browse/JGRP-590");
}
running=true;
}
public void stop() {
super.stop();
running=false;
lock.lock();
try {
credits_available.signalAll();
}
finally {
lock.unlock();
}
}
private void handleConfigEvent(Map<String,Object> map) {
if(map != null) {
Integer frag_size=(Integer)map.get("frag_size");
if(frag_size != null) {
if(frag_size > max_credits) {
log.warn("The fragmentation size of the fragmentation protocol is " + frag_size +
", which is greater than the max credits. While this is not incorrect, " +
"it may lead to long blockings. Frag size should be less than max_credits " +
"(http://jira.jboss.com/jira/browse/JGRP-590)");
}
frag_size_received=true;
}
}
}
private void handleMessage(Message msg, Address sender) {
int len=msg.getLength(); // we don't care about headers, this is faster than size()
Long new_val;
boolean send_credit_response=false;
received_lock.lock();
try {
Long credits=received.get(sender);
if(credits == null) {
new_val=MAX_CREDITS;
received.put(sender, new_val);
}
else {
new_val=credits.longValue() + len;
received.put(sender, new_val);
}
// if(log.isTraceEnabled())
// log.trace("received " + len + " bytes from " + sender + ": total=" + new_val + " bytes");
// see whether we have any pending credit requests
if(!pending_requesters.isEmpty()
&& pending_requesters.contains(sender)
&& new_val.longValue() >= max_credits) {
pending_requesters.remove(sender);
if(log.isTraceEnabled())
log.trace("removed " + sender + " from credit requesters; sending credits");
received.put(sender, ZERO_CREDITS);
send_credit_response=true;
}
}
finally {
received_lock.unlock();
}
if(send_credit_response) // send outside of the monitor
sendCreditResponse(sender);
}
private void handleCreditRequest(Address sender, boolean urgent) {
boolean send_credit_response=false;
received_lock.lock();
try {
num_credit_requests_received++;
Long bytes=received.get(sender);
if(log.isTraceEnabled())
log.trace("received credit request from " + sender + " (total received: " + bytes + " bytes");
if(bytes == null) {
if(log.isErrorEnabled())
log.error("received credit request from " + sender + ", but sender is not in received hashmap;" +
" adding it");
send_credit_response=true;
}
else {
if(bytes.longValue() < max_credits && !urgent) {
if(log.isTraceEnabled())
log.trace("adding " + sender + " to pending credit requesters");
pending_requesters.add(sender);
}
else {
send_credit_response=true;
}
}
if(send_credit_response)
received.put(sender, ZERO_CREDITS);
}
finally{
received_lock.unlock();
}
if(send_credit_response) {
sendCreditResponse(sender);
}
}
private void handleCreditResponse(Address sender) {
lock.lock();
try {
num_replenishments_received++;
if(pending_creditors.remove(sender) && pending_creditors.isEmpty()) {
curr_credits_available=max_credits;
stop=System.nanoTime();
long diff=(stop-start)/1000000L;
if(log.isTraceEnabled())
log.trace("replenished credits to " + curr_credits_available +
" (total blocking time=" + diff + " ms)");
blockings.add(new Long(diff));
total_block_time+=diff;
credits_available.signalAll();
}
}
finally{
lock.unlock();
}
}
private void handleViewChange(View view) {
List<Address> mbrs=view != null? view.getMembers() : null;
if(mbrs != null) {
synchronized(members) {
members.clear();
members.addAll(mbrs);
}
}
lock.lock();
try {
// remove all members which left from pending_creditors
if(pending_creditors.retainAll(members) && pending_creditors.isEmpty()) {
// the collection was changed and is empty now as a result of retainAll()
curr_credits_available=max_credits;
if(log.isTraceEnabled())
log.trace("replenished credits to " + curr_credits_available);
credits_available.signalAll();
}
}
finally {
lock.unlock();
}
received_lock.lock();
try {
// remove left members
received.keySet().retainAll(members);
// add new members with *full* credits (see doc/design/SimpleFlowControl.txt for reason)
for(Address mbr: members) {
if(!received.containsKey(mbr))
received.put(mbr, MAX_CREDITS);
}
// remove left members from pending credit requesters
pending_requesters.retainAll(members);
}
finally{
received_lock.unlock();
}
}
private void handleSuspect(Address suspected_mbr) {
// this is the same as a credit response - we cannot block forever for a crashed member
handleCreditResponse(suspected_mbr);
}
private void sendCreditRequest(boolean urgent) {
Message credit_req=new Message();
// credit_req.setFlag(Message.OOB); // we need to receive the credit request after regular messages
byte type=urgent? Header.URGENT_CREDIT_REQUEST : Header.CREDIT_REQUEST;
credit_req.putHeader(this.id, new Header(type));
num_credit_requests_sent++;
down_prot.down(new Event(Event.MSG, credit_req));
}
private void sendCreditResponse(Address dest) {
Message credit_rsp=new Message(dest);
credit_rsp.setFlag(Message.OOB);
Header hdr=new Header(Header.REPLENISH);
credit_rsp.putHeader(this.id, hdr);
if(log.isTraceEnabled())
log.trace("sending credit response to " + dest);
num_replenishments_sent++;
down_prot.down(new Event(Event.MSG, credit_rsp));
}
public static class Header extends org.jgroups.Header {
public static final byte CREDIT_REQUEST = 1; // the sender of the message is the requester
public static final byte REPLENISH = 2; // the sender of the message is the creditor
public static final byte URGENT_CREDIT_REQUEST = 3;
byte type=CREDIT_REQUEST;
public Header() {
}
public Header(byte type) {
this.type=type;
}
public int size() {
return Global.BYTE_SIZE;
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeByte(type);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readByte();
}
public String toString() {
switch(type) {
case REPLENISH: return "REPLENISH";
case CREDIT_REQUEST: return "CREDIT_REQUEST";
case URGENT_CREDIT_REQUEST: return "URGENT_CREDIT_REQUEST";
default: return "<invalid type>";
}
}
}
}
|
made SFC experimental
|
src/org/jgroups/protocols/SFC.java
|
made SFC experimental
|
|
Java
|
apache-2.0
|
44839eec3f0a6dfefb03ea58e34ceba15067f01a
| 0
|
apache/sandesha,apache/sandesha,apache/sandesha
|
/*
* 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.sandesha2.storage.inmemory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.storage.SandeshaStorageException;
import org.apache.sandesha2.storage.Transaction;
import org.apache.sandesha2.storage.beans.RMBean;
/**
* This class does not really implement transactions, but it is a good
* place to implement locking for the in memory storage manager.
*/
public class InMemoryTransaction implements Transaction {
private static final Log log = LogFactory.getLog(InMemoryTransaction.class);
private InMemoryStorageManager manager;
private String threadName;
private ArrayList enlistedBeans = new ArrayList();
private InMemoryTransaction waitingForTran = null;
private boolean sentMessages = false;
private boolean active = true;
private Thread thread;
InMemoryTransaction(InMemoryStorageManager manager, Thread thread) {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::<init>");
this.manager = manager;
this.thread = thread;
this.threadName = thread.getName();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::<init>, " + this);
}
public void commit() {
releaseLocks();
if(sentMessages) manager.getSender().wakeThread();
active = false;
}
public void rollback() {
releaseLocks();
active = false;
}
public boolean isActive () {
return active;
}
public void enlist(RMBean bean) throws SandeshaStorageException {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::enlist, " + bean);
if(bean != null) {
synchronized (bean) {
InMemoryTransaction other = (InMemoryTransaction) bean.getTransaction();
while(other != null && other != this) {
// Put ourselves into the list of waiters
waitingForTran = other;
// Look to see if there is a loop in the chain of waiters
if(!enlistedBeans.isEmpty()) {
HashSet set = new HashSet();
set.add(this);
while(other != null) {
if(set.contains(other)) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.deadlock, this.toString(), bean.toString());
SandeshaStorageException e = new SandeshaStorageException(message);
// Do our best to get out of the way of the other work in the system
waitingForTran = null;
releaseLocks();
if(log.isDebugEnabled()) log.debug(message, e);
throw e;
}
set.add(other);
other = other.waitingForTran;
}
}
boolean warn = false;
try {
if(log.isDebugEnabled()) log.debug("This " + this + " waiting for " + waitingForTran);
long pre = System.currentTimeMillis();
bean.wait(5000);
long post = System.currentTimeMillis();
if ((post - pre) > 50000)
warn = true;
} catch(InterruptedException e) {
// Do nothing
}
other = (InMemoryTransaction) bean.getTransaction();
if (other != null && warn) {
//we have been waiting for a long time - this might imply a three way deadlock so error condition
if(log.isDebugEnabled()) log.debug("possible deadlock :" + this.toString() + " : " + bean.toString());
}
}
waitingForTran = null;
if(other == null) {
if(log.isDebugEnabled()) log.debug(this + " locking bean");
bean.setTransaction(this);
enlistedBeans.add(bean);
}
}
}
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::enlist");
}
private void releaseLocks() {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::releaseLocks, " + this);
manager.removeTransaction(this);
Iterator beans = enlistedBeans.iterator();
while(beans.hasNext()) {
RMBean bean = (RMBean) beans.next();
synchronized (bean) {
bean.setTransaction(null);
bean.notifyAll();
}
}
enlistedBeans.clear();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::releaseLocks");
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("[InMemoryTransaction, thread:");
result.append(thread);
result.append(", name: ");
result.append(threadName);
result.append(", locks: ");
result.append(enlistedBeans.size());
result.append("]");
return result.toString();
}
public void setSentMessages(boolean sentMessages) {
this.sentMessages = sentMessages;
}
/**
* Get the thread which this transaction is associated with.
* @return
*/
public Thread getThread(){
return thread;
}
}
|
modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.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.sandesha2.storage.inmemory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.storage.SandeshaStorageException;
import org.apache.sandesha2.storage.Transaction;
import org.apache.sandesha2.storage.beans.RMBean;
/**
* This class does not really implement transactions, but it is a good
* place to implement locking for the in memory storage manager.
*/
public class InMemoryTransaction implements Transaction {
private static final Log log = LogFactory.getLog(InMemoryTransaction.class);
private InMemoryStorageManager manager;
private String threadName;
private ArrayList enlistedBeans = new ArrayList();
private InMemoryTransaction waitingForTran = null;
private boolean sentMessages = false;
private boolean active = true;
private Thread thread;
InMemoryTransaction(InMemoryStorageManager manager, Thread thread) {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::<init>");
this.manager = manager;
this.thread = thread;
this.threadName = thread.getName();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::<init>, " + this);
}
public void commit() {
releaseLocks();
if(sentMessages) manager.getSender().wakeThread();
active = false;
}
public void rollback() {
releaseLocks();
active = false;
}
public boolean isActive () {
return active;
}
public void enlist(RMBean bean) throws SandeshaStorageException {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::enlist, " + bean);
if(bean != null) {
synchronized (bean) {
InMemoryTransaction other = (InMemoryTransaction) bean.getTransaction();
while(other != null && other != this) {
// Put ourselves into the list of waiters
waitingForTran = other;
// Look to see if there is a loop in the chain of waiters
if(!enlistedBeans.isEmpty()) {
HashSet set = new HashSet();
set.add(this);
while(other != null && other != this) {
if(set.contains(other)) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.deadlock, this.toString(), bean.toString());
SandeshaStorageException e = new SandeshaStorageException(message);
// Do our best to get out of the way of the other work in the system
waitingForTran = null;
releaseLocks();
if(log.isDebugEnabled()) log.debug(message, e);
throw e;
}
set.add(other);
other = other.waitingForTran;
}
}
boolean warn = false;
try {
if(log.isDebugEnabled()) log.debug("This " + this + " waiting for " + waitingForTran);
long pre = System.currentTimeMillis();
bean.wait(5000);
long post = System.currentTimeMillis();
if ((post - pre) > 50000)
warn = true;
} catch(InterruptedException e) {
// Do nothing
}
other = (InMemoryTransaction) bean.getTransaction();
if (other != null && warn) {
//we have been waiting for a long time - this might imply a three way deadlock so error condition
if(log.isDebugEnabled()) log.debug("possible deadlock :" + this.toString() + " : " + bean.toString());
}
}
waitingForTran = null;
if(other == null) {
if(log.isDebugEnabled()) log.debug(this + " locking bean");
bean.setTransaction(this);
enlistedBeans.add(bean);
}
}
}
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::enlist");
}
private void releaseLocks() {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::releaseLocks, " + this);
manager.removeTransaction(this);
Iterator beans = enlistedBeans.iterator();
while(beans.hasNext()) {
RMBean bean = (RMBean) beans.next();
synchronized (bean) {
bean.setTransaction(null);
bean.notifyAll();
}
}
enlistedBeans.clear();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::releaseLocks");
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("[InMemoryTransaction, thread:");
result.append(thread);
result.append(", name: ");
result.append(threadName);
result.append(", locks: ");
result.append(enlistedBeans.size());
result.append("]");
return result.toString();
}
public void setSentMessages(boolean sentMessages) {
this.sentMessages = sentMessages;
}
/**
* Get the thread which this transaction is associated with.
* @return
*/
public Thread getThread(){
return thread;
}
}
|
Reverting 616602. My bad!
git-svn-id: 2b86aa0691b69980d9a6f3f27dca0ec9e0ea7276@617135 13f79535-47bb-0310-9956-ffa450edef68
|
modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.java
|
Reverting 616602. My bad!
|
|
Java
|
apache-2.0
|
826447bc82b2b7a84539ce7c9838d0a1a195e303
| 0
|
alibaba/Sentinel,alibaba/Sentinel,alibaba/Sentinel,alibaba/Sentinel
|
/*
* Copyright 1999-2018 Alibaba Group Holding 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 com.alibaba.csp.sentinel.slotchain;
import java.lang.reflect.Method;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.util.IdUtil;
import com.alibaba.csp.sentinel.util.MethodUtil;
/**
* Resource wrapper for method invocation.
*
* @author qinan.qn
*/
public class MethodResourceWrapper extends ResourceWrapper {
private transient Method method;
public MethodResourceWrapper(Method method, EntryType type) {
this.method = method;
this.name = MethodUtil.resolveMethodName(method);
this.type = type;
}
@Override
public String getName() {
return name;
}
public Method getMethod() {
return method;
}
@Override
public String getShowName() {
return name;
}
@Override
public EntryType getType() {
return type;
}
}
|
sentinel-core/src/main/java/com/alibaba/csp/sentinel/slotchain/MethodResourceWrapper.java
|
/*
* Copyright 1999-2018 Alibaba Group Holding 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 com.alibaba.csp.sentinel.slotchain;
import java.lang.reflect.Method;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.util.IdUtil;
import com.alibaba.csp.sentinel.util.MethodUtil;
/**
* Resource wrapper for method invocation.
*
* @author qinan.qn
*/
public class MethodResourceWrapper extends ResourceWrapper {
private transient Method method;
public MethodResourceWrapper(Method method, EntryType type) {
this.method = method;
this.name = MethodUtil.resolveMethodName(method);
this.type = type;
}
@Override
public String getName() {
return name;
}
public Method getMethod() {
return method;
}
@Override
public String getShowName() {
return IdUtil.truncate(this.name);
}
@Override
public EntryType getType() {
return type;
}
}
|
Fix the bug that resource name displayed in ClusterNode-related command APIs for SphU.entry(method) is incorrect (#1078)
Signed-off-by: Eric Zhao <54dcf17c32e75a259f2bfe73070341693c64c950@gmail.com>
|
sentinel-core/src/main/java/com/alibaba/csp/sentinel/slotchain/MethodResourceWrapper.java
|
Fix the bug that resource name displayed in ClusterNode-related command APIs for SphU.entry(method) is incorrect (#1078)
|
|
Java
|
apache-2.0
|
ba9b83410cbef0e72e923057c91c947a8ba33bcc
| 0
|
Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math
|
/*
* 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.commons.math.distribution;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.math.exception.MathArithmeticException;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.fraction.BigFraction;
import org.apache.commons.math.fraction.FractionConversionException;
import org.apache.commons.math.linear.Array2DRowFieldMatrix;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.FieldMatrix;
import org.apache.commons.math.linear.RealMatrix;
/**
* The default implementation of {@link KolmogorovSmirnovDistribution}.
*
* @version $Revision$ $Date$
*/
public class KolmogorovSmirnovDistributionImpl implements KolmogorovSmirnovDistribution, Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = -4670676796862967187L;
private int n;
/**
* @param n Number of observations
* @throws NotStrictlyPositiveException
* if n <= 0
*/
public KolmogorovSmirnovDistributionImpl(int n) {
if (n <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.NOT_POSITIVE_NUMBER_OF_SAMPLES, n);
}
this.n = n;
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above). The
* result is not exact as with
* {@link KolmogorovSmirnovDistributionImpl#cdfExact(double)} because
* calculations are based on double rather than
* {@link org.apache.commons.math.fraction.BigFraction}.
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
public double cdf(double d) throws MathArithmeticException {
return this.cdf(d, false);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above).
* The result is exact in the sense that BigFraction/BigReal is used everywhere
* at the expense of very slow execution time. Almost never choose this in
* real applications unless you are very sure; this is almost solely for
* verification purposes. Normally, you would choose
* {@link KolmogorovSmirnovDistributionImpl#cdf(double)}
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
public double cdfExact(double d) throws MathArithmeticException {
return this.cdf(d, true);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above).
*
* @param d statistic
* @param exact
* whether the probability should be calculated exact using
* BigFraction everywhere at the expense of very
* slow execution time, or if double should be used convenient
* places to gain speed. Never choose true in real applications
* unless you are very sure; true is almost solely for
* verification purposes.
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
public double cdf(double d, boolean exact)
throws MathArithmeticException {
final int n = this.n;
final double ninv = 1 / ((double) n);
final double ninvhalf = 0.5 * ninv;
if (d <= ninvhalf) {
return 0;
} else if (ninvhalf < d && d <= ninv) {
double res = 1;
double f = 2 * d - ninv;
// n! f^n = n*f * (n-1)*f * ... * 1*x
for (int i = 1; i <= n; ++i) {
res *= i * f;
}
return res;
} else if (1 - ninv <= d && d < 1) {
return 1 - 2 * Math.pow(1 - d, n);
} else if (1 <= d) {
return 1;
}
return (exact) ? this.exactK(d) : this.roundedK(d);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} exact using method
* described in [1] and BigFraction (see above).
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private double exactK(double d)
throws MathArithmeticException {
final int n = this.n;
final int k = (int) Math.ceil(n * d);
final FieldMatrix<BigFraction> H = this.createH(d);
final FieldMatrix<BigFraction> Hpower = H.power(n);
BigFraction pFrac = Hpower.getEntry(k - 1, k - 1);
for (int i = 1; i <= n; ++i) {
pFrac = pFrac.multiply(i).divide(n);
}
/*
* BigFraction.doubleValue converts numerator to double and the
* denominator to double and divides afterwards. That gives NaN quite
* easy. This does not (scale is the number of digits):
*/
return pFrac.bigDecimalValue(20, BigDecimal.ROUND_HALF_UP)
.doubleValue();
}
/**
* Calculates <code>P(D<sub>n</sup> < d)</code> using method described in
* [1] and doubles (see above).
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private double roundedK(double d)
throws MathArithmeticException {
final int n = this.n;
final int k = (int) Math.ceil(n * d);
final FieldMatrix<BigFraction> HBigFraction = this.createH(d);
final int m = HBigFraction.getRowDimension();
/*
* Here the rounding part comes into play: use
* RealMatrix instead of FieldMatrix<BigFraction>
*/
final RealMatrix H = new Array2DRowRealMatrix(m, m);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
H.setEntry(i, j, HBigFraction.getEntry(i, j).doubleValue());
}
}
final RealMatrix Hpower = H.power(n);
double pFrac = Hpower.getEntry(k - 1, k - 1);
for (int i = 1; i <= n; ++i) {
pFrac *= (double)i / (double)n;
}
return pFrac;
}
/***
* Creates H of size m x m as described in [1] (see above).
*
* @param d statistic
*
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing x as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private FieldMatrix<BigFraction> createH(double d)
throws MathArithmeticException {
int n = this.n;
int k = (int) Math.ceil(n * d);
int m = 2 * k - 1;
double hDouble = k - n * d;
if (hDouble >= 1) {
throw new ArithmeticException("Could not ");
}
BigFraction h = null;
try {
h = new BigFraction(hDouble, 1.0e-20, 10000);
} catch (FractionConversionException e1) {
try {
h = new BigFraction(hDouble, 1.0e-10, 10000);
} catch (FractionConversionException e2) {
try {
h = new BigFraction(hDouble, 1.0e-5, 10000);
} catch (FractionConversionException e3) {
//throw new MathArithmeticException(hDouble, 10000);
throw new MathArithmeticException(LocalizedFormats.CANNOT_CONVERT_OBJECT_TO_FRACTION, hDouble);
}
}
}
final BigFraction[][] Hdata = new BigFraction[m][m];
/*
* Start by filling everything with either 0 or 1.
*/
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
if (i - j + 1 < 0)
Hdata[i][j] = BigFraction.ZERO;
else
Hdata[i][j] = BigFraction.ONE;
}
}
/*
* Setting up power-array to avoid calculating the same value twice:
* hPowers[0] = h^1 ... hPowers[m-1] = h^m
*/
final BigFraction[] hPowers = new BigFraction[m];
hPowers[0] = h;
for (int i = 1; i < m; ++i) {
hPowers[i] = h.multiply(hPowers[i - 1]);
}
/*
* First column and last row has special values (each other reversed).
*/
for (int i = 0; i < m; ++i) {
Hdata[i][0] = Hdata[i][0].subtract(hPowers[i]);
Hdata[m - 1][i] = Hdata[m - 1][i].subtract(hPowers[m - i - 1]);
}
/*
* [1] states: "For 1/2 < h < 1 the bottom left element of the matrix
* should be (1 - 2*h^m + (2h - 1)^m )/m!" Since 0 <= h < 1, then if h >
* 1/2 is sufficient to check:
*/
if (h.compareTo(BigFraction.ONE_HALF) == 1) {
Hdata[m - 1][0] = Hdata[m - 1][0].add(h.multiply(2).subtract(1)
.pow(m));
}
/*
* Aside from the first column and last row, the (i, j)-th element is
* 1/(i - j + 1)! if i − j + 1 >= 0, else 0. 1's and 0's are already
* put, so only division with (i - j + 1)! is needed in the elements
* that have 1's. There is no need to calculate (i - j + 1)! and then
* divide - small steps avoid overflows.
*
* Note that i - j + 1 > 0 <=> i + 1 > j instead of j'ing all the way to
* m. Also note that it is started at g = 2 because dividing by 1 isn't
* really necessary.
*/
for (int i = 0; i < m; ++i) {
for (int j = 0; j < i + 1; ++j) {
if (i - j + 1 > 0) {
for (int g = 2; g <= i - j + 1; ++g) {
Hdata[i][j] = Hdata[i][j].divide(g);
}
}
}
}
return new Array2DRowFieldMatrix<BigFraction>(Hdata);
}
}
|
src/main/java/org/apache/commons/math/distribution/KolmogorovSmirnovDistributionImpl.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.commons.math.distribution;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.math.exception.MathArithmeticException;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.fraction.BigFraction;
import org.apache.commons.math.fraction.FractionConversionException;
import org.apache.commons.math.linear.Array2DRowFieldMatrix;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.FieldMatrix;
import org.apache.commons.math.linear.RealMatrix;
/**
* The default implementation of {@link KolmogorovSmirnovDistribution}.
*
* @version $Revision$ $Date$
*/
public class KolmogorovSmirnovDistributionImpl implements KolmogorovSmirnovDistribution, Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = -4670676796862967187L;
private int n;
/**
* @param n Number of observations
* @throws NotStrictlyPositiveException
* if n <= 0
*/
public KolmogorovSmirnovDistributionImpl(int n) {
if (n <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.NOT_POSITIVE_NUMBER_OF_SAMPLES, n);
}
this.n = n;
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above). The
* result is not exact as with
* {@link KolmogorovSmirnovDistributionImpl#cdfExact(double)} because
* calculations are based on double rather than
* {@link org.apache.commons.math.fraction.BigFraction}.
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
@Override
public double cdf(double d) throws MathArithmeticException {
return this.cdf(d, false);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above).
* The result is exact in the sense that BigFraction/BigReal is used everywhere
* at the expense of very slow execution time. Almost never choose this in
* real applications unless you are very sure; this is almost solely for
* verification purposes. Normally, you would choose
* {@link KolmogorovSmirnovDistributionImpl#cdf(double)}
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
public double cdfExact(double d) throws MathArithmeticException {
return this.cdf(d, true);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} using method described in
* [1] with quick decisions for extreme values given in [2] (see above).
*
* @param d statistic
* @param exact
* whether the probability should be calculated exact using
* BigFraction everywhere at the expense of very
* slow execution time, or if double should be used convenient
* places to gain speed. Never choose true in real applications
* unless you are very sure; true is almost solely for
* verification purposes.
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
public double cdf(double d, boolean exact)
throws MathArithmeticException {
final int n = this.n;
final double ninv = 1 / ((double) n);
final double ninvhalf = 0.5 * ninv;
if (d <= ninvhalf) {
return 0;
} else if (ninvhalf < d && d <= ninv) {
double res = 1;
double f = 2 * d - ninv;
// n! f^n = n*f * (n-1)*f * ... * 1*x
for (int i = 1; i <= n; ++i) {
res *= i * f;
}
return res;
} else if (1 - ninv <= d && d < 1) {
return 1 - 2 * Math.pow(1 - d, n);
} else if (1 <= d) {
return 1;
}
return (exact) ? this.exactK(d) : this.roundedK(d);
}
/**
* Calculates {@code P(D<sub>n</sup> < d)} exact using method
* described in [1] and BigFraction (see above).
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private double exactK(double d)
throws MathArithmeticException {
final int n = this.n;
final int k = (int) Math.ceil(n * d);
final FieldMatrix<BigFraction> H = this.createH(d);
final FieldMatrix<BigFraction> Hpower = H.power(n);
BigFraction pFrac = Hpower.getEntry(k - 1, k - 1);
for (int i = 1; i <= n; ++i) {
pFrac = pFrac.multiply(i).divide(n);
}
/*
* BigFraction.doubleValue converts numerator to double and the
* denominator to double and divides afterwards. That gives NaN quite
* easy. This does not (scale is the number of digits):
*/
return pFrac.bigDecimalValue(20, BigDecimal.ROUND_HALF_UP)
.doubleValue();
}
/**
* Calculates <code>P(D<sub>n</sup> < d)</code> using method described in
* [1] and doubles (see above).
*
* @param d statistic
* @return the two-sided probability of {@code P(D<sub>n</sup> < d)}
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing d as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private double roundedK(double d)
throws MathArithmeticException {
final int n = this.n;
final int k = (int) Math.ceil(n * d);
final FieldMatrix<BigFraction> HBigFraction = this.createH(d);
final int m = HBigFraction.getRowDimension();
/*
* Here the rounding part comes into play: use
* RealMatrix instead of FieldMatrix<BigFraction>
*/
final RealMatrix H = new Array2DRowRealMatrix(m, m);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
H.setEntry(i, j, HBigFraction.getEntry(i, j).doubleValue());
}
}
final RealMatrix Hpower = H.power(n);
double pFrac = Hpower.getEntry(k - 1, k - 1);
for (int i = 1; i <= n; ++i) {
pFrac *= (double)i / (double)n;
}
return pFrac;
}
/***
* Creates H of size m x m as described in [1] (see above).
*
* @param d statistic
*
* @throws MathArithmeticException
* if algorithm fails to convert h to a BigFraction in
* expressing x as (k - h) / m for integer k, m and 0 <= h < 1.
*/
private FieldMatrix<BigFraction> createH(double d)
throws MathArithmeticException {
int n = this.n;
int k = (int) Math.ceil(n * d);
int m = 2 * k - 1;
double hDouble = k - n * d;
if (hDouble >= 1) {
throw new ArithmeticException("Could not ");
}
BigFraction h = null;
try {
h = new BigFraction(hDouble, 1.0e-20, 10000);
} catch (FractionConversionException e1) {
try {
h = new BigFraction(hDouble, 1.0e-10, 10000);
} catch (FractionConversionException e2) {
try {
h = new BigFraction(hDouble, 1.0e-5, 10000);
} catch (FractionConversionException e3) {
//throw new MathArithmeticException(hDouble, 10000);
throw new MathArithmeticException(LocalizedFormats.CANNOT_CONVERT_OBJECT_TO_FRACTION, hDouble);
}
}
}
final BigFraction[][] Hdata = new BigFraction[m][m];
/*
* Start by filling everything with either 0 or 1.
*/
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
if (i - j + 1 < 0)
Hdata[i][j] = BigFraction.ZERO;
else
Hdata[i][j] = BigFraction.ONE;
}
}
/*
* Setting up power-array to avoid calculating the same value twice:
* hPowers[0] = h^1 ... hPowers[m-1] = h^m
*/
final BigFraction[] hPowers = new BigFraction[m];
hPowers[0] = h;
for (int i = 1; i < m; ++i) {
hPowers[i] = h.multiply(hPowers[i - 1]);
}
/*
* First column and last row has special values (each other reversed).
*/
for (int i = 0; i < m; ++i) {
Hdata[i][0] = Hdata[i][0].subtract(hPowers[i]);
Hdata[m - 1][i] = Hdata[m - 1][i].subtract(hPowers[m - i - 1]);
}
/*
* [1] states: "For 1/2 < h < 1 the bottom left element of the matrix
* should be (1 - 2*h^m + (2h - 1)^m )/m!" Since 0 <= h < 1, then if h >
* 1/2 is sufficient to check:
*/
if (h.compareTo(BigFraction.ONE_HALF) == 1) {
Hdata[m - 1][0] = Hdata[m - 1][0].add(h.multiply(2).subtract(1)
.pow(m));
}
/*
* Aside from the first column and last row, the (i, j)-th element is
* 1/(i - j + 1)! if i − j + 1 >= 0, else 0. 1's and 0's are already
* put, so only division with (i - j + 1)! is needed in the elements
* that have 1's. There is no need to calculate (i - j + 1)! and then
* divide - small steps avoid overflows.
*
* Note that i - j + 1 > 0 <=> i + 1 > j instead of j'ing all the way to
* m. Also note that it is started at g = 2 because dividing by 1 isn't
* really necessary.
*/
for (int i = 0; i < m; ++i) {
for (int j = 0; j < i + 1; ++j) {
if (i - j + 1 > 0) {
for (int g = 2; g <= i - j + 1; ++g) {
Hdata[i][j] = Hdata[i][j].divide(g);
}
}
}
}
return new Array2DRowFieldMatrix<BigFraction>(Hdata);
}
}
|
Remove invalid @Override annotation
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1083734 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/math/distribution/KolmogorovSmirnovDistributionImpl.java
|
Remove invalid @Override annotation
|
|
Java
|
apache-2.0
|
9658f5f40072a23749b3c817db262ebf94a8d76e
| 0
|
Vedenin/java_collections_overview,Vedenin/java_in_examples
|
package com.github.vedenin.eng.other;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import com.google.common.base.Charsets;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
/**
* Created by vedenin on 15.01.16.
*/
public class IOTest {
public static void main(String[] s) throws Exception {
convertStringToOrFromInputStream();
}
private static void convertStringToOrFromInputStream() throws IOException {
/* 1. Using Apache Utils */
// convert String to InputStream
InputStream inputStreamApache = IOUtils.toInputStream("test1", StandardCharsets.UTF_8);
// convert InputStream to String
String stringApache = IOUtils.toString(inputStreamApache, StandardCharsets.UTF_8);
System.out.println(stringApache); // print test1
/* 2. Using JDK */
// convert String to InputStream
InputStream inputStreamJDK = new ByteArrayInputStream("test2".getBytes(StandardCharsets.UTF_8));
// convert InputStream to String
BufferedReader str = new BufferedReader(new InputStreamReader(inputStreamJDK));
String stringJDK = str.readLine();
System.out.println(stringJDK); // print test2
/* 3. Using guava */
// convert String to InputStream
InputStream targetStreamGuava = new ReaderInputStream(CharSource.wrap("test3").openStream());
// convert InputStream to String
String stringGuava = CharStreams.toString(new InputStreamReader(targetStreamGuava, Charsets.UTF_8));
System.out.println(stringGuava); // print test3
/* 4. Using JDK and Scanner*/
InputStream inputStreamForScanner = new ReaderInputStream(CharSource.wrap("test4").openStream());
// convert InputStream to String
java.util.Scanner s = new java.util.Scanner(inputStreamForScanner).useDelimiter("\\A");
String stringScanner = s.hasNext() ? s.next() : "";
System.out.println(stringScanner);
/* 5. Using Java 8 */
InputStream inputStreamForJava8 = new ReaderInputStream(CharSource.wrap("test5").openStream());
// convert InputStream to String
String stringJava8 = new BufferedReader(new InputStreamReader(inputStreamForJava8)).lines().collect(Collectors.joining("\n"));
System.out.println(stringJava8);
}
}
|
src/com/github/vedenin/eng/other/IOTest.java
|
package com.github.vedenin.eng.other;
import java.io.*;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
/**
* Created by vedenin on 15.01.16.
*/
public class IOTest {
public static void main(String[] s) throws Exception {
// convert String to InputStream using Apache Utils
InputStream in = IOUtils.toInputStream("test1", StandardCharsets.UTF_8);
// convert InputStream to String using Apache Utils
String myString = IOUtils.toString(in, StandardCharsets.UTF_8);
System.out.println(myString); // print test1
// convert String to InputStream
InputStream stream = new ByteArrayInputStream("test2".getBytes(StandardCharsets.UTF_8));
// convert InputStream to String using Apache Utils
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer, StandardCharsets.UTF_8);
String theString = writer.toString();
System.out.println(theString); // print test2
InputStream myInputStream = IOUtils.toInputStream("test3", "UTF-8");
// convert InputStream to String
InputStreamReader i = new InputStreamReader(myInputStream);
BufferedReader str = new BufferedReader(i);
String msg = str.readLine();
System.out.println(msg);
}
}
|
[JPO-13] Change IOTest
|
src/com/github/vedenin/eng/other/IOTest.java
|
[JPO-13] Change IOTest
|
|
Java
|
apache-2.0
|
6ac551bebee6d7684483c8835f4fa339f3bc5b3f
| 0
|
lmdbjava/lmdbjava
|
/*-
* #%L
* LmdbJava
* %%
* Copyright (C) 2016 - 2018 The LmdbJava Open Source Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.lmdbjava;
import static java.lang.Long.reverseBytes;
import static java.lang.ThreadLocal.withInitial;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import static java.nio.ByteOrder.BIG_ENDIAN;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import java.util.ArrayDeque;
import static java.util.Objects.requireNonNull;
import jnr.ffi.Pointer;
import static org.lmdbjava.Env.SHOULD_CHECK;
import static org.lmdbjava.UnsafeAccess.UNSAFE;
/**
* {@link ByteBuffer}-based proxy.
*
* <p>
* There are two concrete {@link ByteBuffer} proxy implementations available:
* <ul>
* <li>A "fast" implementation: {@link UnsafeProxy}</li>
* <li>A "safe" implementation: {@link ReflectiveProxy}</li>
* </ul>
*
* <p>
* Users nominate which implementation they prefer by referencing the
* {@link #PROXY_OPTIMAL} or {@link #PROXY_SAFE} field when invoking
* {@link Env#create(org.lmdbjava.BufferProxy)}.
*/
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public final class ByteBufferProxy {
/**
* The fastest {@link ByteBuffer} proxy that is available on this platform.
* This will always be the same instance as {@link #PROXY_SAFE} if the
* {@link UnsafeAccess#DISABLE_UNSAFE_PROP} has been set to <code>true</code>
* and/or {@link UnsafeAccess} is unavailable. Guaranteed to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_OPTIMAL;
/**
* The safe, reflective {@link ByteBuffer} proxy for this system. Guaranteed
* to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_SAFE;
static {
PROXY_SAFE = new ReflectiveProxy();
PROXY_OPTIMAL = getProxyOptimal();
}
private ByteBufferProxy() {
}
private static BufferProxy<ByteBuffer> getProxyOptimal() {
try {
return new UnsafeProxy();
} catch (final RuntimeException e) {
return PROXY_SAFE;
}
}
/**
* The buffer must be a direct buffer (not heap allocated).
*/
public static final class BufferMustBeDirectException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public BufferMustBeDirectException() {
super("The buffer must be a direct buffer (not heap allocated");
}
}
/**
* Provides {@link ByteBuffer} pooling and address resolution for concrete
* {@link BufferProxy} implementations.
*/
abstract static class AbstractByteBufferProxy extends BufferProxy<ByteBuffer> {
protected static final String FIELD_NAME_ADDRESS = "address";
protected static final String FIELD_NAME_CAPACITY = "capacity";
/**
* A thread-safe pool for a given length. If the buffer found is valid (ie
* not of a negative length) then that buffer is used. If no valid buffer is
* found, a new buffer is created.
*/
private static final ThreadLocal<ArrayDeque<ByteBuffer>> BUFFERS
= withInitial(() -> new ArrayDeque<>(16));
/**
* Lexicographically compare two buffers.
*
* @param o1 left operand (required)
* @param o2 right operand (required)
* @return as specified by {@link Comparable} interface
*/
@SuppressWarnings({"checkstyle:ReturnCount", "PMD.CyclomaticComplexity"})
public static int compareBuff(final ByteBuffer o1, final ByteBuffer o2) {
requireNonNull(o1);
requireNonNull(o2);
if (o1.equals(o2)) {
return 0;
}
final int minLength = Math.min(o1.limit(), o2.limit());
final int minWords = minLength / Long.BYTES;
final boolean reverse1 = o1.order() == LITTLE_ENDIAN;
final boolean reverse2 = o1.order() == LITTLE_ENDIAN;
for (int i = 0; i < minWords * Long.BYTES; i += Long.BYTES) {
final long lw = reverse1 ? reverseBytes(o1.getLong(i)) : o1.getLong(i);
final long rw = reverse2 ? reverseBytes(o2.getLong(i)) : o2.getLong(i);
final int diff = Long.compareUnsigned(lw, rw);
if (diff != 0) {
return diff;
}
}
for (int i = minWords * Long.BYTES; i < minLength; i++) {
final int lw = Byte.toUnsignedInt(o1.get(i));
final int rw = Byte.toUnsignedInt(o2.get(i));
final int result = Integer.compareUnsigned(lw, rw);
if (result != 0) {
return result;
}
}
return o1.capacity() - o2.capacity();
}
static Field findField(final Class<?> c, final String name) {
Class<?> clazz = c;
do {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
throw new LmdbException(name + " not found");
}
protected final long address(final ByteBuffer buffer) {
if (SHOULD_CHECK && !buffer.isDirect()) {
throw new BufferMustBeDirectException();
}
return ((sun.nio.ch.DirectBuffer) buffer).address() + buffer.position();
}
@Override
protected final ByteBuffer allocate() {
final ArrayDeque<ByteBuffer> queue = BUFFERS.get();
final ByteBuffer buffer = queue.poll();
if (buffer != null && buffer.capacity() >= 0) {
return buffer;
} else {
return allocateDirect(0);
}
}
@Override
protected final int compare(final ByteBuffer o1, final ByteBuffer o2) {
return compareBuff(o1, o2);
}
@Override
protected final void deallocate(final ByteBuffer buff) {
buff.order(BIG_ENDIAN);
final ArrayDeque<ByteBuffer> queue = BUFFERS.get();
queue.offer(buff);
}
@Override
protected byte[] getBytes(final ByteBuffer buffer) {
final byte[] dest = new byte[buffer.limit()];
buffer.get(dest, 0, buffer.limit());
return dest;
}
}
/**
* A proxy that uses Java reflection to modify byte buffer fields, and
* official JNR-FFF methods to manipulate native pointers.
*/
private static final class ReflectiveProxy extends AbstractByteBufferProxy {
private static final Field ADDRESS_FIELD;
private static final Field CAPACITY_FIELD;
static {
ADDRESS_FIELD = findField(Buffer.class, FIELD_NAME_ADDRESS);
CAPACITY_FIELD = findField(Buffer.class, FIELD_NAME_CAPACITY);
}
@Override
protected void in(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, address(buffer));
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, buffer.remaining());
}
@Override
protected void in(final ByteBuffer buffer, final int size, final Pointer ptr,
final long ptrAddr) {
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, size);
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected ByteBuffer out(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
final long addr = ptr.getLong(STRUCT_FIELD_OFFSET_DATA);
final long size = ptr.getLong(STRUCT_FIELD_OFFSET_SIZE);
try {
ADDRESS_FIELD.set(buffer, addr);
CAPACITY_FIELD.set(buffer, (int) size);
} catch (final IllegalArgumentException | IllegalAccessException e) {
throw new LmdbException("Cannot modify buffer", e);
}
buffer.clear();
return buffer;
}
}
/**
* A proxy that uses Java's "unsafe" class to directly manipulate byte buffer
* fields and JNR-FFF allocated memory pointers.
*/
private static final class UnsafeProxy extends AbstractByteBufferProxy {
private static final long ADDRESS_OFFSET;
private static final long CAPACITY_OFFSET;
static {
try {
final Field address = findField(Buffer.class, FIELD_NAME_ADDRESS);
final Field capacity = findField(Buffer.class, FIELD_NAME_CAPACITY);
ADDRESS_OFFSET = UNSAFE.objectFieldOffset(address);
CAPACITY_OFFSET = UNSAFE.objectFieldOffset(capacity);
} catch (final SecurityException e) {
throw new LmdbException("Field access error", e);
}
}
@Override
protected void in(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, buffer.remaining());
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected void in(final ByteBuffer buffer, final int size, final Pointer ptr,
final long ptrAddr) {
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, size);
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected ByteBuffer out(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
final long addr = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA);
final long size = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE);
UNSAFE.putLong(buffer, ADDRESS_OFFSET, addr);
UNSAFE.putInt(buffer, CAPACITY_OFFSET, (int) size);
buffer.clear();
return buffer;
}
}
}
|
src/main/java/org/lmdbjava/ByteBufferProxy.java
|
/*-
* #%L
* LmdbJava
* %%
* Copyright (C) 2016 - 2018 The LmdbJava Open Source Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.lmdbjava;
import static java.lang.Long.reverseBytes;
import static java.lang.ThreadLocal.withInitial;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import static java.nio.ByteOrder.BIG_ENDIAN;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import java.util.ArrayDeque;
import static java.util.Objects.requireNonNull;
import jnr.ffi.Pointer;
import static org.lmdbjava.Env.SHOULD_CHECK;
import static org.lmdbjava.UnsafeAccess.UNSAFE;
/**
* {@link ByteBuffer}-based proxy.
*
* <p>
* There are two concrete {@link ByteBuffer} proxy implementations available:
* <ul>
* <li>A "fast" implementation: {@link UnsafeProxy}</li>
* <li>A "safe" implementation: {@link ReflectiveProxy}</li>
* </ul>
*
* <p>
* Users nominate which implementation they prefer by referencing the
* {@link #PROXY_OPTIMAL} or {@link #PROXY_SAFE} field when invoking
* {@link Env#create(org.lmdbjava.BufferProxy)}.
*/
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public final class ByteBufferProxy {
/**
* The fastest {@link ByteBuffer} proxy that is available on this platform.
* This will always be the same instance as {@link #PROXY_SAFE} if the
* {@link UnsafeAccess#DISABLE_UNSAFE_PROP} has been set to <code>true</code>
* and/or {@link UnsafeAccess} is unavailable. Guaranteed to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_OPTIMAL;
/**
* The safe, reflective {@link ByteBuffer} proxy for this system. Guaranteed
* to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_SAFE;
static {
PROXY_SAFE = new ReflectiveProxy();
PROXY_OPTIMAL = getProxyOptimal();
}
private ByteBufferProxy() {
}
private static BufferProxy<ByteBuffer> getProxyOptimal() {
try {
return new UnsafeProxy();
} catch (final RuntimeException e) {
return PROXY_SAFE;
}
}
/**
* The buffer must be a direct buffer (not heap allocated).
*/
public static final class BufferMustBeDirectException extends LmdbException {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance.
*/
public BufferMustBeDirectException() {
super("The buffer must be a direct buffer (not heap allocated");
}
}
/**
* Provides {@link ByteBuffer} pooling and address resolution for concrete
* {@link BufferProxy} implementations.
*/
abstract static class AbstractByteBufferProxy extends BufferProxy<ByteBuffer> {
protected static final String FIELD_NAME_ADDRESS = "address";
protected static final String FIELD_NAME_CAPACITY = "capacity";
/**
* A thread-safe pool for a given length. If the buffer found is valid (ie
* not of a negative length) then that buffer is used. If no valid buffer is
* found, a new buffer is created.
*/
private static final ThreadLocal<ArrayDeque<ByteBuffer>> BUFFERS
= withInitial(() -> new ArrayDeque<>(16));
/**
* Lexicographically compare two buffers.
*
* @param o1 left operand (required)
* @param o2 right operand (required)
* @return as specified by {@link Comparable} interface
*/
@SuppressWarnings({"checkstyle:ReturnCount", "PMD.CyclomaticComplexity"})
public static int compareBuff(final ByteBuffer o1, final ByteBuffer o2) {
requireNonNull(o1);
requireNonNull(o2);
if (o1.equals(o2)) {
return 0;
}
final int minLength = Math.min(o1.capacity(), o2.capacity());
final int minWords = minLength / Long.BYTES;
final boolean reverse1 = o1.order() == LITTLE_ENDIAN;
final boolean reverse2 = o1.order() == LITTLE_ENDIAN;
for (int i = 0; i < minWords * Long.BYTES; i += Long.BYTES) {
final long lw = reverse1 ? reverseBytes(o1.getLong(i)) : o1.getLong(i);
final long rw = reverse2 ? reverseBytes(o2.getLong(i)) : o2.getLong(i);
final int diff = Long.compareUnsigned(lw, rw);
if (diff != 0) {
return diff;
}
}
for (int i = minWords * Long.BYTES; i < minLength; i++) {
final int lw = Byte.toUnsignedInt(o1.get(i));
final int rw = Byte.toUnsignedInt(o2.get(i));
final int result = Integer.compareUnsigned(lw, rw);
if (result != 0) {
return result;
}
}
return o1.capacity() - o2.capacity();
}
static Field findField(final Class<?> c, final String name) {
Class<?> clazz = c;
do {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
throw new LmdbException(name + " not found");
}
protected final long address(final ByteBuffer buffer) {
if (SHOULD_CHECK && !buffer.isDirect()) {
throw new BufferMustBeDirectException();
}
return ((sun.nio.ch.DirectBuffer) buffer).address() + buffer.position();
}
@Override
protected final ByteBuffer allocate() {
final ArrayDeque<ByteBuffer> queue = BUFFERS.get();
final ByteBuffer buffer = queue.poll();
if (buffer != null && buffer.capacity() >= 0) {
return buffer;
} else {
return allocateDirect(0);
}
}
@Override
protected final int compare(final ByteBuffer o1, final ByteBuffer o2) {
return compareBuff(o1, o2);
}
@Override
protected final void deallocate(final ByteBuffer buff) {
buff.order(BIG_ENDIAN);
final ArrayDeque<ByteBuffer> queue = BUFFERS.get();
queue.offer(buff);
}
@Override
protected byte[] getBytes(final ByteBuffer buffer) {
final byte[] dest = new byte[buffer.limit()];
buffer.get(dest, 0, buffer.limit());
return dest;
}
}
/**
* A proxy that uses Java reflection to modify byte buffer fields, and
* official JNR-FFF methods to manipulate native pointers.
*/
private static final class ReflectiveProxy extends AbstractByteBufferProxy {
private static final Field ADDRESS_FIELD;
private static final Field CAPACITY_FIELD;
static {
ADDRESS_FIELD = findField(Buffer.class, FIELD_NAME_ADDRESS);
CAPACITY_FIELD = findField(Buffer.class, FIELD_NAME_CAPACITY);
}
@Override
protected void in(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, address(buffer));
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, buffer.remaining());
}
@Override
protected void in(final ByteBuffer buffer, final int size, final Pointer ptr,
final long ptrAddr) {
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, size);
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected ByteBuffer out(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
final long addr = ptr.getLong(STRUCT_FIELD_OFFSET_DATA);
final long size = ptr.getLong(STRUCT_FIELD_OFFSET_SIZE);
try {
ADDRESS_FIELD.set(buffer, addr);
CAPACITY_FIELD.set(buffer, (int) size);
} catch (final IllegalArgumentException | IllegalAccessException e) {
throw new LmdbException("Cannot modify buffer", e);
}
buffer.clear();
return buffer;
}
}
/**
* A proxy that uses Java's "unsafe" class to directly manipulate byte buffer
* fields and JNR-FFF allocated memory pointers.
*/
private static final class UnsafeProxy extends AbstractByteBufferProxy {
private static final long ADDRESS_OFFSET;
private static final long CAPACITY_OFFSET;
static {
try {
final Field address = findField(Buffer.class, FIELD_NAME_ADDRESS);
final Field capacity = findField(Buffer.class, FIELD_NAME_CAPACITY);
ADDRESS_OFFSET = UNSAFE.objectFieldOffset(address);
CAPACITY_OFFSET = UNSAFE.objectFieldOffset(capacity);
} catch (final SecurityException e) {
throw new LmdbException("Field access error", e);
}
}
@Override
protected void in(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, buffer.remaining());
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected void in(final ByteBuffer buffer, final int size, final Pointer ptr,
final long ptrAddr) {
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, size);
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, address(buffer));
}
@Override
protected ByteBuffer out(final ByteBuffer buffer, final Pointer ptr,
final long ptrAddr) {
final long addr = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA);
final long size = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE);
UNSAFE.putLong(buffer, ADDRESS_OFFSET, addr);
UNSAFE.putInt(buffer, CAPACITY_OFFSET, (int) size);
buffer.clear();
return buffer;
}
}
}
|
fixes key range search by using limit instead of capacity in ByteBufferProxy compare
|
src/main/java/org/lmdbjava/ByteBufferProxy.java
|
fixes key range search by using limit instead of capacity in ByteBufferProxy compare
|
|
Java
|
apache-2.0
|
cd81b6fee49b9c2cb01e7e104e6cc73adfd1f5fa
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.search;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.Query;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public interface SearchWordQueryBuilder {
/**
* Orders to search word in files which contain {@code containerName} first.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder withContainerName(@Nullable String containerName);
/**
* Sets case sensitivity.<br/>
* The query is case sensitive by default, so this method might be used to make the query case insensitive.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder caseSensitive(boolean caseSensitive);
/**
* Orders to search occurrences in given contexts.
*
* @see com.intellij.psi.search.UsageSearchContext
*/
@Contract(value = "_, _ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inContexts(@NotNull SearchContext context, SearchContext @NotNull ... otherContexts);
/**
* Orders to search occurrences in given contexts.
*
* @see com.intellij.psi.search.UsageSearchContext
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inContexts(@NotNull Set<SearchContext> contexts);
/**
* Orders to search occurrences in given search scope.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inScope(@NotNull SearchScope searchScope);
/**
* Orders to search occurrences in files of given types.
*/
@Contract(value = "_, _ -> new", pure = true)
@NotNull
SearchWordQueryBuilder restrictFileTypes(@NotNull FileType fileType, FileType @NotNull ... fileTypes);
/**
* Orders to search occurrences in files of given language.
* <br/>
* For example {@code inFilesWithLanguage(JavaLanguage.INSTANCE)} will produce occurrences
* from Java files and JSP files (since JSP contains code with JavaLanguage)
* <p>
* This only checks the host file language.
* </p>
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inFilesWithLanguage(@NotNull Language language);
/**
* Orders to search occurrences in files of given language and its dialects.
* <p>
* Same as {@link #inFilesWithLanguage}, except the language is matched with dialects.
* </p>
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inFilesWithLanguageOfKind(@NotNull Language language);
/**
* Orders to include occurrences in language injections of any language as well as occurrences in host files.
*/
@Contract(value = "-> new", pure = true)
@NotNull
SearchWordQueryBuilder includeInjections();
/**
* Orders to search occurrences in language injections (instead of host files).
*/
@Contract(value = "-> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjections();
/**
* Orders to search occurrences in language injections (instead of host files) of given language.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjections(@NotNull Language language);
/**
* Orders to search occurrences in language injections (instead of host files) of given language and its dialects.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjectionsOfKind(@NotNull Language language);
/**
* @param mapper pure function which is run once per each occurrence
* @return query which returns results of applying the {@code mapper} to each occurrence
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
<T> Query<? extends T> buildQuery(@NotNull LeafOccurrenceMapper<T> mapper);
/**
* @return query which generates occurrences by traversing the tree up starting from the offset
*/
@Contract(value = "-> new", pure = true)
@NotNull
Query<? extends TextOccurrence> buildOccurrenceQuery();
}
|
platform/indexing-api/src/com/intellij/model/search/SearchWordQueryBuilder.java
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.search;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.Query;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public interface SearchWordQueryBuilder {
/**
* Orders to search word in files which contain {@code containerName} first.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder withContainerName(@Nullable String containerName);
/**
* Sets case sensitivity.<br/>
* The query is case sensitive by default, so this method might be used to make the query case insensitive.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder caseSensitive(boolean caseSensitive);
/**
* Orders to search occurrences in given contexts.
*
* @see com.intellij.psi.search.UsageSearchContext
*/
@Contract(value = "_, _ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inContexts(@NotNull SearchContext context, SearchContext @NotNull ... otherContexts);
/**
* Orders to search occurrences in given contexts.
*
* @see com.intellij.psi.search.UsageSearchContext
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inContexts(@NotNull Set<SearchContext> contexts);
/**
* Orders to search occurrences in given search scope.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inScope(@NotNull SearchScope searchScope);
/**
* Orders to search occurrences in files of given types.
*/
@Contract(value = "_, _ -> new", pure = true)
@NotNull
SearchWordQueryBuilder restrictFileTypes(@NotNull FileType fileType, FileType @NotNull ... fileTypes);
/**
* Orders to search occurrences in files of given language.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inFilesWithLanguage(@NotNull Language language);
/**
* Orders to search occurrences in files of given language and its dialects.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inFilesWithLanguageOfKind(@NotNull Language language);
/**
* Orders to include occurrences in language injections of any language as well as occurrences in host files.
*/
@Contract(value = "-> new", pure = true)
@NotNull
SearchWordQueryBuilder includeInjections();
/**
* Orders to search occurrences in language injections.
*/
@Contract(value = "-> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjections();
/**
* Orders to search occurrences in language injections of given language.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjections(@NotNull Language language);
/**
* Orders to search occurrences in language injections of given language and its dialects.
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
SearchWordQueryBuilder inInjectionsOfKind(@NotNull Language language);
/**
* @param mapper pure function which is run once per each occurrence
* @return query which returns results of applying the {@code mapper} to each occurrence
*/
@Contract(value = "_ -> new", pure = true)
@NotNull
<T> Query<? extends T> buildQuery(@NotNull LeafOccurrenceMapper<T> mapper);
/**
* @return query which generates occurrences by traversing the tree up starting from the offset
*/
@Contract(value = "-> new", pure = true)
@NotNull
Query<? extends TextOccurrence> buildOccurrenceQuery();
}
|
add notes about injections in SearchWordQueryBuilder docs
GitOrigin-RevId: 4305b8202513d71990ddfbb8aee00d0253a3d8f9
|
platform/indexing-api/src/com/intellij/model/search/SearchWordQueryBuilder.java
|
add notes about injections in SearchWordQueryBuilder docs
|
|
Java
|
bsd-2-clause
|
6217150c0e4a62f05f2e0849c8533487fd244f8b
| 0
|
RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools
|
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* 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
* HOLDER 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.rtg.vcf.eval;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.stream.Stream;
import com.rtg.launcher.CommonFlags;
import com.rtg.launcher.globals.GlobalFlags;
import com.rtg.launcher.globals.ToolsGlobalFlags;
import com.rtg.tabix.TabixIndexReader;
import com.rtg.tabix.TabixIndexer;
import com.rtg.util.Pair;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.diagnostic.ErrorType;
import com.rtg.util.diagnostic.NoTalkbackSlimException;
import com.rtg.util.intervals.ReferenceRanges;
import com.rtg.util.intervals.ReferenceRegions;
import com.rtg.util.io.FileUtils;
import com.rtg.util.io.IOUtils;
import com.rtg.vcf.ArrayVcfIterator;
import com.rtg.vcf.DecomposingVcfIterator;
import com.rtg.vcf.VcfIterator;
import com.rtg.vcf.VcfReader;
import com.rtg.vcf.VcfSortRefiner;
import com.rtg.vcf.VcfUtils;
import com.rtg.vcf.header.ContigField;
import com.rtg.vcf.header.VcfHeader;
/**
* Only load records when asked for
*/
class TabixVcfRecordSet implements VariantSet {
private final File mBaselineFile;
private final File mCallsFile;
private final Collection<Pair<String, Integer>> mNames = new ArrayList<>();
private final ReferenceRanges<String> mRanges;
private final ReferenceRegions mEvalRegions;
private final VcfHeader mBaseLineHeader;
private final VcfHeader mCalledHeader;
private final VariantFactory mBaselineFactory;
private final VariantFactory mCallsFactory;
private final Map<String, File> mBaselinePreprocessed = new HashMap<>();
private final Map<String, File> mCallsPreprocessed = new HashMap<>();
private final boolean mPassOnly;
private final int mMaxLength;
private final File mPreprocessDestDir;
private final boolean mPreprocess;
private int mBaselineSkipped;
private int mCallsSkipped;
TabixVcfRecordSet(File baselineFile, File calledFile,
ReferenceRanges<String> ranges, ReferenceRegions evalRegions,
Collection<Pair<String, Integer>> referenceNameOrdering,
String baselineSample, String callsSample,
boolean passOnly, boolean relaxedRef, int maxLength, File preprocessDestDir) throws IOException {
if (referenceNameOrdering == null) {
throw new NullPointerException();
}
if (preprocessDestDir != null && !preprocessDestDir.isDirectory()) {
throw new IllegalArgumentException();
}
mBaselineFile = baselineFile;
mCallsFile = calledFile;
final VcfHeader baselineHeader = VcfUtils.getHeader(baselineFile);
final VcfHeader calledHeader = VcfUtils.getHeader(calledFile);
mRanges = ranges;
mEvalRegions = evalRegions;
mPassOnly = passOnly;
mMaxLength = maxLength;
mPreprocessDestDir = preprocessDestDir;
mPreprocess = mPreprocessDestDir != null;
final Set<String> basenames = new TreeSet<>();
Collections.addAll(basenames, new TabixIndexReader(TabixIndexer.indexFileName(baselineFile)).sequenceNames());
final Set<String> callnames = new TreeSet<>();
Collections.addAll(callnames, new TabixIndexReader(TabixIndexer.indexFileName(calledFile)).sequenceNames());
final Set<String> basedeclarednames = new TreeSet<>(basenames);
for (ContigField c : baselineHeader.getContigLines()) {
basedeclarednames.add(c.getId());
}
final Set<String> calldeclarednames = new TreeSet<>(callnames);
for (ContigField c : calledHeader.getContigLines()) {
calldeclarednames.add(c.getId());
}
if (Collections.disjoint(basedeclarednames, calldeclarednames)) {
throw new NoTalkbackSlimException("There were no sequence names in common between the supplied baseline and called variant sets. Check they use the same reference and are non-empty.");
}
final Set<String> union = new HashSet<>(basenames);
union.addAll(callnames);
if (disjoint(union, referenceNameOrdering)) {
throw new NoTalkbackSlimException("There were no sequence names in common between the reference and the supplied variant sets."
+ " Check the correct reference is being used.");
}
final Set<String> referenceNames = new HashSet<>();
for (Pair<String, Integer> orderedNameLength : referenceNameOrdering) {
final String name = orderedNameLength.getA();
if (ranges.allAvailable() || ranges.containsSequence(name)) {
referenceNames.add(name);
if (basenames.contains(name)) {
if (callnames.contains(name)) {
mNames.add(orderedNameLength);
} else {
mNames.add(orderedNameLength);
Diagnostic.warning("Reference sequence " + name + " is used in baseline but not in calls.");
}
} else {
if (callnames.contains(name)) {
mNames.add(orderedNameLength);
Diagnostic.warning("Reference sequence " + name + " is used in calls but not in baseline.");
} else {
Diagnostic.userLog("Skipping reference sequence " + name + " that is used by neither baseline or calls.");
}
}
}
}
if (ranges.allAvailable()) {
for (String name : basenames) {
if (!referenceNames.contains(name)) {
Diagnostic.warning("Baseline variants for sequence " + name + " will be ignored as this sequence is not contained in the reference.");
}
}
for (String name : callnames) {
if (!referenceNames.contains(name)) {
Diagnostic.warning("Call set variants for sequence " + name + " will be ignored as this sequence is not contained in the reference.");
}
}
} else {
if (mNames.isEmpty()) {
throw new NoTalkbackSlimException("After applying regions there were no sequence names in common between the reference and the supplied variant sets."
+ " Check the regions supplied by --" + CommonFlags.RESTRICTION_FLAG + " or --" + CommonFlags.BED_REGIONS_FLAG + " are correct.");
}
}
mBaseLineHeader = mPreprocess ? addDecompositionHeader(baselineHeader) : baselineHeader;
mCalledHeader = mPreprocess ? addDecompositionHeader(calledHeader) : calledHeader;
mBaselineFactory = getVariantFactory(VariantSetType.BASELINE, mBaseLineHeader, baselineSample, relaxedRef);
mCallsFactory = getVariantFactory(VariantSetType.CALLS, mCalledHeader, callsSample, relaxedRef);
}
// This is pretty ick, but needed to ensure the main vcfeval output headers contain appropriate declarations created during decomposition
private VcfHeader addDecompositionHeader(VcfHeader baselineHeader) throws IOException {
return new DecomposingVcfIterator(new ArrayVcfIterator(baselineHeader), null, false).getHeader();
}
static VariantFactory getVariantFactory(VariantSetType type, VcfHeader header, String sampleName, boolean relaxedRef) {
final boolean explicitHalf = GlobalFlags.getBooleanValue(ToolsGlobalFlags.VCFEVAL_EXPLICIT_HALF_CALL);
final String f = VariantFactory.getFactoryName(type, sampleName);
switch (f) {
case VariantFactory.SAMPLE_FACTORY:
return new VariantFactory.SampleVariants(VcfUtils.getSampleIndexOrDie(header, sampleName, type.label()), relaxedRef, explicitHalf);
case VariantFactory.ALL_FACTORY:
return new VariantFactory.AllAlts(relaxedRef, explicitHalf);
default:
throw new RuntimeException("Could not determine variant factory for " + f);
}
}
private boolean disjoint(Set<String> names, Collection<Pair<String, Integer>> referenceNameOrdering) {
for (Pair<String, Integer> pair : referenceNameOrdering) {
if (names.contains(pair.getA())) {
return false;
}
}
return true;
}
@Override
public Pair<String, Map<VariantSetType, List<Variant>>> nextSet() throws IOException {
final Map<VariantSetType, List<Variant>> map = new EnumMap<>(VariantSetType.class);
final Iterator<Pair<String, Integer>> iterator = mNames.iterator();
if (!iterator.hasNext()) {
return null;
}
final Pair<String, Integer> nameLength = iterator.next();
mNames.remove(nameLength);
final String currentName = nameLength.getA();
final int currentLength = nameLength.getB();
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
final ReferenceRanges<String> subRanges = mRanges.forSequence(currentName);
final FutureTask<LoadedVariants> baseFuture = new FutureTask<>(new VcfRecordTabixCallable(mBaselineFile, subRanges, mEvalRegions, currentName, currentLength, VariantSetType.BASELINE, mBaselineFactory, mPassOnly, mMaxLength, mPreprocessDestDir));
final FutureTask<LoadedVariants> callFuture = new FutureTask<>(new VcfRecordTabixCallable(mCallsFile, subRanges, mEvalRegions, currentName, currentLength, VariantSetType.CALLS, mCallsFactory, mPassOnly, mMaxLength, mPreprocessDestDir));
executor.execute(baseFuture);
executor.execute(callFuture);
final LoadedVariants baseVars = baseFuture.get();
final LoadedVariants calledVars = callFuture.get();
map.put(VariantSetType.BASELINE, baseVars.mVariants);
map.put(VariantSetType.CALLS, calledVars.mVariants);
if (mPreprocess) {
Diagnostic.developerLog("Preprocessed VCF at " + baseVars.mPreprocessed);
Diagnostic.developerLog("Preprocessed VCF at " + calledVars.mPreprocessed);
mBaselinePreprocessed.put(currentName, baseVars.mPreprocessed);
mCallsPreprocessed.put(currentName, calledVars.mPreprocessed);
}
mBaselineSkipped += baseVars.mSkippedDuringLoading;
mCallsSkipped += calledVars.mSkippedDuringLoading;
Diagnostic.userLog("Reference " + currentName + " baseline contains " + map.get(VariantSetType.BASELINE).size() + " variants.");
Diagnostic.userLog("Reference " + currentName + " calls contains " + map.get(VariantSetType.CALLS).size() + " variants.");
} catch (final ExecutionException e) {
IOUtils.rethrow(e.getCause());
} catch (final InterruptedException e) {
throw new NoTalkbackSlimException(e, ErrorType.INFO_ERROR, e.getCause().getMessage());
} finally {
executor.shutdownNow();
}
return new Pair<>(currentName, map);
}
@Override
public VcfHeader baselineHeader() {
return mBaseLineHeader;
}
@Override
public VcfIterator getBaselineVariants(String sequenceName) throws IOException {
return new VcfSortRefiner(mPreprocess ? VcfReader.openVcfReader(mBaselinePreprocessed.get(sequenceName)) : VcfReader.openVcfReader(mBaselineFile, mRanges.forSequence(sequenceName)));
}
@Override
public VcfHeader calledHeader() {
return mCalledHeader;
}
@Override
public VcfIterator getCalledVariants(String sequenceName) throws IOException {
return new VcfSortRefiner(mPreprocess ? VcfReader.openVcfReader(mCallsPreprocessed.get(sequenceName)) : VcfReader.openVcfReader(mCallsFile, mRanges.forSequence(sequenceName)));
}
@Override
public int getNumberOfSkippedBaselineVariants() {
return mBaselineSkipped;
}
@Override
public int getNumberOfSkippedCalledVariants() {
return mCallsSkipped;
}
@Override
public void close() throws IOException {
if (mPreprocessDestDir != null) { // Delete all the intermediate files we created
final Collection<File> files = new HashSet<>();
Stream.concat(mBaselinePreprocessed.values().stream(), mCallsPreprocessed.values().stream()).forEach(vcf -> {
files.add(vcf);
files.add(TabixIndexer.indexFileName(vcf));
});
for (File todelete : files) {
if (todelete.exists() && !todelete.delete()) {
throw new IOException("Could not delete intermediate file: " + todelete);
}
}
if (FileUtils.isEmptyDir(mPreprocessDestDir)) { // Only do the directory delete if now empty
if (!mPreprocessDestDir.delete()) {
throw new IOException("Could not delete intermediate output dir: " + mPreprocessDestDir);
}
}
}
}
}
|
src/com/rtg/vcf/eval/TabixVcfRecordSet.java
|
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* 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
* HOLDER 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.rtg.vcf.eval;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.stream.Stream;
import com.rtg.launcher.CommonFlags;
import com.rtg.launcher.globals.GlobalFlags;
import com.rtg.launcher.globals.ToolsGlobalFlags;
import com.rtg.tabix.TabixIndexReader;
import com.rtg.tabix.TabixIndexer;
import com.rtg.util.Pair;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.diagnostic.ErrorType;
import com.rtg.util.diagnostic.NoTalkbackSlimException;
import com.rtg.util.intervals.ReferenceRanges;
import com.rtg.util.intervals.ReferenceRegions;
import com.rtg.util.io.FileUtils;
import com.rtg.util.io.IOUtils;
import com.rtg.vcf.ArrayVcfIterator;
import com.rtg.vcf.DecomposingVcfIterator;
import com.rtg.vcf.VcfIterator;
import com.rtg.vcf.VcfReader;
import com.rtg.vcf.VcfSortRefiner;
import com.rtg.vcf.VcfUtils;
import com.rtg.vcf.header.ContigField;
import com.rtg.vcf.header.VcfHeader;
/**
* Only load records when asked for
*/
class TabixVcfRecordSet implements VariantSet {
private final File mBaselineFile;
private final File mCallsFile;
private final Collection<Pair<String, Integer>> mNames = new ArrayList<>();
private final ReferenceRanges<String> mRanges;
private final ReferenceRegions mEvalRegions;
private final VcfHeader mBaseLineHeader;
private final VcfHeader mCalledHeader;
private final VariantFactory mBaselineFactory;
private final VariantFactory mCallsFactory;
private final Map<String, File> mBaselinePreprocessed = new HashMap<>();
private final Map<String, File> mCallsPreprocessed = new HashMap<>();
private final boolean mPassOnly;
private final int mMaxLength;
private final File mPreprocessDestDir;
private final boolean mPreprocess;
private int mBaselineSkipped;
private int mCallsSkipped;
TabixVcfRecordSet(File baselineFile, File calledFile,
ReferenceRanges<String> ranges, ReferenceRegions evalRegions,
Collection<Pair<String, Integer>> referenceNameOrdering,
String baselineSample, String callsSample,
boolean passOnly, boolean relaxedRef, int maxLength, File preprocessDestDir) throws IOException {
if (referenceNameOrdering == null) {
throw new NullPointerException();
}
if (preprocessDestDir != null && !preprocessDestDir.isDirectory()) {
throw new IllegalArgumentException();
}
mBaselineFile = baselineFile;
mCallsFile = calledFile;
final VcfHeader baselineHeader = VcfUtils.getHeader(baselineFile);
final VcfHeader calledHeader = VcfUtils.getHeader(calledFile);
mRanges = ranges;
mEvalRegions = evalRegions;
mPassOnly = passOnly;
mMaxLength = maxLength;
mPreprocessDestDir = preprocessDestDir;
mPreprocess = mPreprocessDestDir != null;
final Set<String> basenames = new TreeSet<>();
Collections.addAll(basenames, new TabixIndexReader(TabixIndexer.indexFileName(baselineFile)).sequenceNames());
final Set<String> callnames = new TreeSet<>();
Collections.addAll(callnames, new TabixIndexReader(TabixIndexer.indexFileName(calledFile)).sequenceNames());
final Set<String> basedeclarednames = new TreeSet<>(basenames);
for (ContigField c : baselineHeader.getContigLines()) {
basedeclarednames.add(c.getId());
}
final Set<String> calldeclarednames = new TreeSet<>(callnames);
for (ContigField c : calledHeader.getContigLines()) {
calldeclarednames.add(c.getId());
}
if (Collections.disjoint(basedeclarednames, calldeclarednames)) {
throw new NoTalkbackSlimException("There were no sequence names in common between the supplied baseline and called variant sets. Check they use the same reference and are non-empty.");
}
final Set<String> union = new HashSet<>(basenames);
union.addAll(callnames);
if (disjoint(union, referenceNameOrdering)) {
throw new NoTalkbackSlimException("There were no sequence names in common between the reference and the supplied variant sets."
+ " Check the correct reference is being used.");
}
final Set<String> referenceNames = new HashSet<>();
for (Pair<String, Integer> orderedNameLength : referenceNameOrdering) {
final String name = orderedNameLength.getA();
if (ranges.allAvailable() || ranges.containsSequence(name)) {
referenceNames.add(name);
if (basenames.contains(name)) {
if (callnames.contains(name)) {
mNames.add(orderedNameLength);
} else {
mNames.add(orderedNameLength);
Diagnostic.warning("Reference sequence " + name + " is used in baseline but not in calls.");
}
} else {
if (callnames.contains(name)) {
mNames.add(orderedNameLength);
Diagnostic.warning("Reference sequence " + name + " is used in calls but not in baseline.");
} else {
Diagnostic.userLog("Skipping reference sequence " + name + " that is used by neither baseline or calls.");
}
}
}
}
if (ranges.allAvailable()) {
for (String name : basenames) {
if (!referenceNames.contains(name)) {
Diagnostic.warning("Baseline variants for sequence " + name + " will be ignored as this sequence is not contained in the reference.");
}
}
for (String name : callnames) {
if (!referenceNames.contains(name)) {
Diagnostic.warning("Call set variants for sequence " + name + " will be ignored as this sequence is not contained in the reference.");
}
}
} else {
if (mNames.isEmpty()) {
throw new NoTalkbackSlimException("After applying regions there were no sequence names in common between the reference and the supplied variant sets."
+ " Check the regions supplied by --" + CommonFlags.RESTRICTION_FLAG + " or --" + CommonFlags.BED_REGIONS_FLAG + " are correct.");
}
}
mBaseLineHeader = mPreprocess ? addDecompositionHeader(baselineHeader) : baselineHeader;
mCalledHeader = mPreprocess ? addDecompositionHeader(calledHeader) : calledHeader;
mBaselineFactory = getVariantFactory(VariantSetType.BASELINE, mBaseLineHeader, baselineSample, relaxedRef);
mCallsFactory = getVariantFactory(VariantSetType.CALLS, mCalledHeader, callsSample, relaxedRef);
}
// This is pretty ick, but needed to ensure the main vcfeval output headers contain appropriate declarations created during decomposition
private VcfHeader addDecompositionHeader(VcfHeader baselineHeader) throws IOException {
return new DecomposingVcfIterator(new ArrayVcfIterator(baselineHeader), null).getHeader();
}
static VariantFactory getVariantFactory(VariantSetType type, VcfHeader header, String sampleName, boolean relaxedRef) {
final boolean explicitHalf = GlobalFlags.getBooleanValue(ToolsGlobalFlags.VCFEVAL_EXPLICIT_HALF_CALL);
final String f = VariantFactory.getFactoryName(type, sampleName);
switch (f) {
case VariantFactory.SAMPLE_FACTORY:
return new VariantFactory.SampleVariants(VcfUtils.getSampleIndexOrDie(header, sampleName, type.label()), relaxedRef, explicitHalf);
case VariantFactory.ALL_FACTORY:
return new VariantFactory.AllAlts(relaxedRef, explicitHalf);
default:
throw new RuntimeException("Could not determine variant factory for " + f);
}
}
private boolean disjoint(Set<String> names, Collection<Pair<String, Integer>> referenceNameOrdering) {
for (Pair<String, Integer> pair : referenceNameOrdering) {
if (names.contains(pair.getA())) {
return false;
}
}
return true;
}
@Override
public Pair<String, Map<VariantSetType, List<Variant>>> nextSet() throws IOException {
final Map<VariantSetType, List<Variant>> map = new EnumMap<>(VariantSetType.class);
final Iterator<Pair<String, Integer>> iterator = mNames.iterator();
if (!iterator.hasNext()) {
return null;
}
final Pair<String, Integer> nameLength = iterator.next();
mNames.remove(nameLength);
final String currentName = nameLength.getA();
final int currentLength = nameLength.getB();
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
final ReferenceRanges<String> subRanges = mRanges.forSequence(currentName);
final FutureTask<LoadedVariants> baseFuture = new FutureTask<>(new VcfRecordTabixCallable(mBaselineFile, subRanges, mEvalRegions, currentName, currentLength, VariantSetType.BASELINE, mBaselineFactory, mPassOnly, mMaxLength, mPreprocessDestDir));
final FutureTask<LoadedVariants> callFuture = new FutureTask<>(new VcfRecordTabixCallable(mCallsFile, subRanges, mEvalRegions, currentName, currentLength, VariantSetType.CALLS, mCallsFactory, mPassOnly, mMaxLength, mPreprocessDestDir));
executor.execute(baseFuture);
executor.execute(callFuture);
final LoadedVariants baseVars = baseFuture.get();
final LoadedVariants calledVars = callFuture.get();
map.put(VariantSetType.BASELINE, baseVars.mVariants);
map.put(VariantSetType.CALLS, calledVars.mVariants);
if (mPreprocess) {
Diagnostic.developerLog("Preprocessed VCF at " + baseVars.mPreprocessed);
Diagnostic.developerLog("Preprocessed VCF at " + calledVars.mPreprocessed);
mBaselinePreprocessed.put(currentName, baseVars.mPreprocessed);
mCallsPreprocessed.put(currentName, calledVars.mPreprocessed);
}
mBaselineSkipped += baseVars.mSkippedDuringLoading;
mCallsSkipped += calledVars.mSkippedDuringLoading;
Diagnostic.userLog("Reference " + currentName + " baseline contains " + map.get(VariantSetType.BASELINE).size() + " variants.");
Diagnostic.userLog("Reference " + currentName + " calls contains " + map.get(VariantSetType.CALLS).size() + " variants.");
} catch (final ExecutionException e) {
IOUtils.rethrow(e.getCause());
} catch (final InterruptedException e) {
throw new NoTalkbackSlimException(e, ErrorType.INFO_ERROR, e.getCause().getMessage());
} finally {
executor.shutdownNow();
}
return new Pair<>(currentName, map);
}
@Override
public VcfHeader baselineHeader() {
return mBaseLineHeader;
}
@Override
public VcfIterator getBaselineVariants(String sequenceName) throws IOException {
return new VcfSortRefiner(mPreprocess ? VcfReader.openVcfReader(mBaselinePreprocessed.get(sequenceName)) : VcfReader.openVcfReader(mBaselineFile, mRanges.forSequence(sequenceName)));
}
@Override
public VcfHeader calledHeader() {
return mCalledHeader;
}
@Override
public VcfIterator getCalledVariants(String sequenceName) throws IOException {
return new VcfSortRefiner(mPreprocess ? VcfReader.openVcfReader(mCallsPreprocessed.get(sequenceName)) : VcfReader.openVcfReader(mCallsFile, mRanges.forSequence(sequenceName)));
}
@Override
public int getNumberOfSkippedBaselineVariants() {
return mBaselineSkipped;
}
@Override
public int getNumberOfSkippedCalledVariants() {
return mCallsSkipped;
}
@Override
public void close() throws IOException {
if (mPreprocessDestDir != null) { // Delete all the intermediate files we created
final Collection<File> files = new HashSet<>();
Stream.concat(mBaselinePreprocessed.values().stream(), mCallsPreprocessed.values().stream()).forEach(vcf -> {
files.add(vcf);
files.add(TabixIndexer.indexFileName(vcf));
});
for (File todelete : files) {
if (todelete.exists() && !todelete.delete()) {
throw new IOException("Could not delete intermediate file: " + todelete);
}
}
if (FileUtils.isEmptyDir(mPreprocessDestDir)) { // Only do the directory delete if now empty
if (!mPreprocessDestDir.delete()) {
throw new IOException("Could not delete intermediate output dir: " + mPreprocessDestDir);
}
}
}
}
}
|
Add support for splitting MNPs into SNPs during partitioning
|
src/com/rtg/vcf/eval/TabixVcfRecordSet.java
|
Add support for splitting MNPs into SNPs during partitioning
|
|
Java
|
bsd-3-clause
|
afcd5e5387c472e9bb296ad116988b385ee03995
| 0
|
bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr
|
/**
* RSSI Viewer - view RSSI values of 802.15.4 channels
* ---------------------------------------------------
* Note: run the rssi-scanner on a Sky or sentilla node connected to USB
* then start with
* make ViewRSSI.class
* make login | java ViewRSSI
* or
* make viewrssi
*
* Created: Fri Apr 24 00:40:01 2009, Joakim Eriksson
*
* @author Joakim Eriksson, SICS
* @version 1.0
*/
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class ViewRSSI extends JPanel {
private int[] rssi = new int[80];
private int[] rssiMax = new int[80];
/* 55 is added by the scanner. 45 is the offset of the CC2420 */
private final int DELTA = -55 -45;
/* this is the max value of the RSSI from the cc2420 */
private static final int RSSI_MAX_VALUE = 200;
public ViewRSSI() {
}
public void paint(Graphics g) {
int h = getHeight();
int w = getWidth();
double factor = (h - 20.0) / RSSI_MAX_VALUE;
double sSpacing = (w - 15) / 80.0;
int sWidth = (int) (sSpacing - 1);
if (sWidth == 0)
sWidth = 1;
Graphics2D g2d=(Graphics2D)g;
Font myFont=new Font("Arial", Font.PLAIN, 8);
g2d.setFont( myFont );
g.setColor(Color.white);
g.fillRect(0, 0, w, h);
g.setColor(Color.gray);
double xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssi = (int) (rssiMax[i] * factor);
g.fillRect((int) xpos, h - 20 - rssi, sWidth, rssi + 1);
g2d.drawString(Integer.toString(rssiMax[i] + DELTA), (int)xpos,h - 20 - rssi - 5 );
xpos += sSpacing;
}
xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
g.setColor(Color.black);
int rssiVal = (int) (rssi[i] * factor);
g.fillRect((int) xpos, h - 20 - rssiVal, sWidth, rssiVal + 1);
g2d.drawString(Integer.toString(rssi[i] + DELTA), (int)xpos,h - 20 - rssiVal - 8 );
g.setColor(Color.white);
g2d.drawString(Float.toString((float)i / 5 + (float)56/5), (int)xpos,h - 20 - 5 );
xpos += sSpacing;
}
}
private void handleInput() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.startsWith("RSSI:")) {
try {
String[] parts = line.substring(5).split(" ");
for (int i = 0, n = parts.length; i < n; i++) {
rssi[i] = 3 * Integer.parseInt(parts[i]);
if (rssi[i] >= rssiMax[i])
rssiMax[i] = rssi[i];
else if (rssiMax[i] > 0)
rssiMax[i]--;
}
} catch (Exception e) {
/* report but do not fail... */
e.printStackTrace();
}
repaint();
}
}
}
public static void main(String[] args) throws IOException {
JFrame win = new JFrame("RSSI Viewer");
ViewRSSI panel;
win.setBounds(10, 10, 300, 300);
win.getContentPane().add(panel = new ViewRSSI());
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.handleInput();
}
}
|
examples/sky/ViewRSSI.java
|
/**
* RSSI Viewer - view RSSI values of 802.15.4 channels
* ---------------------------------------------------
* Note: run the rssi-scanner on a Sky or sentilla node connected to USB
* then start with
* make ViewRSSI.class
* make login | java ViewRSSI
* or
* make viewrssi
*
* Created: Fri Apr 24 00:40:01 2009, Joakim Eriksson
*
* @author Joakim Eriksson, SICS
* @version 1.0
*/
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class ViewRSSI extends JPanel {
private int[] rssi = new int[80];
private int[] rssiMax = new int[80];
/* 55 is added by the scanner. 45 is the offset of the CC2420 */
private final int DELTA = -55 -45
/* this is the max value of the RSSI from the cc2420 */
private static final int RSSI_MAX_VALUE = 200;
public ViewRSSI() {
}
public void paint(Graphics g) {
int h = getHeight();
int w = getWidth();
double factor = (h - 20.0) / RSSI_MAX_VALUE;
double sSpacing = (w - 15) / 80.0;
int sWidth = (int) (sSpacing - 1);
if (sWidth == 0)
sWidth = 1;
Graphics2D g2d=(Graphics2D)g;
Font myFont=new Font("Arial", Font.PLAIN, 8);
g2d.setFont( myFont );
g.setColor(Color.white);
g.fillRect(0, 0, w, h);
g.setColor(Color.gray);
double xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssi = (int) (rssiMax[i] * factor);
g.fillRect((int) xpos, h - 20 - rssi, sWidth, rssi + 1);
g2d.drawString(Integer.toString(rssiMax[i] + DELTA), (int)xpos,h - 20 - rssi - 5 );
xpos += sSpacing;
}
xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
g.setColor(Color.black);
int rssiVal = (int) (rssi[i] * factor);
g.fillRect((int) xpos, h - 20 - rssiVal, sWidth, rssiVal + 1);
g2d.drawString(Integer.toString(rssi[i] + DELTA), (int)xpos,h - 20 - rssiVal - 8 );
g.setColor(Color.white);
g2d.drawString(Float.toString((float)i / 5 + (float)56/5), (int)xpos,h - 20 - 5 );
xpos += sSpacing;
}
}
private void handleInput() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.startsWith("RSSI:")) {
try {
String[] parts = line.substring(5).split(" ");
for (int i = 0, n = parts.length; i < n; i++) {
rssi[i] = 3 * Integer.parseInt(parts[i]);
if (rssi[i] >= rssiMax[i])
rssiMax[i] = rssi[i];
else if (rssiMax[i] > 0)
rssiMax[i]--;
}
} catch (Exception e) {
/* report but do not fail... */
e.printStackTrace();
}
repaint();
}
}
}
public static void main(String[] args) throws IOException {
JFrame win = new JFrame("RSSI Viewer");
ViewRSSI panel;
win.setBounds(10, 10, 300, 300);
win.getContentPane().add(panel = new ViewRSSI());
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.handleInput();
}
}
|
Add missing semi-colon
|
examples/sky/ViewRSSI.java
|
Add missing semi-colon
|
|
Java
|
mit
|
33d0f8d68e6c401188b9ed087c697077b03b0388
| 0
|
GiuseppeGiorgi/javaCrawler
|
javaCrawler/Crawler.java
|
package javaCrawler;
import java.util.ArrayList;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Crawler extends AbstractCrawler{
private Url record;
private String url;
private String userAgent = Parameters.USER_AGENT;
private int timeout = Parameters.TIMEOUT;
private ArrayList<String> tag = new ArrayList<String>();
private Boolean searchWord = false;
public Record search(Url record){
this.record = record;
this.url = this.record.getUrl();
boolean statusConn = super.connection(this.url, userAgent, timeout);
/**
* error connection
*/
if(!statusConn){
buildRecord();
return this.record;
}
if (Parameters.WORD != null){
searchWord = searchWord(Parameters.WORD);
}
//list of tags to be searched
ArrayList<String> tagL = Parameters.TAGLIST;
//tags found
for (String tg : tagL) {
this.tag.add(String.valueOf(htmlDocument.select(tg).first()).replace("\n", " "));
}
this.buildRecord();
/**
* list of urls to be scanned
*/
Elements linksOnPages = htmlDocument.body().select("a[abs:href*="+Parameters.URL_FOLLOW+"]");
for (Element link : linksOnPages) {
String linkSave = String.valueOf(link.attr("abs:href"));
if(Visitable.getInstance().isVisitable(linkSave)){
Record newRecord = new Url(linkSave, this.url);
UrlToVisit.getInstance().setLinkToVisit(linkSave, newRecord);
}
}
return this.record;
}
private void buildRecord(){
this.record.setErrorMessage(super.errorMessage);
this.record.setResponsCode(super.responseStatusCode);
this.record.setResponseTime(super.responseTime);
this.record.setTag(this.tag);
this.record.setLogError(super.logError);
this.record.setDate(super.date);
this.record.setTimeStamp(super.timeStamp);
this.record.setSearchWord(this.searchWord);
}
private boolean searchWord(String word){
String bodyText = super.htmlDocument.body().text();
return bodyText.toLowerCase().contains(word.toLowerCase());
}
}
|
Delete Crawler.java
|
javaCrawler/Crawler.java
|
Delete Crawler.java
|
||
Java
|
mit
|
87281be8cfb9759efd0b3b809c7cefada964b60c
| 0
|
AuthMe/FastLogin,games647/FastLogin
|
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 games647 and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.listener.protocollib;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.injector.server.TemporaryPlayerFactory;
import com.comphenix.protocol.reflect.FieldUtils;
import com.comphenix.protocol.reflect.FuzzyReflection;
import com.comphenix.protocol.utility.MinecraftReflection;
import com.comphenix.protocol.utility.MinecraftVersion;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.github.games647.craftapi.model.auth.Verification;
import com.github.games647.craftapi.model.skin.SkinProperty;
import com.github.games647.craftapi.resolver.AbstractResolver;
import com.github.games647.craftapi.resolver.MojangResolver;
import com.github.games647.fastlogin.bukkit.BukkitLoginSession;
import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import org.bukkit.entity.Player;
import static com.comphenix.protocol.PacketType.Login.Client.START;
import static com.comphenix.protocol.PacketType.Login.Server.DISCONNECT;
public class VerifyResponseTask implements Runnable {
private static final String ENCRYPTION_CLASS_NAME = "MinecraftEncryption";
private static final Class<?> ENCRYPTION_CLASS;
static {
ENCRYPTION_CLASS = MinecraftReflection.getMinecraftClass("util." + ENCRYPTION_CLASS_NAME, ENCRYPTION_CLASS_NAME);
}
private final FastLoginBukkit plugin;
private final PacketEvent packetEvent;
private final KeyPair serverKey;
private final Player player;
private final BukkitLoginSession session;
private final byte[] sharedSecret;
private static Method encryptMethod;
private static Method cipherMethod;
public VerifyResponseTask(FastLoginBukkit plugin, PacketEvent packetEvent,
Player player, BukkitLoginSession session,
byte[] sharedSecret, KeyPair keyPair) {
this.plugin = plugin;
this.packetEvent = packetEvent;
this.player = player;
this.session = session;
this.sharedSecret = Arrays.copyOf(sharedSecret, sharedSecret.length);
this.serverKey = keyPair;
}
@Override
public void run() {
try {
verifyResponse(session);
} finally {
//this is a fake packet; it shouldn't be sent to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
private void verifyResponse(BukkitLoginSession session) {
PrivateKey privateKey = serverKey.getPrivate();
SecretKey loginKey;
try {
loginKey = EncryptionUtil.decryptSharedKey(privateKey, sharedSecret);
} catch (GeneralSecurityException securityEx) {
disconnect("error-kick", "Cannot decrypt received contents", securityEx);
return;
}
try {
if (!checkVerifyToken(session) || !enableEncryption(loginKey)) {
return;
}
} catch (Exception ex) {
disconnect("error-kick", "Cannot decrypt received contents", ex);
return;
}
String serverId = EncryptionUtil.getServerIdHashString("", loginKey, serverKey.getPublic());
String requestedUsername = session.getRequestUsername();
InetSocketAddress socketAddress = player.getAddress();
try {
MojangResolver resolver = plugin.getCore().getResolver();
InetAddress address = socketAddress.getAddress();
Optional<Verification> response = resolver.hasJoined(requestedUsername, serverId, address);
if (response.isPresent()) {
encryptConnection(session, requestedUsername, response.get());
} else {
//user tried to fake an authentication
disconnect("invalid-session", "GameProfile {} ({}) tried to log in with an invalid session. ServerId: {}", session.getRequestUsername(), socketAddress, serverId);
}
} catch (IOException ioEx) {
disconnect("error-kick", "Failed to connect to session server", ioEx);
}
}
private void encryptConnection(BukkitLoginSession session, String requestedUsername, Verification verification) {
plugin.getLog().info("Profile {} has a verified premium account", requestedUsername);
String realUsername = verification.getName();
if (realUsername == null) {
disconnect("invalid-session", "Username field null for {}", requestedUsername);
return;
}
SkinProperty[] properties = verification.getProperties();
if (properties.length > 0) {
session.setSkinProperty(properties[0]);
}
session.setVerifiedUsername(realUsername);
session.setUuid(verification.getId());
session.setVerified(true);
setPremiumUUID(session.getUuid());
receiveFakeStartPacket(realUsername);
}
private void setPremiumUUID(UUID premiumUUID) {
if (plugin.getConfig().getBoolean("premiumUuid") && premiumUUID != null) {
try {
Object networkManager = getNetworkManager();
//https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/NetworkManager.java#L69
FieldUtils.writeField(networkManager, "spoofedUUID", premiumUUID, true);
} catch (Exception exc) {
plugin.getLog().error("Error setting premium uuid of {}", player, exc);
}
}
}
private boolean checkVerifyToken(BukkitLoginSession session) throws GeneralSecurityException {
byte[] requestVerify = session.getVerifyToken();
//encrypted verify token
byte[] responseVerify = packetEvent.getPacket().getByteArrays().read(1);
//https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/LoginListener.java#L182
if (!Arrays.equals(requestVerify, EncryptionUtil.decrypt(serverKey.getPrivate(), responseVerify))) {
//check if the verify-token are equal to the server sent one
disconnect("invalid-verify-token",
"GameProfile {0} ({1}) tried to login with an invalid verify token. Server: {2} Client: {3}",
session.getRequestUsername(), packetEvent.getPlayer().getAddress(), requestVerify, responseVerify);
return false;
}
return true;
}
//try to get the networkManager from ProtocolLib
private Object getNetworkManager() throws IllegalAccessException, ClassNotFoundException {
Object injectorContainer = TemporaryPlayerFactory.getInjectorFromPlayer(player);
// ChannelInjector
Class<?> injectorClass = Class.forName("com.comphenix.protocol.injector.netty.Injector");
Object rawInjector = FuzzyReflection.getFieldValue(injectorContainer, injectorClass, true);
return FieldUtils.readField(rawInjector, "networkManager", true);
}
private boolean enableEncryption(SecretKey loginKey) throws IllegalArgumentException {
plugin.getLog().info("Enabling onlinemode encryption for {}", player.getName());
// Initialize method reflections
if (encryptMethod == null) {
Class<?> networkManagerClass = MinecraftReflection.getNetworkManagerClass();
try {
// Try to get the old (pre MC 1.16.4) encryption method
encryptMethod = FuzzyReflection.fromClass(networkManagerClass)
.getMethodByParameters("a", SecretKey.class);
} catch (IllegalArgumentException exception) {
// Get the new encryption method
encryptMethod = FuzzyReflection.fromClass(networkManagerClass)
.getMethodByParameters("a", Cipher.class, Cipher.class);
// Get the needed Cipher helper method (used to generate ciphers from login key)
cipherMethod = FuzzyReflection.fromClass(ENCRYPTION_CLASS)
.getMethodByParameters("a", int.class, Key.class);
}
}
try {
Object networkManager = this.getNetworkManager();
// If cipherMethod is null - use old encryption (pre MC 1.16.4), otherwise use the new cipher one
if (cipherMethod == null) {
// Encrypt/decrypt packet flow, this behaviour is expected by the client
encryptMethod.invoke(networkManager, loginKey);
} else {
// Create ciphers from login key
Object decryptionCipher = cipherMethod.invoke(null, Cipher.DECRYPT_MODE, loginKey);
Object encryptionCipher = cipherMethod.invoke(null, Cipher.ENCRYPT_MODE, loginKey);
// Encrypt/decrypt packet flow, this behaviour is expected by the client
encryptMethod.invoke(networkManager, decryptionCipher, encryptionCipher);
}
} catch (Exception ex) {
disconnect("error-kick", "Couldn't enable encryption", ex);
return false;
}
return true;
}
private void disconnect(String reasonKey, String logMessage, Object... arguments) {
plugin.getLog().error(logMessage, arguments);
kickPlayer(plugin.getCore().getMessage(reasonKey));
}
private void kickPlayer(String reason) {
PacketContainer kickPacket = new PacketContainer(DISCONNECT);
kickPacket.getChatComponents().write(0, WrappedChatComponent.fromText(reason));
try {
//send kick packet at login state
//the normal event.getPlayer.kickPlayer(String) method does only work at play state
ProtocolLibrary.getProtocolManager().sendServerPacket(player, kickPacket);
//tell the server that we want to close the connection
player.kickPlayer("Disconnect");
} catch (InvocationTargetException ex) {
plugin.getLog().error("Error sending kick packet for: {}", player, ex);
}
}
//fake a new login packet in order to let the server handle all the other stuff
private void receiveFakeStartPacket(String username) {
//see StartPacketListener for packet information
PacketContainer startPacket = new PacketContainer(START);
if (MinecraftVersion.atOrAbove(new MinecraftVersion(1, 19, 0))) {
startPacket.getStrings().write(0, username);
} else {
//uuid is ignored by the packet definition
WrappedGameProfile fakeProfile = new WrappedGameProfile(UUID.randomUUID(), username);
startPacket.getGameProfiles().write(0, fakeProfile);
}
try {
//we don't want to handle our own packets so ignore filters
startPacket.setMeta(ProtocolLibListener.SOURCE_META_KEY, plugin.getName());
ProtocolLibrary.getProtocolManager().recieveClientPacket(player, startPacket, true);
} catch (InvocationTargetException | IllegalAccessException ex) {
plugin.getLog().warn("Failed to fake a new start packet for: {}", username, ex);
//cancel the event in order to prevent the server receiving an invalid packet
kickPlayer(plugin.getCore().getMessage("error-kick"));
}
}
}
|
bukkit/src/main/java/com/github/games647/fastlogin/bukkit/listener/protocollib/VerifyResponseTask.java
|
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 games647 and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.listener.protocollib;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.injector.server.TemporaryPlayerFactory;
import com.comphenix.protocol.reflect.FieldUtils;
import com.comphenix.protocol.reflect.FuzzyReflection;
import com.comphenix.protocol.utility.MinecraftReflection;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.github.games647.craftapi.model.auth.Verification;
import com.github.games647.craftapi.model.skin.SkinProperty;
import com.github.games647.craftapi.resolver.AbstractResolver;
import com.github.games647.craftapi.resolver.MojangResolver;
import com.github.games647.fastlogin.bukkit.BukkitLoginSession;
import com.github.games647.fastlogin.bukkit.FastLoginBukkit;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import org.bukkit.entity.Player;
import static com.comphenix.protocol.PacketType.Login.Client.START;
import static com.comphenix.protocol.PacketType.Login.Server.DISCONNECT;
public class VerifyResponseTask implements Runnable {
private static final String ENCRYPTION_CLASS_NAME = "MinecraftEncryption";
private static final Class<?> ENCRYPTION_CLASS;
static {
ENCRYPTION_CLASS = MinecraftReflection.getMinecraftClass("util." + ENCRYPTION_CLASS_NAME, ENCRYPTION_CLASS_NAME);
}
private final FastLoginBukkit plugin;
private final PacketEvent packetEvent;
private final KeyPair serverKey;
private final Player player;
private final BukkitLoginSession session;
private final byte[] sharedSecret;
private static Method encryptMethod;
private static Method cipherMethod;
public VerifyResponseTask(FastLoginBukkit plugin, PacketEvent packetEvent,
Player player, BukkitLoginSession session,
byte[] sharedSecret, KeyPair keyPair) {
this.plugin = plugin;
this.packetEvent = packetEvent;
this.player = player;
this.session = session;
this.sharedSecret = Arrays.copyOf(sharedSecret, sharedSecret.length);
this.serverKey = keyPair;
}
@Override
public void run() {
try {
verifyResponse(session);
} finally {
//this is a fake packet; it shouldn't be sent to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
private void verifyResponse(BukkitLoginSession session) {
PrivateKey privateKey = serverKey.getPrivate();
SecretKey loginKey;
try {
loginKey = EncryptionUtil.decryptSharedKey(privateKey, sharedSecret);
} catch (GeneralSecurityException securityEx) {
disconnect("error-kick", "Cannot decrypt received contents", securityEx);
return;
}
try {
if (!checkVerifyToken(session) || !enableEncryption(loginKey)) {
return;
}
} catch (Exception ex) {
disconnect("error-kick", "Cannot decrypt received contents", ex);
return;
}
String serverId = EncryptionUtil.getServerIdHashString("", loginKey, serverKey.getPublic());
String requestedUsername = session.getRequestUsername();
InetSocketAddress socketAddress = player.getAddress();
try {
MojangResolver resolver = plugin.getCore().getResolver();
InetAddress address = socketAddress.getAddress();
Optional<Verification> response = resolver.hasJoined(requestedUsername, serverId, address);
if (response.isPresent()) {
encryptConnection(session, requestedUsername, response.get());
} else {
//user tried to fake an authentication
disconnect("invalid-session", "GameProfile {} ({}) tried to log in with an invalid session. ServerId: {}", session.getRequestUsername(), socketAddress, serverId);
}
} catch (IOException ioEx) {
disconnect("error-kick", "Failed to connect to session server", ioEx);
}
}
private void encryptConnection(BukkitLoginSession session, String requestedUsername, Verification verification) {
plugin.getLog().info("Profile {} has a verified premium account", requestedUsername);
String realUsername = verification.getName();
if (realUsername == null) {
disconnect("invalid-session", "Username field null for {}", requestedUsername);
return;
}
SkinProperty[] properties = verification.getProperties();
if (properties.length > 0) {
session.setSkinProperty(properties[0]);
}
session.setVerifiedUsername(realUsername);
session.setUuid(verification.getId());
session.setVerified(true);
setPremiumUUID(session.getUuid());
receiveFakeStartPacket(realUsername);
}
private void setPremiumUUID(UUID premiumUUID) {
if (plugin.getConfig().getBoolean("premiumUuid") && premiumUUID != null) {
try {
Object networkManager = getNetworkManager();
//https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/NetworkManager.java#L69
FieldUtils.writeField(networkManager, "spoofedUUID", premiumUUID, true);
} catch (Exception exc) {
plugin.getLog().error("Error setting premium uuid of {}", player, exc);
}
}
}
private boolean checkVerifyToken(BukkitLoginSession session) throws GeneralSecurityException {
byte[] requestVerify = session.getVerifyToken();
//encrypted verify token
byte[] responseVerify = packetEvent.getPacket().getByteArrays().read(1);
//https://github.com/bergerkiller/CraftSource/blob/master/net.minecraft.server/LoginListener.java#L182
if (!Arrays.equals(requestVerify, EncryptionUtil.decrypt(serverKey.getPrivate(), responseVerify))) {
//check if the verify-token are equal to the server sent one
disconnect("invalid-verify-token",
"GameProfile {0} ({1}) tried to login with an invalid verify token. Server: {2} Client: {3}",
session.getRequestUsername(), packetEvent.getPlayer().getAddress(), requestVerify, responseVerify);
return false;
}
return true;
}
//try to get the networkManager from ProtocolLib
private Object getNetworkManager() throws IllegalAccessException, ClassNotFoundException {
Object injectorContainer = TemporaryPlayerFactory.getInjectorFromPlayer(player);
// ChannelInjector
Class<?> injectorClass = Class.forName("com.comphenix.protocol.injector.netty.Injector");
Object rawInjector = FuzzyReflection.getFieldValue(injectorContainer, injectorClass, true);
return FieldUtils.readField(rawInjector, "networkManager", true);
}
private boolean enableEncryption(SecretKey loginKey) throws IllegalArgumentException {
plugin.getLog().info("Enabling onlinemode encryption for {}", player.getName());
// Initialize method reflections
if (encryptMethod == null) {
Class<?> networkManagerClass = MinecraftReflection.getNetworkManagerClass();
try {
// Try to get the old (pre MC 1.16.4) encryption method
encryptMethod = FuzzyReflection.fromClass(networkManagerClass)
.getMethodByParameters("a", SecretKey.class);
} catch (IllegalArgumentException exception) {
// Get the new encryption method
encryptMethod = FuzzyReflection.fromClass(networkManagerClass)
.getMethodByParameters("a", Cipher.class, Cipher.class);
// Get the needed Cipher helper method (used to generate ciphers from login key)
cipherMethod = FuzzyReflection.fromClass(ENCRYPTION_CLASS)
.getMethodByParameters("a", int.class, Key.class);
}
}
try {
Object networkManager = this.getNetworkManager();
// If cipherMethod is null - use old encryption (pre MC 1.16.4), otherwise use the new cipher one
if (cipherMethod == null) {
// Encrypt/decrypt packet flow, this behaviour is expected by the client
encryptMethod.invoke(networkManager, loginKey);
} else {
// Create ciphers from login key
Object decryptionCipher = cipherMethod.invoke(null, Cipher.DECRYPT_MODE, loginKey);
Object encryptionCipher = cipherMethod.invoke(null, Cipher.ENCRYPT_MODE, loginKey);
// Encrypt/decrypt packet flow, this behaviour is expected by the client
encryptMethod.invoke(networkManager, decryptionCipher, encryptionCipher);
}
} catch (Exception ex) {
disconnect("error-kick", "Couldn't enable encryption", ex);
return false;
}
return true;
}
private void disconnect(String reasonKey, String logMessage, Object... arguments) {
plugin.getLog().error(logMessage, arguments);
kickPlayer(plugin.getCore().getMessage(reasonKey));
}
private void kickPlayer(String reason) {
PacketContainer kickPacket = new PacketContainer(DISCONNECT);
kickPacket.getChatComponents().write(0, WrappedChatComponent.fromText(reason));
try {
//send kick packet at login state
//the normal event.getPlayer.kickPlayer(String) method does only work at play state
ProtocolLibrary.getProtocolManager().sendServerPacket(player, kickPacket);
//tell the server that we want to close the connection
player.kickPlayer("Disconnect");
} catch (InvocationTargetException ex) {
plugin.getLog().error("Error sending kick packet for: {}", player, ex);
}
}
//fake a new login packet in order to let the server handle all the other stuff
private void receiveFakeStartPacket(String username) {
//see StartPacketListener for packet information
PacketContainer startPacket = new PacketContainer(START);
//uuid is ignored by the packet definition
WrappedGameProfile fakeProfile = new WrappedGameProfile(UUID.randomUUID(), username);
startPacket.getGameProfiles().write(0, fakeProfile);
try {
//we don't want to handle our own packets so ignore filters
startPacket.setMeta(ProtocolLibListener.SOURCE_META_KEY, plugin.getName());
ProtocolLibrary.getProtocolManager().recieveClientPacket(player, startPacket, true);
} catch (InvocationTargetException | IllegalAccessException ex) {
plugin.getLog().warn("Failed to fake a new start packet for: {}", username, ex);
//cancel the event in order to prevent the server receiving an invalid packet
kickPlayer(plugin.getCore().getMessage("error-kick"));
}
}
}
|
Fix start packet containing username in 1.19
|
bukkit/src/main/java/com/github/games647/fastlogin/bukkit/listener/protocollib/VerifyResponseTask.java
|
Fix start packet containing username in 1.19
|
|
Java
|
mit
|
fbcb6552b4397a0a3bb603693537a36810794db9
| 0
|
project-recoin/PybossaTwitterController,project-recoin/PybossaTwitterController
|
package sociam.pybossa;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import sociam.pybossa.config.Config;
import sociam.pybossa.util.StringToImage;
import sociam.pybossa.util.TwitterAccount;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
/**
*
* @author user Saud Aljaloud
* @author email sza1g10@ecs.soton.ac.uk
*
*/
public class TaskPerformer {
final static Logger logger = Logger.getLogger(TaskPerformer.class);
final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static Boolean wasPushed = false;
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.info("TaskPerformer will be repeated every " + Config.TaskCreatorTrigger + " ms");
try {
while (true) {
Config.reload();
run();
logger.info("Sleeping for " + Config.TaskPerformerTrigger + " ms");
Thread.sleep(Integer.valueOf(Config.TaskPerformerTrigger));
}
} catch (InterruptedException e) {
logger.error("Error ", e);
}
}
public static void run() {
try {
HashSet<Document> tasksToBePushed = getReadyTasksFromMongoDB();
if (tasksToBePushed != null) {
logger.info("There are " + tasksToBePushed.size()
+ " tasks that need to be pushed into Twitter, then updating to MongoDB");
for (Document document : tasksToBePushed) {
String task_status = document.getString("task_status");
String task_text = document.getString("task_text");
if (task_status.equals("pushed")) {
Date lastPushAt = document.getDate("lastPushAt");
if (!rePush(lastPushAt)) {
break;
} else {
logger.debug("Repushing task " + task_text);
}
}
ObjectId _id = document.getObjectId("_id");
int pybossa_task_id = document.getInteger("pybossa_task_id");
int project_id = document.getInteger("project_id");
JSONObject project = getProjectByID(project_id);
ArrayList<String> hashtags = new ArrayList<>();
if (project != null) {
JSONArray bin_id = project.getJSONArray("bin_ids");
for (Object object : bin_id) {
String binItem = (String) object;
hashtags.add("#" + binItem);
}
}
String taskTag = "#t" + pybossa_task_id;
int responseCode = sendTaskToTwitter(task_text, taskTag, hashtags, 2);
if (responseCode == 1) {
if (updateTaskToPushedInMongoDB(_id, "pushed")) {
logger.info("Task with text " + task_text + " has been sucessfully pushed to Twitter");
wasPushed = true;
} else {
logger.error(
"Error with updating " + Config.taskCollection + " for the _id " + _id.toString());
}
} else if (responseCode == 0) {
if (updateTaskToPushedInMongoDB(_id, "notValied")) {
logger.debug("Tweeet is not valid because of length, but updated in Mongodb" + task_text);
}
logger.error("Couldn't update the task in MongoDB");
} else if (responseCode == 2) {
if (updateTaskToPushedInMongoDB(_id, "error")) {
logger.debug("pushing tweet has encountered an error, but has been updated into MongoDB "
+ task_text);
} else {
logger.error("Couldn't update the task in MongoDB");
}
}
// TODO: add lastPushAt when updating tasks
if (wasPushed) {
wasPushed = false;
logger.debug(
"waiting for " + Config.TaskPerformerPushRate + " ms before pushing another tweet");
Thread.sleep(Integer.valueOf(Config.TaskPerformerPushRate));
}
}
}
} catch (Exception e) {
logger.error("Error ", e);
}
}
public static Boolean rePush(Date lastPushAt) {
try {
Calendar cal = Calendar.getInstance();
Date currentDate = new Date();
cal.setTime(lastPushAt);
cal.add(Calendar.HOUR, Integer.valueOf(Config.RePushTaskToTwitter));
Date convertedDate = cal.getTime();
return currentDate.before(convertedDate);
} catch (Exception e) {
logger.error("Error ", e);
return false;
}
}
public static Boolean updateTaskToPushedInMongoDB(ObjectId _id, String task_status) {
MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort);
try {
MongoDatabase database = mongoClient.getDatabase(Config.projectsDatabaseName);
Date date = new Date();
String lastPushAt = MongoDBformatter.format(date);
UpdateResult result = database.getCollection(Config.taskCollection).updateOne(new Document("_id", _id),
new Document().append("$set",
new Document("task_status", task_status).append("lastPushAt", lastPushAt)));
logger.debug(result.toString());
if (result.wasAcknowledged()) {
if (result.getMatchedCount() > 0) {
logger.debug(Config.taskCollection + " Collection was updated where _id= " + _id.toString()
+ " to task_status=" + task_status);
mongoClient.close();
return true;
}
}
mongoClient.close();
return false;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return false;
}
}
/**
* This method send a task by a twitter account
*
* @param taskId
* The id of the task to be hashed within the tweet
* @param taskContent
* the content of the tweet to be published
*/
public static int sendTaskToTwitter(String taskContent, String taskTag, ArrayList<String> hashtags,
int project_type) {
try {
Twitter twitter = TwitterAccount.setTwitterAccount(project_type);
// combine hashtags and tasktag while maintaining the 140 length
String post = "";
for (String string : hashtags) {
if (post.length() == 0) {
post = string;
} else {
String tmpResult = post + " " + string + taskTag;
if (tmpResult.length() >= 140) {
break;
}
post = post + " " + string;
}
}
post = post + " " + taskTag;
// defualt
String question = Config.project_validation_question;
if (project_type == 1) {
question = Config.project_validation_question;
}
// convert taskContent and question into an image
File image = StringToImage.convertStringToImage(taskContent, question);
if (post.length() < 140) {
// status = twitter.updateStatus(post);
StatusUpdate status = new StatusUpdate(post);
status.setMedia(image);
twitter.updateStatus(status);
logger.debug("Successfully posting a task '" + status.getStatus() + "'." + status.getPlaceId());
return 1;
} else {
logger.error("Post \"" + post + "\" is longer than 140 characters. It has: " + (post.length()));
return 0;
}
} catch (Exception e) {
logger.error("Error", e);
return 2;
}
}
// static HashSet<Document> NotPushedTasksjsons = new
// LinkedHashSet<Document>();
public static HashSet<Document> getReadyTasksFromMongoDB() {
HashSet<Document> NotPushedTasksjsons = new LinkedHashSet<Document>();
MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort);
try {
MongoDatabase database = mongoClient.getDatabase(Config.projectsDatabaseName);
FindIterable<Document> iterable = database.getCollection(Config.taskCollection)
.find(new Document("task_status", "ready"));
if (iterable.first() != null) {
for (Document document : iterable) {
NotPushedTasksjsons.add(document);
}
}
mongoClient.close();
return NotPushedTasksjsons;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return null;
}
}
public static JSONObject getProjectByID(int project_id) {
logger.debug("getting project by project_id from " + Config.projectCollection + " collection");
MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort);
try {
JSONObject json = null;
DB database = mongoClient.getDB(Config.projectsDatabaseName);
JSONObject proj = new JSONObject();
proj.put("project_id", project_id);
Object o = com.mongodb.util.JSON.parse(proj.toString());
DBObject dbObj = (DBObject) o;
DBCollection collections = database.getCollection(Config.projectCollection);
DBCursor iterable = collections.find(dbObj);
if (iterable.hasNext()) {
json = new JSONObject(iterable.next().toString());
}
mongoClient.close();
return json;
// MongoDatabase database =
// mongoClient.getDatabase(Config.projectsDatabaseName);
// JSONObject json = null;
// FindIterable<Document> iterable =
// database.getCollection(Config.projectCollection)
// .find(new Document("project_id", project_id));
// if (iterable.first() != null) {
// Document document = iterable.first();
// json = new JSONObject(document);
// }
// return json;
} catch (Exception e) {
logger.error("Error ", e);
mongoClient.close();
return null;
}
}
}
|
src/main/java/sociam/pybossa/TaskPerformer.java
|
package sociam.pybossa;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import sociam.pybossa.config.Config;
import sociam.pybossa.util.StringToImage;
import sociam.pybossa.util.TwitterAccount;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
/**
*
* @author user Saud Aljaloud
* @author email sza1g10@ecs.soton.ac.uk
*
*/
public class TaskPerformer {
final static Logger logger = Logger.getLogger(TaskPerformer.class);
final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static MongoClient mongoClient = new MongoClient(Config.mongoHost, Config.mongoPort);
static Boolean wasPushed = false;
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.info("TaskPerformer will be repeated every " + Config.TaskCreatorTrigger + " ms");
try {
while (true) {
Config.reload();
run();
logger.info("Sleeping for " + Config.TaskPerformerTrigger + " ms");
Thread.sleep(Integer.valueOf(Config.TaskPerformerTrigger));
}
} catch (InterruptedException e) {
logger.error("Error ", e);
}
}
public static void run() {
try {
HashSet<Document> tasksToBePushed = getReadyTasksFromMongoDB();
if (tasksToBePushed != null) {
logger.info("There are " + tasksToBePushed.size()
+ " tasks that need to be pushed into Twitter, then updating to MongoDB");
for (Document document : tasksToBePushed) {
String task_status = document.getString("task_status");
String task_text = document.getString("task_text");
if (task_status.equals("pushed")) {
Date lastPushAt = document.getDate("lastPushAt");
if (!rePush(lastPushAt)) {
break;
} else {
logger.debug("Repushing task " + task_text);
}
}
ObjectId _id = document.getObjectId("_id");
int pybossa_task_id = document.getInteger("pybossa_task_id");
int project_id = document.getInteger("project_id");
JSONObject project = getProjectByID(project_id);
ArrayList<String> hashtags = new ArrayList<>();
if (project != null) {
JSONArray bin_id = project.getJSONArray("bin_ids");
for (Object object : bin_id) {
String binItem = (String) object;
hashtags.add("#" + binItem);
}
}
String taskTag = "#t" + pybossa_task_id;
int responseCode = sendTaskToTwitter(task_text, taskTag, hashtags, 2);
if (responseCode == 1) {
if (updateTaskToPushedInMongoDB(_id, "pushed")) {
logger.info("Task with text " + task_text + " has been sucessfully pushed to Twitter");
wasPushed = true;
} else {
logger.error(
"Error with updating " + Config.taskCollection + " for the _id " + _id.toString());
}
} else if (responseCode == 0) {
if (updateTaskToPushedInMongoDB(_id, "notValied")) {
logger.debug("Tweeet is not valid because of length, but updated in Mongodb" + task_text);
}
logger.error("Couldn't update the task in MongoDB");
} else if (responseCode == 2) {
if (updateTaskToPushedInMongoDB(_id, "error")) {
logger.debug("pushing tweet has encountered an error, but has been updated into MongoDB "
+ task_text);
} else {
logger.error("Couldn't update the task in MongoDB");
}
}
// TODO: add lastPushAt when updating tasks
if (wasPushed) {
wasPushed = false;
logger.debug(
"waiting for " + Config.TaskPerformerPushRate + " ms before pushing another tweet");
Thread.sleep(Integer.valueOf(Config.TaskPerformerPushRate));
}
}
}
} catch (Exception e) {
logger.error("Error ", e);
}
}
public static Boolean rePush(Date lastPushAt) {
try {
Calendar cal = Calendar.getInstance();
Date currentDate = new Date();
cal.setTime(lastPushAt);
cal.add(Calendar.HOUR, Integer.valueOf(Config.RePushTaskToTwitter));
Date convertedDate = cal.getTime();
return currentDate.before(convertedDate);
} catch (Exception e) {
logger.error("Error ", e);
return false;
}
}
public static Boolean updateTaskToPushedInMongoDB(ObjectId _id, String task_status) {
try {
MongoDatabase database = mongoClient.getDatabase(Config.projectsDatabaseName);
Date date = new Date();
String lastPushAt = MongoDBformatter.format(date);
UpdateResult result = database.getCollection(Config.taskCollection).updateOne(new Document("_id", _id),
new Document().append("$set",
new Document("task_status", task_status).append("lastPushAt", lastPushAt)));
logger.debug(result.toString());
if (result.wasAcknowledged()) {
if (result.getMatchedCount() > 0) {
logger.debug(Config.taskCollection + " Collection was updated where _id= " + _id.toString()
+ " to task_status=" + task_status);
return true;
}
}
return false;
} catch (Exception e) {
logger.error("Error ", e);
return false;
}
}
/**
* This method send a task by a twitter account
*
* @param taskId
* The id of the task to be hashed within the tweet
* @param taskContent
* the content of the tweet to be published
*/
public static int sendTaskToTwitter(String taskContent, String taskTag, ArrayList<String> hashtags,
int project_type) {
try {
Twitter twitter = TwitterAccount.setTwitterAccount(project_type);
// combine hashtags and tasktag while maintaining the 140 length
String post = "";
for (String string : hashtags) {
if (post.length() == 0) {
post = string;
} else {
String tmpResult = post + " " + string + taskTag;
if (tmpResult.length() >= 140) {
break;
}
post = post + " " + string;
}
}
post = post + " " + taskTag;
// defualt
String question = Config.project_validation_question;
if (project_type == 1) {
question = Config.project_validation_question;
}
// convert taskContent and question into an image
File image = StringToImage.convertStringToImage(taskContent, question);
if (post.length() < 140) {
// status = twitter.updateStatus(post);
StatusUpdate status = new StatusUpdate(post);
status.setMedia(image);
twitter.updateStatus(status);
logger.debug("Successfully posting a task '" + status.getStatus() + "'." + status.getPlaceId());
return 1;
} else {
logger.error("Post \"" + post + "\" is longer than 140 characters. It has: " + (post.length()));
return 0;
}
} catch (Exception e) {
logger.error("Error", e);
return 2;
}
}
// static HashSet<Document> NotPushedTasksjsons = new
// LinkedHashSet<Document>();
public static HashSet<Document> getReadyTasksFromMongoDB() {
HashSet<Document> NotPushedTasksjsons = new LinkedHashSet<Document>();
try {
MongoDatabase database = mongoClient.getDatabase(Config.projectsDatabaseName);
FindIterable<Document> iterable = database.getCollection(Config.taskCollection)
.find(new Document("task_status", "ready"));
if (iterable.first() != null) {
for (Document document : iterable) {
NotPushedTasksjsons.add(document);
}
}
return NotPushedTasksjsons;
} catch (Exception e) {
logger.error("Error ", e);
return null;
}
}
public static JSONObject getProjectByID(int project_id) {
logger.debug("getting project by project_id from " + Config.projectCollection + " collection");
try {
JSONObject json = null;
DB database = mongoClient.getDB(Config.projectsDatabaseName);
JSONObject proj = new JSONObject();
proj.put("project_id", project_id);
Object o = com.mongodb.util.JSON.parse(proj.toString());
DBObject dbObj = (DBObject) o;
DBCollection collections = database.getCollection(Config.projectCollection);
DBCursor iterable = collections.find(dbObj);
if(iterable.hasNext()){
json = new JSONObject(iterable.next().toString());
}
return json;
// MongoDatabase database =
// mongoClient.getDatabase(Config.projectsDatabaseName);
// JSONObject json = null;
// FindIterable<Document> iterable =
// database.getCollection(Config.projectCollection)
// .find(new Document("project_id", project_id));
// if (iterable.first() != null) {
// Document document = iterable.first();
// json = new JSONObject(document);
// }
// return json;
} catch (Exception e) {
logger.error("Error ", e);
return null;
}
}
}
|
add close connections
|
src/main/java/sociam/pybossa/TaskPerformer.java
|
add close connections
|
|
Java
|
mit
|
6943dc7f2fbe1f4a5c4e26c05e27f1093c00597e
| 0
|
taursus96/java-commands
|
package taursus.commands;
public class CommandParser implements ICommandParser {
protected static class CommandParserLoader {
private static final CommandParser INSTANCE = new CommandParser();
}
protected CommandParser() {
if (CommandParserLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static CommandParser getInstance() {
return CommandParserLoader.INSTANCE;
}
@Override
public ICommand parse(String str, ICommandsRepository repository) {
StringReader reader = new StringReader();
StringIterator it = new StringIterator(str);
String name = reader.read(it, new CommandNameReadStrategy());
ICommand command = repository.getCommand(name);
if(command == null) {
return null;
}
command.setName(name);
while(it.hasNext()) {
reader.read(it, new CommandSkipToNextParamReadStrategy()); //Skip to next param
String paramName = reader.read(it, new CommandParamNameReadStrategy());
it.skipToNextNonWhiteChar();
String paramValue = "";
if(determineIfParamValueExists(it)) {
boolean isWithinQuotes = determineIfParamValueIsWithinQuotes(it);
paramValue = reader.read(it, new CommandParamValueReadStrategy(isWithinQuotes));
}
command.addParam(paramName, paramValue);
}
return command;
}
private boolean determineIfParamValueExists(StringIterator it) {
if(it.hasNext()) {
char c = it.next();
it.rewind();
if(c != '-') {
return true;
}
}
return false;
}
private boolean determineIfParamValueIsWithinQuotes(StringIterator it) {
if(it.hasNext()) {
boolean withinQuotes = it.next() == '"';
it.rewind();
return withinQuotes;
}
return false;
}
}
|
src/taursus/commands/CommandParser.java
|
package taursus.commands;
public class CommandParser implements ICommandParser {
protected static class CommandParserLoader {
private static final CommandParser INSTANCE = new CommandParser();
}
protected CommandParser() {
if (CommandParserLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static CommandParser getInstance() {
return CommandParserLoader.INSTANCE;
}
protected boolean endsCmdNameParsing(char c) {
return c == ' ';
}
protected boolean startsCmdParamNameParsing(char c) {
return c == '-';
}
protected boolean endsCmdParamNameParsing(char c) {
return c == ' ';
}
protected boolean endsCmdParamValueParsing(char c, boolean withinQuotes) {
if(withinQuotes) {
return c == '"';
} else {
return c == ' ' || startsCmdParamNameParsing(c);
}
}
protected String readCmdName(String str) {
String name = "";
int length = str.length();
for(int i=0; i<length; i++){
char c = str.charAt(i);
if(endsCmdNameParsing(c)) {
break;
}
name += c;
}
return name;
}
protected String readCmdParamName(String str) {
String name = "";
int length = str.length();
for(int i=0; i<length; i++){
char c = str.charAt(i);
if(endsCmdParamNameParsing(c)) {
break;
}
name += c;
}
return name;
}
protected String readCmdParamValue(String str, boolean withinQuotes) {
String name = "";
int length = str.length();
for(int i=0; i<length; i++){
char c = str.charAt(i);
if(endsCmdParamValueParsing(c, withinQuotes)) {
break;
}
name += c;
}
return name;
}
protected String skipToNextParam(String str) {
int skipLength = 0;
int length = str.length();
for(int i=0; i<length; i++){
char c = str.charAt(i);
skipLength++;
if(startsCmdParamNameParsing(c)) {
break;
}
}
return str.substring(skipLength);
}
protected String skipToNextNonWhiteChar(String str) {
int skipLength = 0;
int length = str.length();
for(int i=0; i<length; i++){
char c = str.charAt(i);
if(c != ' ') {
break;
}
skipLength++;
}
return str.substring(skipLength);
}
@Override
public ICommand parse(String str, ICommandsRepository repository) {
String name = readCmdName(str);
ICommand command = repository.getCommand(name);
if(command != null) {
command.setName(name);
str = str.substring(name.length());
while(str.length() > 0) {
str = skipToNextParam(str);
String paramName = readCmdParamName(str);
str = str.substring(paramName.length());
str = skipToNextNonWhiteChar(str);
boolean withinQuotes = false;
if(str.length() > 0 && str.charAt(0) == '"') {
withinQuotes = true;
str = str.substring(1);
}
String paramValue = readCmdParamValue(str, withinQuotes);
command.addParam(paramName, paramValue);
str = str.substring(paramValue.length());
}
}
return command;
}
}
|
refactored CommandParser so it uses read string reader and read strategies
|
src/taursus/commands/CommandParser.java
|
refactored CommandParser so it uses read string reader and read strategies
|
|
Java
|
mit
|
580b5867e43a9411347431c381c6b1ae6bc33f21
| 0
|
CS2103JAN2017-W09-B2/main,CS2103JAN2017-W09-B2/main
|
package seedu.typed.schedule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.Month;
import org.junit.Before;
import org.junit.Test;
import seedu.typed.commons.exceptions.IllegalValueException;
import seedu.typed.model.task.DateTime;
//@@author A0139379M
/**
* Unit Test for ScheduleElement
* which indirectly verifies the validity of Recurrence class
* @author YIM CHIA HUI
*
*/
public class ScheduleElementTest {
private DateTime firstApril = DateTime.getDateTime(2017, Month.APRIL, 1, 0, 0);
private DateTime firstApril2pm = DateTime.getDateTime(2017, Month.APRIL, 1, 14, 0);
private DateTime firstApril4pm = DateTime.getDateTime(2017, Month.APRIL, 1, 16, 0);
private DateTime secondApril2pm = DateTime.getDateTime(2017, Month.APRIL, 2, 14, 0);
private DateTime secondApril4pm = DateTime.getDateTime(2017, Month.APRIL, 2, 16, 0);
private DateTime secondApril = DateTime.getDateTime(2017, Month.APRIL, 2, 0, 0);
private DateTime thirdApril = DateTime.getDateTime(2017, Month.APRIL, 3, 0, 0);
private DateTime eightApril = DateTime.getDateTime(2017, Month.APRIL, 8, 0, 0);
private DateTime nineApril = DateTime.getDateTime(2017, Month.APRIL, 9, 0, 0);
private DateTime firstMay = DateTime.getDateTime(2017, Month.MAY, 1, 0, 0);
private DateTime secondMay = DateTime.getDateTime(2017, Month.MAY, 2, 0, 0);
private DateTime firstApril2018 = DateTime.getDateTime(2018, Month.APRIL, 1, 0, 0);
private DateTime secondApril2018 = DateTime.getDateTime(2018, Month.APRIL, 2, 0, 0);
private ScheduleElement testFloating;
// Deadlines specifics
private ScheduleElement testDeadline;
private ScheduleElement testDeadlineRecurDaily;
private ScheduleElement testDeadlineRecurWeekly;
private ScheduleElement testDeadlineRecurMonthly;
private ScheduleElement testDeadlineRecurYearly;
// Event Specifics
private ScheduleElement testEvent;
private ScheduleElement testEventRecurDaily;
private ScheduleElement testEventRecurWeekly;
private ScheduleElement testEventRecurMonthly;
private ScheduleElement testEventRecurYearly;
// No specific dates input recurring tasks
private ScheduleElement testEveryMonday;
private ScheduleElement testEverySaturday;
@Before
public void setUp() {
try {
testFloating = new ScheduleElement();
testDeadline = new ScheduleElement(firstApril);
testDeadlineRecurDaily = new ScheduleElement(firstApril, "day");
testDeadlineRecurWeekly = new ScheduleElement(firstApril, "week");
testDeadlineRecurMonthly = new ScheduleElement(firstApril, "month");
testDeadlineRecurYearly = new ScheduleElement(firstApril, "year");
testEvent = new ScheduleElement(firstApril, secondApril);
testEventRecurDaily = new ScheduleElement(firstApril2pm, firstApril4pm, "day");
testEventRecurWeekly = new ScheduleElement(firstApril, secondApril, "week");
testEventRecurMonthly = new ScheduleElement(firstApril, secondApril, "month");
testEventRecurYearly = new ScheduleElement(firstApril, secondApril, "year");
testEveryMonday = ScheduleElement.makeDeadline("monday");
testEverySaturday = ScheduleElement.makeDeadline("saturday");
} catch (IllegalValueException e) {
// no exception is expected
e.printStackTrace();
}
}
@Test
public void isDeadline_deadline_true() {
assertTrue(testDeadline.isDeadline());
}
@Test
public void isDeadline_event_false() {
assertFalse(testEvent.isDeadline());
}
@Test
public void isEvent_event_true() {
assertTrue(testEvent.isEvent());
}
@Test
public void isFloating_event_false() {
assertFalse(testEvent.isFloating());
}
/**
* Floating Task Testing
*/
@Test
public void isRecurring_floating_false() {
assertFalse(testFloating.isRecurring());
}
@Test
public void isFloating_floating_true() {
assertTrue(testFloating.isFloating());
}
@Test
public void isDeadline_floating_false() {
assertFalse(testFloating.isDeadline());
}
@Test
public void isEvent_floating_false() {
assertFalse(testFloating.isEvent());
}
@Test
public void nextOccurrence_floating_null() {
assertEquals(testFloating.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void includes_floating_false() {
assertFalse(testFloating.includes(firstApril));
}
@Test
public void updateDate_floating_null() {
assertEquals(testFloating.updateDate(), null);
}
/**
* Deadlines Testing : non-recurring deadlines, recurring daily, weekly, monthly and yearly
*/
@Test
public void isRecurring_testDeadline_false() {
assertFalse(testDeadline.isRecurring());
}
@Test
public void isRecurring_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.isRecurring());
}
@Test
public void isFloating_testDeadline_false() {
assertFalse(testDeadline.isFloating());
}
@Test
public void isDeadline_testDeadline_true() {
assertTrue(testDeadline.isDeadline());
}
@Test
public void isDeadline_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.isDeadline());
}
@Test
public void isEvent_testDeadline_false() {
assertFalse(testDeadline.isEvent());
}
@Test
public void nextOccurrence_testDeadline_null() {
assertEquals(testDeadline.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void nextOccurrence_testDeadlineRecurDaily_secondApril() {
assertTrue(testDeadlineRecurDaily.nextOccurrence(firstApril).equals(secondApril));
}
@Test
public void nextOccurrence_testDeadlineRecurWeekly_eightApril() {
assertTrue(testDeadlineRecurWeekly.nextOccurrence(firstApril).equals(eightApril));
}
@Test
public void nextOccurrence_testDeadlineRecurMonthly_firstMay() {
assertTrue(testDeadlineRecurMonthly.nextOccurrence(firstApril).equals(firstMay));
}
@Test
public void nextOccurrence_testDeadlineRecurYearly_firstApril2018() {
assertTrue(testDeadlineRecurYearly.nextOccurrence(firstApril).equals(firstApril2018));
}
/**
* includes should includes the dates that fall within the recurrence rule
*/
@Test
public void includes_testDeadline_false() {
assertFalse(testDeadline.includes(firstApril));
}
@Test
public void includes_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.includes(firstApril));
assertTrue(testDeadlineRecurDaily.includes(secondApril));
assertTrue(testDeadlineRecurDaily.includes(eightApril));
}
@Test
public void includes_testDeadlineRecurWeekly_true() {
assertTrue(testDeadlineRecurWeekly.includes(firstApril));
assertFalse(testDeadlineRecurWeekly.includes(secondApril));
assertTrue(testDeadlineRecurWeekly.includes(eightApril));
}
@Test
public void includes_testDeadlineRecurMonthly_true() {
assertTrue(testDeadlineRecurMonthly.includes(firstApril));
assertFalse(testDeadlineRecurMonthly.includes(secondApril));
assertFalse(testDeadlineRecurMonthly.includes(eightApril));
assertTrue(testDeadlineRecurMonthly.includes(firstMay));
}
@Test
public void includes_testDeadlineRecurYearly_true() {
assertTrue(testDeadlineRecurYearly.includes(firstApril));
assertFalse(testDeadlineRecurYearly.includes(secondApril));
assertFalse(testDeadlineRecurYearly.includes(eightApril));
assertTrue(testDeadlineRecurYearly.includes(firstApril2018));
}
/**
* updateDate should return the next occurrence of the recurring deadlines
*/
@Test
public void updateDate_testDeadlineRecurDaily_secondApril() {
assertTrue(testDeadlineRecurDaily.updateDate().getDate().equals(secondApril));
}
@Test
public void updateDate_testDeadlineRecurWeekly_eightApril() {
assertTrue(testDeadlineRecurWeekly.updateDate().getDate().equals(eightApril));
}
@Test
public void updateDate_testDeadlineRecurMonthly_firstMay() {
assertTrue(testDeadlineRecurMonthly.updateDate().getDate().equals(firstMay));
}
@Test
public void updateDate_testDeadlineRecurYearly_firstApril2018() {
assertTrue(testDeadlineRecurYearly.updateDate().getDate().equals(firstApril2018));
}
/**
* Events Testing : non-recurring events, recurring daily, weekly, monthly and yearly events
*/
/**
* nextOccurrence should return the next occurrence of the recurrence
*/
@Test
public void nextOccurrence_testEvent_null() {
assertEquals(testEvent.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void nextOccurrence_testEventRecurDaily_secondApril2pm() {
DateTime endDate = testEventRecurDaily.getEndDate();
assertTrue(testEventRecurDaily.nextOccurrence(endDate).equals(secondApril2pm));
}
@Test
public void nextOccurrence_testEventRecurWeekly_eightApril() {
DateTime endDate = testEventRecurWeekly.getEndDate();
assertTrue(testEventRecurWeekly.nextOccurrence(endDate).equals(eightApril));
}
@Test
public void nextOccurrence_testEventRecurMonthly_firstMay() {
DateTime endDate = testEventRecurMonthly.getEndDate();
assertTrue(testEventRecurMonthly.nextOccurrence(endDate).equals(firstMay));
}
@Test
public void nextOccurrence_testEventRecurYearly_firstApril2018() {
DateTime endDate = testEventRecurYearly.getEndDate();
assertTrue(testEventRecurYearly.nextOccurrence(endDate).equals(firstApril2018));
}
/**
* includes should includes the dates that fall within the recurrence rule
* In particular, includes should only work for recurring tasks
*/
@Test
public void includes_testEvent_false() {
// not recurring
assertFalse(testEvent.includes(firstApril));
}
@Test
public void includes_testEventRecurDaily_true() {
assertTrue(testEventRecurDaily.includes(firstApril));
assertTrue(testEventRecurDaily.includes(secondApril));
assertTrue(testEventRecurDaily.includes(eightApril));
}
@Test
public void includes_testEventRecurWeekly_true() {
assertTrue(testEventRecurWeekly.includes(firstApril));
// the event last between 1st april to 2nd april hence it should include second april
assertTrue(testEventRecurWeekly.includes(secondApril));
assertFalse(testEventRecurWeekly.includes(thirdApril));
assertTrue(testEventRecurWeekly.includes(eightApril));
}
@Test
public void includes_testEventRecurMonthly_true() {
assertTrue(testEventRecurMonthly.includes(firstApril));
assertTrue(testEventRecurMonthly.includes(secondApril));
assertFalse(testEventRecurMonthly.includes(eightApril));
assertTrue(testEventRecurMonthly.includes(firstMay));
}
@Test
public void includes_testEventRecurYearly_true() {
assertTrue(testEventRecurYearly.includes(firstApril));
assertTrue(testEventRecurYearly.includes(secondApril));
assertFalse(testEventRecurYearly.includes(eightApril));
assertTrue(testEventRecurYearly.includes(firstApril2018));
}
/**
* updateDate should return the next occurrence of the recurring deadlines
* For events, both startDate and endDate needs to be verified
*/
@Test
public void updateDate_testEventRecurDaily_secondApril2pmTosecondApril4pm() {
assertTrue(testEventRecurDaily.updateDate().getStartDate().equals(secondApril2pm));
assertTrue(testEventRecurDaily.updateDate().getEndDate().equals(secondApril4pm));
}
@Test
public void updateDate_testEventRecurWeekly_eightAprilToNineApril() {
assertTrue(testEventRecurWeekly.updateDate().getStartDate().equals(eightApril));
assertTrue(testEventRecurWeekly.updateDate().getEndDate().equals(nineApril));
}
@Test
public void updateDate_testEventRecurMonthly_firstMayToSecondMay() {
assertTrue(testEventRecurMonthly.updateDate().getStartDate().equals(firstMay));
assertTrue(testEventRecurMonthly.updateDate().getEndDate().equals(secondMay));
}
@Test
public void updateDate_testEventRecurYearly_firstApril2018() {
assertTrue(testEventRecurYearly.updateDate().getStartDate().equals(firstApril2018));
assertTrue(testEventRecurYearly.updateDate().getEndDate().equals(secondApril2018));
}
/**
* As overdue method is time sensitive, it is strictly overdue if the today's date is after
* the date (for deadline) or end date (for events). Since today always change, we just
* test if it's overdue if today is after the date
*/
@Test
public void isOverdue_floating_false() {
assertFalse(testFloating.isOverdue());
}
@Test
public void isOverdue_testDeadline() {
DateTime today = DateTime.getToday();
assertEquals(testDeadline.isOverdue(), today.isAfter(testDeadline.getDate()));
}
@Test
public void isOverdue_testEvent() {
DateTime today = DateTime.getToday();
assertEquals(testEvent.isOverdue(), today.isAfter(testEvent.getEndDate()));
}
/**
* Testing for special add commands like add task every monday (with no date specified)
* includes test format : includes_SCHEDULEELEMENTForDATE_OUTCOME
*/
@Test
public void includes_testEveryMondayForFirstApril_false() {
assertFalse(testEveryMonday.includes(firstApril));
}
@Test
public void includes_testEveryMondayForThirdApril_true() {
assertTrue(testEveryMonday.includes(thirdApril));
}
@Test
public void includes_testEverySaturdayForFirstApril_true() {
assertTrue(testEverySaturday.includes(firstApril));
}
@Test
public void includes_testEverySaturdayForSecondApril_false() {
assertFalse(testEverySaturday.includes(secondApril));
}
/**
* NextOccurrence format : nextOccurrence_SCHEDULEELEMENT_DATE_OUTCOME
* As it is very time sensitive, every time we create a "every saturday"
* it will be based on the current time now (which is different every time)
*/
@Test
public void nextOccurrence_testEverySaturday_7dayslaterFromItsDate() {
DateTime date = testEverySaturday.getDate();
assertTrue(testEverySaturday.nextOccurrence(date).equals(date.nextDays(7)));
}
@Test
public void nextOccurrence_testEveryMonday_firstApril_7dayslaterFromItsDate() {
DateTime date = testEveryMonday.getDate();
assertTrue(testEveryMonday.nextOccurrence(date).equals(date.nextDays(7)));
}
}
|
src/test/java/seedu/typed/schedule/ScheduleElementTest.java
|
package seedu.typed.schedule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.Month;
import org.junit.Before;
import org.junit.Test;
import seedu.typed.commons.exceptions.IllegalValueException;
import seedu.typed.model.task.DateTime;
//@@author A0139379M
/**
* Unit Test for ScheduleElement
* which indirectly verifies the validity of Recurrence class
* @author YIM CHIA HUI
*
*/
public class ScheduleElementTest {
private DateTime firstApril = DateTime.getDateTime(2017, Month.APRIL, 1, 0, 0);
private DateTime firstApril2pm = DateTime.getDateTime(2017, Month.APRIL, 1, 14, 0);
private DateTime firstApril4pm = DateTime.getDateTime(2017, Month.APRIL, 1, 16, 0);
private DateTime secondApril2pm = DateTime.getDateTime(2017, Month.APRIL, 2, 14, 0);
private DateTime secondApril4pm = DateTime.getDateTime(2017, Month.APRIL, 2, 16, 0);
private DateTime secondApril = DateTime.getDateTime(2017, Month.APRIL, 2, 0, 0);
private DateTime thirdApril = DateTime.getDateTime(2017, Month.APRIL, 3, 0, 0);
private DateTime eightApril = DateTime.getDateTime(2017, Month.APRIL, 8, 0, 0);
private DateTime nineApril = DateTime.getDateTime(2017, Month.APRIL, 9, 0, 0);
private DateTime firstMay = DateTime.getDateTime(2017, Month.MAY, 1, 0, 0);
private DateTime secondMay = DateTime.getDateTime(2017, Month.MAY, 2, 0, 0);
private DateTime firstApril2018 = DateTime.getDateTime(2018, Month.APRIL, 1, 0, 0);
private DateTime secondApril2018 = DateTime.getDateTime(2018, Month.APRIL, 2, 0, 0);
private ScheduleElement testFloating;
// Deadlines specifics
private ScheduleElement testDeadline;
private ScheduleElement testDeadlineRecurDaily;
private ScheduleElement testDeadlineRecurWeekly;
private ScheduleElement testDeadlineRecurMonthly;
private ScheduleElement testDeadlineRecurYearly;
// Event Specifics
private ScheduleElement testEvent;
private ScheduleElement testEventRecurDaily;
private ScheduleElement testEventRecurWeekly;
private ScheduleElement testEventRecurMonthly;
private ScheduleElement testEventRecurYearly;
// No specific dates input recurring tasks
private ScheduleElement testEveryMonday;
private ScheduleElement testEverySaturday;
@Before
public void setUp() {
try {
testFloating = new ScheduleElement();
testDeadline = new ScheduleElement(firstApril);
testDeadlineRecurDaily = new ScheduleElement(firstApril, "day");
testDeadlineRecurWeekly = new ScheduleElement(firstApril, "week");
testDeadlineRecurMonthly = new ScheduleElement(firstApril, "month");
testDeadlineRecurYearly = new ScheduleElement(firstApril, "year");
testEvent = new ScheduleElement(firstApril, secondApril);
testEventRecurDaily = new ScheduleElement(firstApril2pm, firstApril4pm, "day");
testEventRecurWeekly = new ScheduleElement(firstApril, secondApril, "week");
testEventRecurMonthly = new ScheduleElement(firstApril, secondApril, "month");
testEventRecurYearly = new ScheduleElement(firstApril, secondApril, "year");
testEveryMonday = new ScheduleElement("monday");
testEverySaturday = new ScheduleElement("saturday");
} catch (IllegalValueException e) {
// no exception is expected
e.printStackTrace();
}
}
@Test
public void isDeadline_deadline_true() {
assertTrue(testDeadline.isDeadline());
}
@Test
public void isDeadline_event_false() {
assertFalse(testEvent.isDeadline());
}
@Test
public void isEvent_event_true() {
assertTrue(testEvent.isEvent());
}
@Test
public void isFloating_event_false() {
assertFalse(testEvent.isFloating());
}
/**
* Floating Task Testing
*/
@Test
public void isRecurring_floating_false() {
assertFalse(testFloating.isRecurring());
}
@Test
public void isFloating_floating_true() {
assertTrue(testFloating.isFloating());
}
@Test
public void isDeadline_floating_false() {
assertFalse(testFloating.isDeadline());
}
@Test
public void isEvent_floating_false() {
assertFalse(testFloating.isEvent());
}
@Test
public void nextOccurrence_floating_null() {
assertEquals(testFloating.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void includes_floating_false() {
assertFalse(testFloating.includes(firstApril));
}
@Test
public void updateDate_floating_null() {
assertEquals(testFloating.updateDate(), null);
}
/**
* Deadlines Testing : non-recurring deadlines, recurring daily, weekly, monthly and yearly
*/
@Test
public void isRecurring_testDeadline_false() {
assertFalse(testDeadline.isRecurring());
}
@Test
public void isRecurring_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.isRecurring());
}
@Test
public void isFloating_testDeadline_false() {
assertFalse(testDeadline.isFloating());
}
@Test
public void isDeadline_testDeadline_true() {
assertTrue(testDeadline.isDeadline());
}
@Test
public void isDeadline_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.isDeadline());
}
@Test
public void isEvent_testDeadline_false() {
assertFalse(testDeadline.isEvent());
}
@Test
public void nextOccurrence_testDeadline_null() {
assertEquals(testDeadline.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void nextOccurrence_testDeadlineRecurDaily_secondApril() {
assertTrue(testDeadlineRecurDaily.nextOccurrence(firstApril).equals(secondApril));
}
@Test
public void nextOccurrence_testDeadlineRecurWeekly_eightApril() {
assertTrue(testDeadlineRecurWeekly.nextOccurrence(firstApril).equals(eightApril));
}
@Test
public void nextOccurrence_testDeadlineRecurMonthly_firstMay() {
assertTrue(testDeadlineRecurMonthly.nextOccurrence(firstApril).equals(firstMay));
}
@Test
public void nextOccurrence_testDeadlineRecurYearly_firstApril2018() {
assertTrue(testDeadlineRecurYearly.nextOccurrence(firstApril).equals(firstApril2018));
}
/**
* includes should includes the dates that fall within the recurrence rule
*/
@Test
public void includes_testDeadline_false() {
assertFalse(testDeadline.includes(firstApril));
}
@Test
public void includes_testDeadlineRecurDaily_true() {
assertTrue(testDeadlineRecurDaily.includes(firstApril));
assertTrue(testDeadlineRecurDaily.includes(secondApril));
assertTrue(testDeadlineRecurDaily.includes(eightApril));
}
@Test
public void includes_testDeadlineRecurWeekly_true() {
assertTrue(testDeadlineRecurWeekly.includes(firstApril));
assertFalse(testDeadlineRecurWeekly.includes(secondApril));
assertTrue(testDeadlineRecurWeekly.includes(eightApril));
}
@Test
public void includes_testDeadlineRecurMonthly_true() {
assertTrue(testDeadlineRecurMonthly.includes(firstApril));
assertFalse(testDeadlineRecurMonthly.includes(secondApril));
assertFalse(testDeadlineRecurMonthly.includes(eightApril));
assertTrue(testDeadlineRecurMonthly.includes(firstMay));
}
@Test
public void includes_testDeadlineRecurYearly_true() {
assertTrue(testDeadlineRecurYearly.includes(firstApril));
assertFalse(testDeadlineRecurYearly.includes(secondApril));
assertFalse(testDeadlineRecurYearly.includes(eightApril));
assertTrue(testDeadlineRecurYearly.includes(firstApril2018));
}
/**
* updateDate should return the next occurrence of the recurring deadlines
*/
@Test
public void updateDate_testDeadlineRecurDaily_secondApril() {
assertTrue(testDeadlineRecurDaily.updateDate().getDate().equals(secondApril));
}
@Test
public void updateDate_testDeadlineRecurWeekly_eightApril() {
assertTrue(testDeadlineRecurWeekly.updateDate().getDate().equals(eightApril));
}
@Test
public void updateDate_testDeadlineRecurMonthly_firstMay() {
assertTrue(testDeadlineRecurMonthly.updateDate().getDate().equals(firstMay));
}
@Test
public void updateDate_testDeadlineRecurYearly_firstApril2018() {
assertTrue(testDeadlineRecurYearly.updateDate().getDate().equals(firstApril2018));
}
/**
* Events Testing : non-recurring events, recurring daily, weekly, monthly and yearly events
*/
/**
* nextOccurrence should return the next occurrence of the recurrence
*/
@Test
public void nextOccurrence_testEvent_null() {
assertEquals(testEvent.nextOccurrence(DateTime.getToday()), null);
}
@Test
public void nextOccurrence_testEventRecurDaily_secondApril2pm() {
DateTime endDate = testEventRecurDaily.getEndDate();
assertTrue(testEventRecurDaily.nextOccurrence(endDate).equals(secondApril2pm));
}
@Test
public void nextOccurrence_testEventRecurWeekly_eightApril() {
DateTime endDate = testEventRecurWeekly.getEndDate();
assertTrue(testEventRecurWeekly.nextOccurrence(endDate).equals(eightApril));
}
@Test
public void nextOccurrence_testEventRecurMonthly_firstMay() {
DateTime endDate = testEventRecurMonthly.getEndDate();
assertTrue(testEventRecurMonthly.nextOccurrence(endDate).equals(firstMay));
}
@Test
public void nextOccurrence_testEventRecurYearly_firstApril2018() {
DateTime endDate = testEventRecurYearly.getEndDate();
assertTrue(testEventRecurYearly.nextOccurrence(endDate).equals(firstApril2018));
}
/**
* includes should includes the dates that fall within the recurrence rule
* In particular, includes should only work for recurring tasks
*/
@Test
public void includes_testEvent_false() {
// not recurring
assertFalse(testEvent.includes(firstApril));
}
@Test
public void includes_testEventRecurDaily_true() {
assertTrue(testEventRecurDaily.includes(firstApril));
assertTrue(testEventRecurDaily.includes(secondApril));
assertTrue(testEventRecurDaily.includes(eightApril));
}
@Test
public void includes_testEventRecurWeekly_true() {
assertTrue(testEventRecurWeekly.includes(firstApril));
// the event last between 1st april to 2nd april hence it should include second april
assertTrue(testEventRecurWeekly.includes(secondApril));
assertFalse(testEventRecurWeekly.includes(thirdApril));
assertTrue(testEventRecurWeekly.includes(eightApril));
}
@Test
public void includes_testEventRecurMonthly_true() {
assertTrue(testEventRecurMonthly.includes(firstApril));
assertTrue(testEventRecurMonthly.includes(secondApril));
assertFalse(testEventRecurMonthly.includes(eightApril));
assertTrue(testEventRecurMonthly.includes(firstMay));
}
@Test
public void includes_testEventRecurYearly_true() {
assertTrue(testEventRecurYearly.includes(firstApril));
assertTrue(testEventRecurYearly.includes(secondApril));
assertFalse(testEventRecurYearly.includes(eightApril));
assertTrue(testEventRecurYearly.includes(firstApril2018));
}
/**
* updateDate should return the next occurrence of the recurring deadlines
* For events, both startDate and endDate needs to be verified
*/
@Test
public void updateDate_testEventRecurDaily_secondApril2pmTosecondApril4pm() {
assertTrue(testEventRecurDaily.updateDate().getStartDate().equals(secondApril2pm));
assertTrue(testEventRecurDaily.updateDate().getEndDate().equals(secondApril4pm));
}
@Test
public void updateDate_testEventRecurWeekly_eightAprilToNineApril() {
assertTrue(testEventRecurWeekly.updateDate().getStartDate().equals(eightApril));
assertTrue(testEventRecurWeekly.updateDate().getEndDate().equals(nineApril));
}
@Test
public void updateDate_testEventRecurMonthly_firstMayToSecondMay() {
assertTrue(testEventRecurMonthly.updateDate().getStartDate().equals(firstMay));
assertTrue(testEventRecurMonthly.updateDate().getEndDate().equals(secondMay));
}
@Test
public void updateDate_testEventRecurYearly_firstApril2018() {
assertTrue(testEventRecurYearly.updateDate().getStartDate().equals(firstApril2018));
assertTrue(testEventRecurYearly.updateDate().getEndDate().equals(secondApril2018));
}
/**
* As overdue method is time sensitive, it is strictly overdue if the today's date is after
* the date (for deadline) or end date (for events). Since today always change, we just
* test if it's overdue if today is after the date
*/
@Test
public void isOverdue_floating_false() {
assertFalse(testFloating.isOverdue());
}
@Test
public void isOverdue_testDeadline() {
DateTime today = DateTime.getToday();
assertEquals(testDeadline.isOverdue(), today.isAfter(testDeadline.getDate()));
}
@Test
public void isOverdue_testEvent() {
DateTime today = DateTime.getToday();
assertEquals(testEvent.isOverdue(), today.isAfter(testEvent.getEndDate()));
}
/**
* Testing for special add commands like add task every monday (with no date specified)
* includes test format : includes_SCHEDULEELEMENTForDATE_OUTCOME
*/
@Test
public void includes_testEveryMondayForFirstApril_false() {
assertFalse(testEveryMonday.includes(firstApril));
}
@Test
public void includes_testEveryMondayForThirdApril_true() {
assertTrue(testEveryMonday.includes(thirdApril));
}
@Test
public void includes_testEverySaturdayForFirstApril_true() {
assertTrue(testEverySaturday.includes(firstApril));
}
@Test
public void includes_testEverySaturdayForSecondApril_false() {
assertFalse(testEverySaturday.includes(secondApril));
}
/**
* NextOccurrence format : nextOccurrence_SCHEDULEELEMENT_DATE_OUTCOME
* As it is very time sensitive, every time we create a "every saturday"
* it will be based on the current time now (which is different every time)
*/
@Test
public void nextOccurrence_testEverySaturday_7dayslaterFromItsDate() {
DateTime date = testEverySaturday.getDate();
assertTrue(testEverySaturday.nextOccurrence(date).equals(date.nextDays(7)));
}
@Test
public void nextOccurrence_testEveryMonday_firstApril_7dayslaterFromItsDate() {
DateTime date = testEveryMonday.getDate();
assertTrue(testEveryMonday.nextOccurrence(date).equals(date.nextDays(7)));
}
}
|
Fixed travis
|
src/test/java/seedu/typed/schedule/ScheduleElementTest.java
|
Fixed travis
|
|
Java
|
mit
|
24070d59b810bdcb2fb73eea1e4fc9afb926a5ca
| 0
|
CjHare/systematic-trading
|
/**
* Copyright (c) 2015-2017, CJ Hare 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 [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 HOLDER 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.systematic.trading.maths.indicator;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* Verifies the IllegalArgumentThrowingValidator behaviour.
*
* @author CJ Hare
*/
public class IllegalArgumentThrowingValidatorTest {
@Test
public void verifyEnoughValues() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add("two");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotEnoughValues() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyEnoughValuesAllNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add(null);
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesIgnoringStartingNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add("one");
data.add("two");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesIgnoringLastNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add("two");
data.add(null);
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArray() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[2];
data[0] = "one";
data[1] = "two";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotEnoughValuesArray() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[1];
data[0] = "one";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyEnoughValuesArrayAllNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[2];
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArrayIgnoringStartingNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = null;
data[1] = "one";
data[2] = "two";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArrayIgnoringLastNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = "two";
data[2] = null;
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyZeroNullEntriesEmpty() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntries() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesStartingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add("one");
data.add("two");
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesMidNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add(null);
data.add("two");
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntriesArrayEmpty() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[0];
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntriesArray() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[1];
data[0] = "one";
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesSArraytartingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = null;
data[1] = "one";
data[2] = "two";
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesArrayEndingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = "two";
data[2] = null;
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesArrayMidNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = null;
data[2] = "two";
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyNotNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[0];
validator.verifyNotNull(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotNullWhenNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
validator.verifyNotNull(null);
}
}
|
systematic-trading-maths/src/test/java/com/systematic/trading/maths/indicator/IllegalArgumentThrowingValidatorTest.java
|
/**
* Copyright (c) 2015-2017, CJ Hare 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 [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 HOLDER 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.systematic.trading.maths.indicator;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* Verifies the IllegalArgumentThrowingValidator behaviour.
*
* @author CJ Hare
*/
public class IllegalArgumentThrowingValidatorTest {
@Test
public void verifyEnoughValues() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add("two");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotEnoughValues() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyEnoughValuesAllNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add(null);
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesIgnoringStartingNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add("one");
data.add("two");
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesIgnoringLastNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add("two");
data.add(null);
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArray() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[2];
data[0] = "one";
data[1] = "two";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotEnoughValuesArray() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[1];
data[0] = "one";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test(expected = IllegalArgumentException.class)
public void verifyEnoughValuesArrayAllNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[2];
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArrayIgnoringStartingNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = null;
data[1] = "one";
data[2] = "two";
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyEnoughValuesArrayIgnoringLastNull() {
final int requiredNumberOfPrices = 2;
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = "two";
data[2] = null;
validator.verifyEnoughValues(data, requiredNumberOfPrices);
}
@Test
public void verifyZeroNullEntriesEmpty() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntries() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesStartingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add(null);
data.add("one");
data.add("two");
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesMidNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final List<String> data = new ArrayList<String>();
data.add("one");
data.add(null);
data.add("two");
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntriesArrayEmpty() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[0];
validator.verifyZeroNullEntries(data);
}
@Test
public void verifyZeroNullEntriesArray() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[1];
data[0] = "one";
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesSArraytartingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = null;
data[1] = "one";
data[2] = "two";
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesArrayEndingNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = "two";
data[2] = null;
validator.verifyZeroNullEntries(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyZeroNullEntriesArrayMidNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[3];
data[0] = "one";
data[1] = null;
data[2] = "two";
validator.verifyZeroNullEntries(data);
}
public void verifyNotNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
final String[] data = new String[0];
validator.verifyNotNull(data);
}
@Test(expected = IllegalArgumentException.class)
public void verifyNotNullWhenNull() {
final IllegalArgumentThrowingValidator validator = new IllegalArgumentThrowingValidator();
validator.verifyNotNull(null);
}
}
|
Missed @Test
|
systematic-trading-maths/src/test/java/com/systematic/trading/maths/indicator/IllegalArgumentThrowingValidatorTest.java
|
Missed @Test
|
|
Java
|
mit
|
3c9b5af1efb4dab4c5131d279176e55c12c1ccd5
| 0
|
stallboy/configgen,stallboy/configgen
|
package configgen.gen;
import configgen.define.Bean;
import configgen.define.Column;
import configgen.genjava.IndentPrint;
import configgen.type.*;
import configgen.value.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;
public class GenLua extends Generator {
static void register() {
providers.put("lua", new Provider() {
@Override
public Generator create(Parameter parameter) {
return new GenLua(parameter);
}
@Override
public String usage() {
return "dir:.,pkg:cfg,encoding:UTF-8 add ,own:x if need, cooperate with -gen bin, -gen pack";
}
});
}
private final String dir;
private final String pkg;
private final String encoding;
private final String own;
private VDb value;
private GenLua(Parameter parameter) {
super(parameter);
dir = parameter.get("dir", ".");
pkg = parameter.getNotEmpty("pkg", "cfg");
encoding = parameter.get("encoding", "UTF-8");
own = parameter.get("own", null);
parameter.end();
}
@Override
public void generate(VDb _value) throws IOException {
File dstDir = Paths.get(dir).resolve(pkg.replace('.', '/')).toFile();
value = own != null ? extract(_value, own) : _value;
try (IndentPrint ps = createCode(new File(dstDir, "_cfgs.lua"), encoding)) {
generate_cfgs(ps);
}
try (IndentPrint ps = createCode(new File(dstDir, "_loads.lua"), encoding)) {
generate_loads(ps);
}
try (IndentPrint ps = createCode(new File(dstDir, "_beans.lua"), encoding)) {
generate_beans(ps);
}
for (VTable v : value.vtables.values()) {
Name name = new Name(pkg, v.name);
try (IndentPrint ps = createCode(dstDir.toPath().resolve(name.path).toFile(), encoding)) {
generate_table(v, name, ps);
}
}
CachedFileOutputStream.keepMetaAndDeleteOtherFiles(dstDir);
}
private static class Name {
final String pkg;
final String className;
final String fullName;
final String path;
Name(String topPkg, String configName) {
String[] seps = configName.split("\\.");
String[] pks = new String[seps.length - 1];
for (int i = 0; i < pks.length; i++)
pks[i] = seps[i].toLowerCase();
className = seps[seps.length - 1].toLowerCase();
if (pks.length == 0)
pkg = topPkg;
else
pkg = topPkg + "." + String.join(".", pks);
if (pkg.isEmpty())
fullName = className;
else
fullName = pkg + "." + className;
if (pks.length == 0)
path = className + ".lua";
else
path = String.join("/", pks) + "/" + className + ".lua";
}
}
private void generate_cfgs(IndentPrint ps) {
ps.println("local %s = {}", pkg);
ps.println();
ps.println("%s._mk = require \"common.mkcfg\"", pkg);
ps.println();
Set<String> context = new HashSet<>();
context.add(pkg);
for (TTable c : value.dbType.ttables.values()) {
String name = fullName(c);
define(name, ps, context);
context.add(name);
}
ps.println();
ps.println("return %s", pkg);
}
private void define(String beanName, IndentPrint ps, Set<String> context) {
List<String> seps = Arrays.asList(beanName.split("\\."));
for (int i = 0; i < seps.size(); i++) {
String pkg = String.join(".", seps.subList(0, i + 1));
if (context.add(pkg)) {
ps.println(pkg + " = {}");
}
}
}
private void generate_loads(IndentPrint ps) {
ps.println("local require = require");
ps.println();
for (TTable c : value.dbType.ttables.values()) {
ps.println("require \"%s\"", fullName(c));
}
ps.println();
}
private void generate_beans(IndentPrint ps) {
ps.println("local %s = require \"%s._cfgs\"", pkg, pkg);
ps.println();
ps.println("local Beans = {}");
ps.println("%s._beans = Beans", pkg);
ps.println();
ps.println("local bean = %s._mk.bean", pkg);
ps.println("local action = %s._mk.action", pkg);
ps.println();
for (TBean tbean : value.dbType.tbeans.values()) {
if (tbean.beanDefine.type == Bean.BeanType.BaseAction) {
ps.println("%s = {}", fullName(tbean));
for (TBean actionBean : tbean.actionBeans.values()) {
//function mkcfg.action(typeName, refs, ...)
ps.println("%s = action(\"%s\", %s, %s\n )", fullName(actionBean), actionBean.name, getLuaRefsString(actionBean), getLuaFieldsString(actionBean));
}
} else {
//function mkcfg.bean(refs, ...)
ps.println("%s = bean(%s, %s\n )", fullName(tbean), getLuaRefsString(tbean), getLuaFieldsString(tbean));
}
}
ps.println();
ps.println("return Beans");
}
private void generate_table(VTable vtable, Name name, IndentPrint ps) {
TTable ttable = vtable.tableType;
TBean tbean = ttable.tbean;
ps.println("local %s = require \"%s._cfgs\"", pkg, pkg);
ps.println();
if (ttable.tbean.hasSubBean()) {
ps.println("local Beans = %s._beans", pkg);
ps.println();
}
//function mkcfg.table(self, uniqkeys, enumidx, refs, ...)
ps.println("local mk = %s._mk.table(%s, %s, %s, %s, %s\n )", pkg, name.fullName, getLuaUniqKeysString(ttable), getLuaEnumIdxString(ttable), getLuaRefsString(tbean), getLuaFieldsString(tbean));
ps.println();
for (VBean vBean : vtable.vbeanList) {
ps.println(getLuaValueString(vBean, "mk", false));
}
}
private String getLuaValueString(Value thisValue) {
return getLuaValueString(thisValue, null, false);
}
private String getLuaValueString(Value thisValue, String beanTypeStr, boolean asKey) {
String[] v = new String[1];
thisValue.accept(new ValueVisitor() {
@Override
public void visit(VBool value) {
v[0] = String.valueOf(value.value);
}
@Override
public void visit(VInt value) {
v[0] = String.valueOf(value.value);
}
@Override
public void visit(VLong value) {
v[0] = String.valueOf(value.value);
}
@Override
public void visit(VFloat value) {
v[0] = String.valueOf(value.value);
}
@Override
public void visit(VString value) {
String val = value.value.replace("\r\n", "\\n");
String val2 = val.replace("\n", "\\n");
if (asKey) {
v[0] = val2;
} else {
v[0] = String.format("\"%s\"", val2);
}
}
@Override
public void visit(VList value) {
List<String> list = new ArrayList<>();
for (Value eleValue : value.list) {
list.add(getLuaValueString(eleValue));
}
String liststr = String.join(", ", list);
v[0] = String.format("{%s}", liststr);
}
@Override
public void visit(VMap value) {
List<String> list = new ArrayList<>();
for (Map.Entry<Value, Value> entry : value.map.entrySet()) {
String key = getLuaValueString(entry.getKey(), null, true);
String val = getLuaValueString(entry.getValue());
list.add(String.format("%s = %s", key, val));
}
String liststr = String.join(", ", list);
v[0] = String.format("{%s}", liststr);
}
@Override
public void visit(VBean value) {
VBean val = value;
if (value.beanType.beanDefine.type == Bean.BeanType.BaseAction) {
val = value.actionVBean;
}
String beanType = beanTypeStr;
if (beanType == null) {
beanType = fullName(val.beanType);
}
List<String> list = new ArrayList<>();
for (Value fieldValue : value.valueMap.values()) {
list.add(getLuaValueString(fieldValue));
}
String params = String.join(", ", list);
v[0] = String.format("%s(%s)", beanType, params);
}
});
return v[0];
}
// uniqkeys : {{allname=, getname=, keyidx1=, keyidx2=}, }
private String getLuaUniqKeysString(TTable ttable) {
StringBuilder sb = new StringBuilder();
sb.append("{ ");
sb.append(getLuaOneUniqKeyString(ttable, ttable.primaryKey, true));
for (Map<String, Type> uniqueKey : ttable.uniqueKeys) {
sb.append(getLuaOneUniqKeyString(ttable, uniqueKey, false));
}
sb.append("}");
return sb.toString();
}
private String getLuaOneUniqKeyString(TTable ttable, Map<String, Type> keys, boolean isPrimaryKey) {
String allname = isPrimaryKey ? "all" : uniqueKeyMapName(keys);
String getname = isPrimaryKey ? "get" : uniqueKeyGetByName(keys);
Iterator<String> it = keys.keySet().iterator();
String key1 = it.next();
int keyidx1 = findFieldIdx(ttable.tbean, key1);
boolean hasKeyIdx2 = false;
int keyidx2 = 0;
if (keys.size() > 1) {
if (keys.size() != 2) {
throw new RuntimeException("uniqkeys size != 2 " + ttable.name);
}
String key2 = it.next();
hasKeyIdx2 = true;
keyidx2 = findFieldIdx(ttable.tbean, key2);
}
if (hasKeyIdx2) {
return String.format("{ \"%s\", \"%s\", %d, %d }, ", allname, getname, keyidx1, keyidx2);
} else {
return String.format("{ \"%s\", \"%s\", %d }, ", allname, getname, keyidx1);
}
}
private String getLuaEnumIdxString(TTable ttable) {
switch (ttable.tableDefine.enumType) {
case None:
return "nil";
default:
return String.valueOf(findFieldIdx(ttable.tbean, ttable.tableDefine.enumStr));
}
}
// refs { {refname, dsttable, dstgetname, keyidx1, keyidx2}, }
private String getLuaRefsString(TBean tbean) {
StringBuilder sb = new StringBuilder();
boolean hasRef = false;
sb.append("{ ");
int i = 0;
for (Type t : tbean.columns.values()) {
i++;
for (SRef r : t.constraint.references) {
String refname = refName(r);
String dsttable = fullName(r.refTable);
String dstgetname = uniqueKeyGetByName(r.refCols);
sb.append(String.format("\n { \"%s\", %s, \"%s\", %d }, ", refname, dsttable, dstgetname, i));
hasRef = true;
}
}
for (TForeignKey mRef : tbean.mRefs) {
String refname = refName(mRef);
String dsttable = fullName(mRef.refTable);
String dstgetname = uniqueKeyGetByName(mRef.foreignKeyDefine.ref.cols);
int keyidx1 = findFieldIdx(tbean, mRef.foreignKeyDefine.keys[0]);
boolean hasKeyIdx2 = false;
int keyidx2 = 0;
if (mRef.foreignKeyDefine.keys.length > 1) {
if (mRef.foreignKeyDefine.keys.length != 2) {
throw new RuntimeException("keys length != 2 " + tbean.name);
}
hasKeyIdx2 = true;
keyidx2 = findFieldIdx(tbean, mRef.foreignKeyDefine.keys[1]);
}
if (hasKeyIdx2) {
sb.append(String.format("\n { \"%s\", %s, \"%s\", %d, %d }, ", refname, dsttable, dstgetname, keyidx1, keyidx2));
} else {
sb.append(String.format("\n { \"%s\", %s, \"%s\", %d }, ", refname, dsttable, dstgetname, keyidx1));
}
hasRef = true;
}
sb.append("}");
//忽略ListRef
if (hasRef) {
return sb.toString();
} else {
return "nil";
}
}
private String getLuaFieldsString(TBean tbean) {
StringBuilder sb = new StringBuilder();
int cnt = tbean.columns.size();
int i = 0;
for (String n : tbean.columns.keySet()) {
i++;
Column f = tbean.beanDefine.columns.get(n);
String c = f.desc.isEmpty() ? "" : ", " + f.desc;
if (i < cnt) {
sb.append("\n \"").append(lower1(n)).append("\", -- ").append(f.type).append(c);
} else {
sb.append("\n \"").append(lower1(n)).append("\" -- ").append(f.type).append(c);
}
}
return sb.toString();
}
private int findFieldIdx(TBean tbean, String fieldName) {
int i = 0;
for (String s : tbean.columns.keySet()) {
i++;
if (s.equals(fieldName)) {
return i;
}
}
throw new RuntimeException("key idx not found " + tbean.name + ", " + fieldName);
}
private String uniqueKeyGetByName(Map<String, Type> keys) {
return "getBy" + keys.keySet().stream().map(Generator::upper1).reduce("", (a, b) -> a + b);
}
private String uniqueKeyMapName(Map<String, Type> keys) {
return keys.keySet().stream().map(Generator::upper1).reduce("", (a, b) -> a + b) + "Map";
}
private String uniqueKeyGetByName(String[] cols) {
if (cols.length == 0) //ref to primary key
return "get";
else
return "getBy" + Stream.of(cols).map(Generator::upper1).reduce("", (a, b) -> a + b);
}
private String refName(SRef sr) {
return (sr.refNullable ? "NullableRef" : "Ref") + upper1(sr.name);
}
private String refName(TForeignKey fk) {
switch (fk.foreignKeyDefine.refType) {
case NORMAL:
return "Ref" + upper1(fk.name);
case NULLABLE:
return "NullableRef" + upper1(fk.name);
default:
return "ListRef" + upper1(fk.name);
}
}
private String fullName(TBean tbean) {
if (tbean.beanDefine.type == Bean.BeanType.Table)
return new Name(pkg, tbean.name).fullName;
else if (tbean.beanDefine.type == Bean.BeanType.Action)
return "Beans." + (((TBean) tbean.parent)).name.toLowerCase() + "." + tbean.name.toLowerCase();
else
return "Beans." + tbean.name.toLowerCase();
}
private String fullName(TTable ttable) {
return fullName(ttable.tbean);
}
}
|
src/configgen/gen/GenLua.java
|
package configgen.gen;
import configgen.define.Bean;
import configgen.define.Column;
import configgen.define.ForeignKey;
import configgen.genjava.IndentPrint;
import configgen.type.*;
import configgen.value.VDb;
import configgen.value.VTable;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GenLua extends Generator {
static void register() {
providers.put("lua", new Provider() {
@Override
public Generator create(Parameter parameter) {
return new GenLua(parameter);
}
@Override
public String usage() {
return "dir:.,pkg:cfg,encoding:UTF-8 add ,own:x if need, cooperate with -gen bin, -gen pack";
}
});
}
private final String dir;
private final String pkg;
private final String encoding;
private final String own;
private VDb value;
public GenLua(Parameter parameter) {
super(parameter);
dir = parameter.get("dir", ".");
pkg = parameter.getNotEmpty("pkg", "cfg");
encoding = parameter.get("encoding", "UTF-8");
own = parameter.get("own", null);
parameter.end();
}
@Override
public void generate(VDb _value) throws IOException {
File dstDir = Paths.get(dir).resolve(pkg.replace('.', '/')).toFile();
value = own != null ? extract(_value, own) : _value;
try (IndentPrint ps = createCode(new File(dstDir, "_beans.lua"), encoding)) {
generate_beans(ps);
}
try (IndentPrint ps = createCode(new File(dstDir, "_cfgs.lua"), encoding)) {
generate_cfgs(ps);
}
try (IndentPrint ps = createCode(new File(dstDir, "_loads.lua"), encoding)) {
generate_loads(ps);
}
for (VTable c : value.vtables.values()) {
Name name = new Name(pkg, c.name);
//try (IndentPrint ps = createCode(dstDir.toPath().resolve(name.path).toFile(), encoding)) {
//generateTable(c.tableType, c, ps);
//}
}
CachedFileOutputStream.keepMetaAndDeleteOtherFiles(dstDir);
}
private static class Name {
final String pkg;
final String className;
final String fullName;
final String path;
Name(String topPkg, String configName) {
String[] seps = configName.split("\\.");
String[] pks = new String[seps.length - 1];
for (int i = 0; i < pks.length; i++)
pks[i] = seps[i].toLowerCase();
className = seps[seps.length - 1].toLowerCase();
if (pks.length == 0)
pkg = topPkg;
else
pkg = topPkg + "." + String.join(".", pks);
if (pkg.isEmpty())
fullName = className;
else
fullName = pkg + "." + className;
if (pks.length == 0)
path = className + ".lua";
else
path = String.join("/", pks) + "/" + className + ".lua";
}
}
private void generate_beans(IndentPrint ps) {
ps.println("local %s = require \"%s._cfgs\"", pkg, pkg);
ps.println();
ps.println("local Beans = {}");
ps.println("%s._beans = Beans", pkg);
ps.println();
ps.println("local bean = %s._mk.bean", pkg);
ps.println("local tbean = %s._mk.tbean", pkg);
ps.println();
for (TBean tbean : value.dbType.tbeans.values()) {
if (tbean.beanDefine.type == Bean.BeanType.BaseAction) {
ps.println("%s = {}", fullName(tbean));
for (TBean actionBean : tbean.actionBeans.values()) {
ps.println("%s = tbean(\"%s\", %s, %s\n )", fullName(actionBean), actionBean.name, getLuaRefsString(actionBean), getLuaFieldsString(actionBean));
}
} else {
ps.println("%s = bean(%s, %s\n )", fullName(tbean), getLuaRefsString(tbean), getLuaFieldsString(tbean));
}
}
ps.println();
ps.println("return Beans");
}
private void generate_cfgs(IndentPrint ps) {
ps.println("local %s = {}", pkg);
ps.println("%s._mk = require \"common.mkcfg\"", pkg);
Set<String> context = new HashSet<>();
context.add(pkg);
for (TTable c : value.dbType.ttables.values()) {
String name = fullName(c);
define(name, ps, context);
context.add(name);
}
ps.println();
ps.println("return %s", pkg);
}
private void generate_loads(IndentPrint ps) {
ps.println("local require = require");
ps.println();
for (TTable c : value.dbType.ttables.values()) {
ps.println("require \"%s\"", fullName(c));
}
ps.println();
}
private void define(String beanName, IndentPrint ps, Set<String> context) {
List<String> seps = Arrays.asList(beanName.split("\\."));
for (int i = 0; i < seps.size(); i++) {
String pkg = String.join(".", seps.subList(0, i + 1));
if (context.add(pkg)) {
ps.println(pkg + " = {}");
}
}
}
// uniqkeys : {{allname=, getname=, keyidx1=, keyidx2=}, }
private String getLuaUniqKeysString(TTable ttable) {
StringBuilder sb = new StringBuilder();
sb.append("{ ");
sb.append(getOneUniqKeyString(ttable, ttable.primaryKey, true));
for (Map<String, Type> uniqueKey : ttable.uniqueKeys) {
sb.append(getOneUniqKeyString(ttable, uniqueKey, false));
}
sb.append("}");
return sb.toString();
}
private String getOneUniqKeyString(TTable ttable, Map<String, Type> keys, boolean isPrimaryKey) {
String allname = isPrimaryKey ? "all" : uniqueKeyMapName(keys);
String getname = isPrimaryKey ? "get" : uniqueKeyGetByName(keys);
Iterator<String> it = keys.keySet().iterator();
String key1 = it.next();
int keyidx1 = getKeyIdx(ttable.tbean, key1);
boolean hasKeyIdx2 = false;
int keyidx2 = 0;
if (keys.size() > 1) {
if (keys.size() != 2) {
throw new RuntimeException("uniqkeys size != 2 " + ttable.name);
}
String key2 = it.next();
hasKeyIdx2 = true;
keyidx2 = getKeyIdx(ttable.tbean, key2);
}
if (hasKeyIdx2) {
return String.format("{ allname = \"%s\", getname = \"%s\", keyidx1 = %d, keyidx2 = %d }, ", allname, getname, keyidx1, keyidx2);
} else {
return String.format("{ allname = \"%s\", getname = \"%s\", keyidx1 = %d }, ", allname, getname, keyidx1);
}
}
private String uniqueKeyGetByName(Map<String, Type> keys) {
return "getBy" + keys.keySet().stream().map(Generator::upper1).reduce("", (a, b) -> a + b);
}
private String uniqueKeyMapName(Map<String, Type> keys) {
return keys.keySet().stream().map(Generator::upper1).reduce("", (a, b) -> a + b) + "Map";
}
private String uniqueKeyGetByName(String[] cols) {
if (cols.length == 0) //ref to primary key
return "get";
else
return "getBy" + Stream.of(cols).map(Generator::upper1).reduce("", (a, b) -> a + b);
}
// refs { {refname=, dsttable=, dstgetname=, keyidx1=, keyidx2=}, }
private String getLuaRefsString(TBean tbean) {
StringBuilder sb = new StringBuilder();
boolean hasRef = false;
sb.append("{ ");
int i = 0;
for (Type t : tbean.columns.values()) {
i++;
for (SRef r : t.constraint.references) {
String refname = refName(r);
String dsttable = fullName(r.refTable);
String dstgetname = uniqueKeyGetByName(r.refCols);
sb.append(String.format("{ refname = \"%s\", dsttable = %s, dstgetname = \"%s\", keyidx1 = %d }, ", refname, dsttable, dstgetname, i));
hasRef = true;
}
}
for (TForeignKey mRef : tbean.mRefs) {
String refname = refName(mRef);
String dsttable = fullName(mRef.refTable);
String dstgetname = uniqueKeyGetByName(mRef.foreignKeyDefine.ref.cols);
int keyidx1 = getKeyIdx(tbean, mRef.foreignKeyDefine.keys[0]);
boolean hasKeyIdx2 = false;
int keyidx2 = 0;
if (mRef.foreignKeyDefine.keys.length > 1) {
if (mRef.foreignKeyDefine.keys.length != 2) {
throw new RuntimeException("keys length != 2 " + tbean.name);
}
hasKeyIdx2 = true;
keyidx2 = getKeyIdx(tbean, mRef.foreignKeyDefine.keys[1]);
}
if (hasKeyIdx2) {
sb.append(String.format("{ refname = \"%s\", dsttable = %s, dstgetname = \"%s\", keyidx1 = %d, keyidx2 = %d }, ", refname, dsttable, dstgetname, keyidx1, keyidx2));
} else {
sb.append(String.format("{ refname = \"%s\", dsttable = %s, dstgetname = \"%s\", keyidx1 = %d }, ", refname, dsttable, dstgetname, keyidx1));
}
hasRef = true;
}
sb.append("}");
//忽略ListRef
if (hasRef) {
return sb.toString();
} else {
return "nil";
}
}
private int getKeyIdx(TBean tbean, String fieldName) {
int i = 0;
for (String s : tbean.columns.keySet()) {
i++;
if (s.equals(fieldName)) {
return i;
}
}
throw new RuntimeException("key idx not found " + tbean.name + ", " + fieldName);
}
private String getLuaFieldsString(TBean tbean) {
StringBuilder sb = new StringBuilder();
int cnt = tbean.columns.size();
int i = 0;
for (String n : tbean.columns.keySet()) {
i++;
Column f = tbean.beanDefine.columns.get(n);
String c = f.desc.isEmpty() ? "" : ", " + f.desc;
if (i < cnt) {
sb.append("\n \"").append(lower1(n)).append("\", -- ").append(f.type).append(c);
}else{
sb.append("\n \"").append(lower1(n)).append("\" -- ").append(f.type).append(c);
}
}
return sb.toString();
}
private void generateMapGetBy(Map<String, Type> keys, String className, IndentPrint ps, boolean isPrimaryKey) {
String mapName = isPrimaryKey ? "all" : uniqueKeyMapName(keys);
ps.println(className + "." + mapName + " = {}");
String getByName = isPrimaryKey ? "get" : uniqueKeyGetByName(keys);
ps.println("function " + className + "." + getByName + "(" + formalParams(keys) + ")");
ps.println1("return " + className + "." + mapName + "[" + actualParams(keys, "") + "]");
ps.println("end");
ps.println();
}
private void generateCreateAndAssign(TBean tbean, IndentPrint ps, String fullName) {
ps.println("function " + fullName + ":_create(os)");
ps.println1("local o = {}");
ps.println1("setmetatable(o, self)");
ps.println1("self.__index = self");
tbean.columns.forEach((n, t) -> {
Column f = tbean.beanDefine.columns.get(n);
String c = f.desc.isEmpty() ? "" : " -- " + f.desc;
if (t instanceof TList) {
ps.println1("o." + lower1(n) + " = {}" + c);
ps.println1("for _ = 1, os:ReadSize() do");
ps.println2("table.insert(o." + lower1(n) + ", " + _create(((TList) t).value) + ")");
ps.println1("end");
} else if (t instanceof TMap) {
ps.println1("o." + lower1(n) + " = {}" + c);
ps.println1("for _ = 1, os:ReadSize() do");
ps.println2("o." + lower1(n) + "[" + _create(((TMap) t).key) + "] = " + _create(((TMap) t).value));
ps.println1("end");
} else {
ps.println1("o." + lower1(n) + " = " + _create(t) + c);
}
t.constraint.references.forEach(r -> ps.println1("o." + refName(r) + " = nil"));
});
tbean.mRefs.forEach(m -> ps.println1("o." + refName(m) + " = nil"));
tbean.listRefs.forEach(l -> ps.println1("o." + refName(l) + " = {}"));
ps.println1("return o");
ps.println("end");
ps.println();
ps.println();
}
private void generateTable(TTable ttable, VTable vtable, IndentPrint ps) {
String className = new Name(pkg, ttable.name).className;
if (ttable.tbean.hasSubBean()) {
ps.println("local Beans = require(\"" + pkg + "._beans\")");
ps.println();
}
ps.println("local " + className + " = {}");
vtable.enumNames.forEach(e -> ps.println(className + "." + e + " = nil"));
ps.println();
generateCreateAndAssign(ttable.tbean, ps, className);
//static get
generateMapGetBy(ttable.primaryKey, className, ps, true);
for (Map<String, Type> uniqueKey : ttable.uniqueKeys) {
generateMapGetBy(uniqueKey, className, ps, false);
}
//static _initialize
ps.println("function " + className + "._initialize(os, errors)");
ps.println1("for _ = 1, os:ReadSize() do");
ps.println2("local v = " + className + ":_create(os)");
if (ttable.tableDefine.isEnum()) {
ps.println2("if #(v." + lower1(ttable.tableDefine.enumStr) + ") > 0 then");
ps.println3(className + "[v." + lower1(ttable.tableDefine.enumStr) + "] = v");
ps.println2("end");
}
generateAllMapPut(ttable, className, ps);
ps.println1("end");
if (ttable.tableDefine.isEnum()) {
vtable.enumNames.forEach(e -> {
ps.println1("if " + className + "." + e + " == nil then");
ps.println2("errors.enumNil(\"" + ttable.tbean.beanDefine.name + "\", \"" + e + "\");");
ps.println1("end");
});
}
ps.println("end");
ps.println();
ps.println("return " + className);
}
private void generateAllMapPut(TTable ttable, String className, IndentPrint ps) {
generateMapPut(ttable.primaryKey, className, ps, true);
for (Map<String, Type> uniqueKey : ttable.uniqueKeys) {
generateMapPut(uniqueKey, className, ps, false);
}
}
private void generateMapPut(Map<String, Type> keys, String className, IndentPrint ps, boolean isPrimaryKey) {
String mapName = isPrimaryKey ? "all" : uniqueKeyMapName(keys);
ps.println2(className + "." + mapName + "[" + actualParams(keys, "v.") + "] = v");
}
private String formalParams(Map<String, Type> fs) {
return String.join(", ", fs.keySet().stream().map(Generator::lower1).collect(Collectors.toList()));
}
private String actualParams(Map<String, Type> keys, String prefix) {
return String.join(" ..\",\".. ", keys.entrySet().stream().map(e ->
e.getValue() instanceof TBool ? "(" + prefix + lower1(e.getKey()) + " and 1 or 0)" : prefix + lower1(e.getKey())
).collect(Collectors.toList()));
}
private String actualParams(String[] keys, String prefix) {
return String.join(", ", Arrays.asList(keys).stream().map(n -> prefix + lower1(n)).collect(Collectors.toList()));
}
private String refName(SRef sr) {
return (sr.refNullable ? "NullableRef" : "Ref") + upper1(sr.name);
}
private String refName(TForeignKey fk) {
switch (fk.foreignKeyDefine.refType) {
case NORMAL:
return "Ref" + upper1(fk.name);
case NULLABLE:
return "NullableRef" + upper1(fk.name);
default:
return "ListRef" + upper1(fk.name);
}
}
private String fullName(TBean tbean) {
if (tbean.beanDefine.type == Bean.BeanType.Table)
return new Name(pkg, tbean.name).fullName;
else if (tbean.beanDefine.type == Bean.BeanType.Action)
return "Beans." + (((TBean) tbean.parent)).name.toLowerCase() + "." + tbean.name.toLowerCase();
else
return "Beans." + tbean.name.toLowerCase();
}
private String fullName(TTable ttable) {
return fullName(ttable.tbean);
}
private String _create(Type t) {
return t.accept(new TypeVisitorT<String>() {
@Override
public String visit(TBool type) {
return "os:ReadBool()";
}
@Override
public String visit(TInt type) {
return "os:ReadInt32()";
}
@Override
public String visit(TLong type) {
return "os:ReadInt64()";
}
@Override
public String visit(TFloat type) {
return "os:ReadSingle()";
}
@Override
public String visit(TString type) {
return type.subtype == TString.Subtype.STRING ? "os:ReadString()" : "os:ReadText()";
}
@Override
public String visit(TList type) {
return null;
}
@Override
public String visit(TMap type) {
return null;
}
@Override
public String visit(TBean type) {
return fullName(type) + ":_create(os)";
}
});
}
}
|
lua生成修改,结构和数据都放到lua里
|
src/configgen/gen/GenLua.java
|
lua生成修改,结构和数据都放到lua里
|
|
Java
|
mit
|
f65ca069297a60973a52f4325803181ca747157b
| 0
|
MathSquared/ResultsWizard2
|
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/**
* Obtains connection details from a user for connecting to a local or remote computer. If remote, also obtains a corresponding {@link Socket}.
*
* <p>
* The user's selection is returned by the {@link #call()} method, which sets the visibility of this frame and blocks until the user makes a valid selection.
*
* @author MathSquared
*
*/
public class ConnectionDetailsFrame extends JFrame implements Callable<Socket> {
private JPanel contentPane;
private JTextField portField;
private JTextField ipAddrField;
private final ButtonGroup localOrRemoteGroup = new ButtonGroup();
private boolean finished = false;
private Socket output = null;
/**
* Create the frame.
*/
public ConnectionDetailsFrame () {
setTitle("Connection Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblHeader = new JLabel("Please specify the location of the component you wish to connect to:");
contentPane.add(lblHeader, BorderLayout.NORTH);
Component selectLocationHorizontalStrut = Box.createHorizontalStrut(10);
contentPane.add(selectLocationHorizontalStrut, BorderLayout.WEST);
JPanel selectLocationPanel = new JPanel();
contentPane.add(selectLocationPanel, BorderLayout.CENTER);
selectLocationPanel.setLayout(new BoxLayout(selectLocationPanel, BoxLayout.Y_AXIS));
Component selectLocationVerticalStrut = Box.createVerticalStrut(10);
selectLocationPanel.add(selectLocationVerticalStrut);
JRadioButton rdbtnLocal = new JRadioButton("Local (this computer)");
localOrRemoteGroup.add(rdbtnLocal);
selectLocationPanel.add(rdbtnLocal);
final JRadioButton rdbtnRemote = new JRadioButton("Remote (another computer)");
rdbtnRemote.setSelected(true);
localOrRemoteGroup.add(rdbtnRemote);
selectLocationPanel.add(rdbtnRemote);
JPanel detailAndSubmitPanel = new JPanel();
contentPane.add(detailAndSubmitPanel, BorderLayout.SOUTH);
detailAndSubmitPanel.setLayout(new BorderLayout(0, 0));
final JPanel detailPanel = new JPanel();
detailAndSubmitPanel.add(detailPanel, BorderLayout.NORTH);
detailPanel.setLayout(new CardLayout(0, 0));
JPanel localPanel = new JPanel();
detailPanel.add(localPanel, "localCard");
JLabel lblLocalDescriptor = new JLabel("<html><body style='width:300px;text-align:center;'>This component will connect to another component running on this computer.</body></html>");
lblLocalDescriptor.setHorizontalAlignment(SwingConstants.CENTER);
localPanel.add(lblLocalDescriptor);
JPanel remotePanel = new JPanel();
detailPanel.add(remotePanel, "remoteCard");
((CardLayout) detailPanel.getLayout()).show(detailPanel, "remoteCard");
remotePanel.setLayout(new BorderLayout(0, 0));
JLabel lblRemoteHeader = new JLabel("Please specify the connection details below:");
remotePanel.add(lblRemoteHeader, BorderLayout.NORTH);
Component connectionDetailsHorizontalStrut = Box.createHorizontalStrut(10);
remotePanel.add(connectionDetailsHorizontalStrut, BorderLayout.WEST);
JPanel connectionDetailsPanel = new JPanel();
remotePanel.add(connectionDetailsPanel, BorderLayout.CENTER);
GridBagLayout gbl_connectionDetailsPanel = new GridBagLayout();
gbl_connectionDetailsPanel.columnWidths = new int[] {0, 0, 0, 0};
gbl_connectionDetailsPanel.rowHeights = new int[] {0, 0, 0, 0};
gbl_connectionDetailsPanel.columnWeights = new double[] {0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_connectionDetailsPanel.rowWeights = new double[] {0.0, 0.0, 0.0, Double.MIN_VALUE};
connectionDetailsPanel.setLayout(gbl_connectionDetailsPanel);
Component connectionDetailsVerticalStrut = Box.createVerticalStrut(10);
GridBagConstraints gbc_connectionDetailsVerticalStrut = new GridBagConstraints();
gbc_connectionDetailsVerticalStrut.insets = new Insets(0, 0, 5, 5);
gbc_connectionDetailsVerticalStrut.gridx = 0;
gbc_connectionDetailsVerticalStrut.gridy = 0;
connectionDetailsPanel.add(connectionDetailsVerticalStrut, gbc_connectionDetailsVerticalStrut);
JLabel lblIpAddress = new JLabel("IP address:");
GridBagConstraints gbc_lblIpAddress = new GridBagConstraints();
gbc_lblIpAddress.anchor = GridBagConstraints.WEST;
gbc_lblIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblIpAddress.gridx = 0;
gbc_lblIpAddress.gridy = 1;
connectionDetailsPanel.add(lblIpAddress, gbc_lblIpAddress);
Component connectionDetailsGridHorizontalStrut = Box.createHorizontalStrut(10);
GridBagConstraints gbc_connectionDetailsGridHorizontalStrut = new GridBagConstraints();
gbc_connectionDetailsGridHorizontalStrut.insets = new Insets(0, 0, 5, 5);
gbc_connectionDetailsGridHorizontalStrut.gridx = 1;
gbc_connectionDetailsGridHorizontalStrut.gridy = 1;
connectionDetailsPanel.add(connectionDetailsGridHorizontalStrut, gbc_connectionDetailsGridHorizontalStrut);
ipAddrField = new JTextField();
ipAddrField.setHorizontalAlignment(SwingConstants.CENTER);
ipAddrField.setText("127.0.0.1");
GridBagConstraints gbc_ipAddrField = new GridBagConstraints();
gbc_ipAddrField.anchor = GridBagConstraints.WEST;
gbc_ipAddrField.insets = new Insets(0, 0, 5, 0);
gbc_ipAddrField.gridx = 2;
gbc_ipAddrField.gridy = 1;
connectionDetailsPanel.add(ipAddrField, gbc_ipAddrField);
ipAddrField.setColumns(10);
JLabel lblPort = new JLabel("Port:");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.insets = new Insets(0, 0, 0, 5);
gbc_lblPort.anchor = GridBagConstraints.WEST;
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 2;
connectionDetailsPanel.add(lblPort, gbc_lblPort);
portField = new JTextField();
portField.setHorizontalAlignment(SwingConstants.CENTER);
portField.setText("60845");
GridBagConstraints gbc_portField = new GridBagConstraints();
gbc_portField.anchor = GridBagConstraints.WEST;
gbc_portField.gridx = 2;
gbc_portField.gridy = 2;
connectionDetailsPanel.add(portField, gbc_portField);
portField.setColumns(5);
Component submitStrut = Box.createVerticalStrut(20);
detailAndSubmitPanel.add(submitStrut, BorderLayout.CENTER);
JButton btnSubmit = new JButton("Submit");
detailAndSubmitPanel.add(btnSubmit, BorderLayout.SOUTH);
// Event listeners to change cards
rdbtnLocal.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
CardLayout layout = (CardLayout) (detailPanel.getLayout());
layout.show(detailPanel, "localCard");
}
});
rdbtnRemote.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
CardLayout layout = (CardLayout) (detailPanel.getLayout());
layout.show(detailPanel, "remoteCard");
}
});
// Event listener for Submit button
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
boolean whetherToClose = false; // don't close if an error occurs
// Clean up (if local, output remains null)
if (rdbtnRemote.isSelected()) {
try {
output = new Socket(InetAddress.getByName(ipAddrField.getText()), Integer.parseInt(portField.getText()));
whetherToClose = true;
} catch (IllegalArgumentException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "Error: Invalid port " + portField.getText() + "; must be a number between 0 and 65535");
} catch (UnknownHostException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "Error: unable to connect to " + ipAddrField.getText() + "; host unknown");
} catch (IOException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "An I/O error occurred: " + e1.getMessage());
}
} else { // local
output = null;
whetherToClose = true;
}
if (whetherToClose) {
ConnectionDetailsFrame.this.setVisible(false);
finished = true;
}
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent e) {
finished = true;
}
});
// Center on screen
setLocationRelativeTo(null);
}
/**
* Returns a <code>Socket</code> connected to the user-specified IP/host and port.
*
* @return a {@link Socket} as specified by the user, or null if the connection was specified as local or the user closed the window other than by activating the Submit button
*/
public Socket call () {
setVisible(true);
while (!finished);
return output;
}
}
|
ResultsWizard2/src/mathsquared/resultswizard2/ConnectionDetailsFrame.java
|
package mathsquared.resultswizard2;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/**
* Obtains connection details from a user for connecting to a local or remote computer. If remote, also obtains a corresponding {@link Socket}.
*
* <p>
* The user's selection is returned by the {@link #call()} method, which sets the visibility of this frame and blocks until the user makes a valid selection.
*
* @author MathSquared
*
*/
public class ConnectionDetailsFrame extends JFrame implements Callable<Socket> {
private JPanel contentPane;
private JTextField portField;
private JTextField ipAddrField;
private final ButtonGroup localOrRemoteGroup = new ButtonGroup();
private boolean finished = false;
private Socket output = null;
/**
* Create the frame.
*/
public ConnectionDetailsFrame () {
setTitle("Connection Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblHeader = new JLabel("Please specify the location of the component you wish to connect to:");
contentPane.add(lblHeader, BorderLayout.NORTH);
Component selectLocationHorizontalStrut = Box.createHorizontalStrut(10);
contentPane.add(selectLocationHorizontalStrut, BorderLayout.WEST);
JPanel selectLocationPanel = new JPanel();
contentPane.add(selectLocationPanel, BorderLayout.CENTER);
selectLocationPanel.setLayout(new BoxLayout(selectLocationPanel, BoxLayout.Y_AXIS));
Component selectLocationVerticalStrut = Box.createVerticalStrut(10);
selectLocationPanel.add(selectLocationVerticalStrut);
JRadioButton rdbtnLocal = new JRadioButton("Local (this computer)");
rdbtnLocal.setSelected(true);
localOrRemoteGroup.add(rdbtnLocal);
selectLocationPanel.add(rdbtnLocal);
final JRadioButton rdbtnRemote = new JRadioButton("Remote (another computer)");
localOrRemoteGroup.add(rdbtnRemote);
selectLocationPanel.add(rdbtnRemote);
JPanel detailAndSubmitPanel = new JPanel();
contentPane.add(detailAndSubmitPanel, BorderLayout.SOUTH);
detailAndSubmitPanel.setLayout(new BorderLayout(0, 0));
final JPanel detailPanel = new JPanel();
detailAndSubmitPanel.add(detailPanel, BorderLayout.NORTH);
detailPanel.setLayout(new CardLayout(0, 0));
JPanel localPanel = new JPanel();
detailPanel.add(localPanel, "localCard");
JLabel lblLocalDescriptor = new JLabel("<html><body style='width:300px;text-align:center;'>This component will connect to another component running on this computer.</body></html>");
lblLocalDescriptor.setHorizontalAlignment(SwingConstants.CENTER);
localPanel.add(lblLocalDescriptor);
JPanel remotePanel = new JPanel();
detailPanel.add(remotePanel, "remoteCard");
remotePanel.setLayout(new BorderLayout(0, 0));
JLabel lblRemoteHeader = new JLabel("Please specify the connection details below:");
remotePanel.add(lblRemoteHeader, BorderLayout.NORTH);
Component connectionDetailsHorizontalStrut = Box.createHorizontalStrut(10);
remotePanel.add(connectionDetailsHorizontalStrut, BorderLayout.WEST);
JPanel connectionDetailsPanel = new JPanel();
remotePanel.add(connectionDetailsPanel, BorderLayout.CENTER);
GridBagLayout gbl_connectionDetailsPanel = new GridBagLayout();
gbl_connectionDetailsPanel.columnWidths = new int[] {0, 0, 0, 0};
gbl_connectionDetailsPanel.rowHeights = new int[] {0, 0, 0, 0};
gbl_connectionDetailsPanel.columnWeights = new double[] {0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_connectionDetailsPanel.rowWeights = new double[] {0.0, 0.0, 0.0, Double.MIN_VALUE};
connectionDetailsPanel.setLayout(gbl_connectionDetailsPanel);
Component connectionDetailsVerticalStrut = Box.createVerticalStrut(10);
GridBagConstraints gbc_connectionDetailsVerticalStrut = new GridBagConstraints();
gbc_connectionDetailsVerticalStrut.insets = new Insets(0, 0, 5, 5);
gbc_connectionDetailsVerticalStrut.gridx = 0;
gbc_connectionDetailsVerticalStrut.gridy = 0;
connectionDetailsPanel.add(connectionDetailsVerticalStrut, gbc_connectionDetailsVerticalStrut);
JLabel lblIpAddress = new JLabel("IP address:");
GridBagConstraints gbc_lblIpAddress = new GridBagConstraints();
gbc_lblIpAddress.anchor = GridBagConstraints.WEST;
gbc_lblIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblIpAddress.gridx = 0;
gbc_lblIpAddress.gridy = 1;
connectionDetailsPanel.add(lblIpAddress, gbc_lblIpAddress);
Component connectionDetailsGridHorizontalStrut = Box.createHorizontalStrut(10);
GridBagConstraints gbc_connectionDetailsGridHorizontalStrut = new GridBagConstraints();
gbc_connectionDetailsGridHorizontalStrut.insets = new Insets(0, 0, 5, 5);
gbc_connectionDetailsGridHorizontalStrut.gridx = 1;
gbc_connectionDetailsGridHorizontalStrut.gridy = 1;
connectionDetailsPanel.add(connectionDetailsGridHorizontalStrut, gbc_connectionDetailsGridHorizontalStrut);
ipAddrField = new JTextField();
ipAddrField.setHorizontalAlignment(SwingConstants.CENTER);
ipAddrField.setText("127.0.0.1");
GridBagConstraints gbc_ipAddrField = new GridBagConstraints();
gbc_ipAddrField.anchor = GridBagConstraints.WEST;
gbc_ipAddrField.insets = new Insets(0, 0, 5, 0);
gbc_ipAddrField.gridx = 2;
gbc_ipAddrField.gridy = 1;
connectionDetailsPanel.add(ipAddrField, gbc_ipAddrField);
ipAddrField.setColumns(10);
JLabel lblPort = new JLabel("Port:");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.insets = new Insets(0, 0, 0, 5);
gbc_lblPort.anchor = GridBagConstraints.WEST;
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 2;
connectionDetailsPanel.add(lblPort, gbc_lblPort);
portField = new JTextField();
portField.setHorizontalAlignment(SwingConstants.CENTER);
portField.setText("60845");
GridBagConstraints gbc_portField = new GridBagConstraints();
gbc_portField.anchor = GridBagConstraints.WEST;
gbc_portField.gridx = 2;
gbc_portField.gridy = 2;
connectionDetailsPanel.add(portField, gbc_portField);
portField.setColumns(5);
Component submitStrut = Box.createVerticalStrut(20);
detailAndSubmitPanel.add(submitStrut, BorderLayout.CENTER);
JButton btnSubmit = new JButton("Submit");
detailAndSubmitPanel.add(btnSubmit, BorderLayout.SOUTH);
// Event listeners to change cards
rdbtnLocal.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
CardLayout layout = (CardLayout) (detailPanel.getLayout());
layout.show(detailPanel, "localCard");
}
});
rdbtnRemote.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
CardLayout layout = (CardLayout) (detailPanel.getLayout());
layout.show(detailPanel, "remoteCard");
}
});
// Event listener for Submit button
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
boolean whetherToClose = false; // don't close if an error occurs
// Clean up (if local, output remains null)
if (rdbtnRemote.isSelected()) {
try {
output = new Socket(InetAddress.getByName(ipAddrField.getText()), Integer.parseInt(portField.getText()));
whetherToClose = true;
} catch (IllegalArgumentException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "Error: Invalid port " + portField.getText() + "; must be a number between 0 and 65535");
} catch (UnknownHostException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "Error: unable to connect to " + ipAddrField.getText() + "; host unknown");
} catch (IOException e1) {
JOptionPane.showMessageDialog(ConnectionDetailsFrame.this, "An I/O error occurred: " + e1.getMessage());
}
} else { // local
output = null;
whetherToClose = true;
}
if (whetherToClose) {
ConnectionDetailsFrame.this.setVisible(false);
finished = true;
}
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent e) {
finished = true;
}
});
// Center on screen
setLocationRelativeTo(null);
}
/**
* Returns a <code>Socket</code> connected to the user-specified IP/host and port.
*
* @return a {@link Socket} as specified by the user, or null if the connection was specified as local or the user closed the window other than by activating the Submit button
*/
public Socket call () {
setVisible(true);
while (!finished);
return output;
}
}
|
ConnectionDetailsFrame now specifies a remote connection by default
|
ResultsWizard2/src/mathsquared/resultswizard2/ConnectionDetailsFrame.java
|
ConnectionDetailsFrame now specifies a remote connection by default
|
|
Java
|
mit
|
b7edb30e4833fdc1a1037d6f8216eb9298325350
| 0
|
ashleypackard/compiler-design-project
|
import java.io.IOException;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
public class Main {
public static void main(String[] args) throws IOException {
PL0Lexer lexer = new PL0Lexer(new ANTLRFileStream("sample2.pl0"));
CommonTokenStream tokens = new CommonTokenStream(lexer);
PL0Parser parser = new PL0Parser(tokens);
ParseTree tree = parser.program(); // String representation of tree starting from root node
// Interpreter
PL0Interpreter interpreter = new PL0Interpreter();
interpreter.visit(tree);
// C++ Compiler
//PL0CppCompiler compiler = new PL0CppCompiler();
//compiler.visit(tree);
// Java Compiler
//PL0JavaCompiler javaCompiler = new PL0JavaCompiler();
//javaCompiler.visit(tree);
}
}
|
target/generated-sources/antlr4/Main.java
|
import java.io.IOException;
import org.antlr.v4.runtime.ANTLRFileStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
public class Main {
public static void main(String[] args) throws IOException {
PL0Lexer lexer = new PL0Lexer(new ANTLRFileStream("sample2.pl0"));
CommonTokenStream tokens = new CommonTokenStream(lexer);
PL0Parser parser = new PL0Parser(tokens);
ParseTree tree = parser.program(); // String representation of tree starting from root node
// Interpreter
//PL0Interpreter interpreter = new PL0Interpreter();
//interpreter.visit(tree);
// C++ Compiler
PL0CppCompiler compiler = new PL0CppCompiler();
compiler.visit(tree);
// Java Compiler
PL0JavaCompiler javaCompiler = new PL0JavaCompiler();
javaCompiler.visit(tree);
}
}
|
Fixed tabs/spaces formatting in main
|
target/generated-sources/antlr4/Main.java
|
Fixed tabs/spaces formatting in main
|
|
Java
|
agpl-3.0
|
eea3f28a72139c95d80840875b7cff4e1310e44e
| 0
|
geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt2
|
/*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.print.component.impl;
import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
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 javax.imageio.ImageIO;
import javax.media.jai.ImageLayout;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.operator.MosaicDescriptor;
import javax.media.jai.operator.TranslateDescriptor;
import org.geomajas.configuration.client.ClientMapInfo;
import org.geomajas.geometry.Bbox;
import org.geomajas.global.GeomajasException;
import org.geomajas.layer.RasterLayer;
import org.geomajas.layer.RasterLayerService;
import org.geomajas.layer.common.proxy.LayerHttpService;
import org.geomajas.layer.tile.RasterTile;
import org.geomajas.plugin.print.component.LayoutConstraint;
import org.geomajas.plugin.print.component.PdfContext;
import org.geomajas.plugin.print.component.PrintComponentVisitor;
import org.geomajas.plugin.print.component.dto.RasterLayerComponentInfo;
import org.geomajas.plugin.print.component.service.PrintConfigurationService;
import org.geomajas.service.ConfigurationService;
import org.geomajas.service.DispatcherUrlService;
import org.geomajas.service.GeoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.vividsolutions.jts.geom.Envelope;
/**
* Sub component of a map responsible for rendering raster layer.
*
* @author Jan De Moerloose
*/
@Component()
@Scope(value = "prototype")
public class RasterLayerComponentImpl extends BaseLayerComponentImpl<RasterLayerComponentInfo> {
protected static final int DOWNLOAD_MAX_ATTEMPTS = 2;
protected static final int DOWNLOAD_MAX_THREADS = 5;
protected static final long DOWNLOAD_TIMEOUT = 120000; // millis
protected static final long DOWNLOAD_TIMEOUT_ONE_TILE = 100; // millis
protected static final Font ERROR_FONT = new Font("SansSerif", Font.PLAIN, 6); //$NON-NLS-1$
private static final String BUNDLE_NAME = "org/geomajas/extension/print/rasterlayercomponent"; //$NON-NLS-1$
// do not make this static, different requests might need different bundles
@XStreamOmitField
private final ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
/** The calculated bounds. */
@XStreamOmitField
protected Envelope bbox;
/** List of the tile images. */
@XStreamOmitField
protected List<RasterTile> tiles;
/** The raster scale, may be different from map ppunit. */
@XStreamOmitField
protected double rasterScale;
@XStreamOmitField
private final Logger log = LoggerFactory.getLogger(RasterLayerComponentImpl.class);
@Autowired
@XStreamOmitField
private RasterLayerService rasterLayerService;
@Autowired
@XStreamOmitField
private PrintConfigurationService printConfigurationService;
@Autowired
@XStreamOmitField
private ConfigurationService configurationService;
@Autowired
@XStreamOmitField
private GeoService geoService;
@Autowired
@XStreamOmitField
private DispatcherUrlService dispatcherUrlService;
@Autowired
private LayerHttpService layerHttpService;
private float opacity = 1.0f;
/** Constructor. */
public RasterLayerComponentImpl() {
getConstraint().setAlignmentX(LayoutConstraint.JUSTIFIED);
getConstraint().setAlignmentY(LayoutConstraint.JUSTIFIED);
}
/**
* Call back visitor.
*
* @param visitor
* visitor
*/
public void accept(PrintComponentVisitor visitor) {
}
@Override
public void render(PdfContext context) {
if (isVisible()) {
rasterScale = getMap().getPpUnit() * getMap().getRasterResolution() / 72;
bbox = createBbox();
if (log.isDebugEnabled()) {
log.debug("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "]");
}
ClientMapInfo map = printConfigurationService.getMapInfo(getMap().getMapId(), getMap().getApplicationId());
try {
tiles = rasterLayerService.getTiles(getLayerId(), geoService.getCrs2(map.getCrs()), bbox, rasterScale);
if (tiles.size() > 0) {
Collection<Callable<ImageResult>> callables = new ArrayList<Callable<ImageResult>>(tiles.size());
// Build the image downloading threads
for (RasterTile tile : tiles) {
RasterImageDownloadCallable downloadThread = new RasterImageDownloadCallable(
DOWNLOAD_MAX_ATTEMPTS, tile);
callables.add(downloadThread);
}
// Loop until all images are downloaded or timeout is reached
long totalTimeout = DOWNLOAD_TIMEOUT + DOWNLOAD_TIMEOUT_ONE_TILE * tiles.size();
log.debug("=== total timeout (millis): {}", totalTimeout);
ExecutorService service = Executors.newFixedThreadPool(DOWNLOAD_MAX_THREADS);
List<Future<ImageResult>> futures = service.invokeAll(callables, totalTimeout,
TimeUnit.MILLISECONDS);
// determine the pixel bounds of the mosaic
Bbox pixelBounds = getPixelBounds(tiles);
int imageWidth = printConfigurationService.getRasterLayerInfo(getLayerId()).getTileWidth();
int imageHeight = printConfigurationService.getRasterLayerInfo(getLayerId()).getTileHeight();
// create the images for the mosaic
List<RenderedImage> images = new ArrayList<RenderedImage>();
for (Future<ImageResult> future : futures) {
if (future.isDone()) {
try {
ImageResult result;
result = future.get();
// create a rendered image
RenderedImage image = JAI.create("stream",
new ByteArraySeekableStream(result.getImage()));
// convert to common direct colormodel (some images have their own indexed color model)
// Sprint-51 If the image source is not available the java.awt.image will throw
// a runtime error causing the printing to fail. If this happens handle the error
// and and allow the print process to continue.
// convert to common direct colormodel (some images have their own indexed color model)
RenderedImage colored = null;
try {
colored = toDirectColorModel(image);
} catch (Exception e) {
String msg = getLayerId() + " returned a null image.";
msg += " The print plugin will not render this layer";
log.error(msg, e);
continue;
}
// translate to the correct position in the tile grid
double xOffset = result.getRasterImage().getCode().getX() * imageWidth
- pixelBounds.getX();
double yOffset = 0;
// TODO: in some cases, the y-index is up (e.g. WMS), should be down for
// all layers !!!!
if (isYIndexUp(tiles)) {
yOffset = result.getRasterImage().getCode().getY() * imageHeight
- pixelBounds.getY();
} else {
yOffset = (float) (pixelBounds.getMaxY() - (result.getRasterImage().getCode()
.getY() + 1)
* imageHeight);
}
log.debug("adding to(" + xOffset + "," + yOffset + "), url = "
+ result.getRasterImage().getUrl());
RenderedImage translated = TranslateDescriptor.create(colored, (float) xOffset,
(float) yOffset, new InterpolationNearest(), null);
images.add(translated);
} catch (ExecutionException e) {
addLoadError(context, (ImageException) (e.getCause()));
} catch (InterruptedException e) {
log.warn("missing tile in mosaic " + e.getMessage());
} catch (MalformedURLException e) {
log.warn("missing tile in mosaic " + e.getMessage());
} catch (IOException e) {
log.warn("missing tile in mosaic " + e.getMessage());
}
}
}
if (images.size() > 0) {
ImageLayout imageLayout = new ImageLayout(0, 0, (int) pixelBounds.getWidth(),
(int) pixelBounds.getHeight());
imageLayout.setTileWidth(imageWidth);
imageLayout.setTileHeight(imageHeight);
// create the mosaic image
ParameterBlock pbMosaic = new ParameterBlock();
pbMosaic.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY);
for (RenderedImage renderedImage : images) {
pbMosaic.addSource(renderedImage);
}
RenderedOp mosaic = JAI.create("mosaic", pbMosaic, new RenderingHints(JAI.KEY_IMAGE_LAYOUT,
imageLayout));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.debug("rendering to buffer...");
ImageIO.write(mosaic, "png", baos);
log.debug("rendering done, size = " + baos.toByteArray().length);
RasterTile mosaicTile = new RasterTile();
mosaicTile.setBounds(getWorldBounds(tiles));
ImageResult mosaicResult = new ImageResult(mosaicTile);
mosaicResult.setImage(baos.toByteArray());
addImage(context, mosaicResult);
} catch (IOException e) {
log.warn("could not write mosaic image " + e.getMessage());
} catch (BadElementException e) {
log.warn("could not write mosaic image " + e.getMessage());
}
}
}
} catch (GeomajasException e) {
log.warn("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "] failed : " + e.getMessage());
} catch (InterruptedException e) {
log.warn("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "] failed : " + e.getMessage());
}
}
}
private boolean isYIndexUp(List<RasterTile> tiles) {
RasterTile first = tiles.iterator().next();
for (RasterTile tile : tiles) {
if (tile.getCode().getY() > first.getCode().getY()) {
return tile.getBounds().getY() > first.getBounds().getY();
} else if (tile.getCode().getY() < first.getCode().getY()) {
return tile.getBounds().getY() < first.getBounds().getY();
}
}
return false;
}
private Bbox getPixelBounds(List<RasterTile> tiles) {
Bbox bounds = null;
int imageWidth = printConfigurationService.getRasterLayerInfo(getLayerId()).getTileWidth();
int imageHeight = printConfigurationService.getRasterLayerInfo(getLayerId()).getTileHeight();
for (RasterTile tile : tiles) {
Bbox tileBounds = new Bbox(tile.getCode().getX() * imageWidth, tile.getCode().getY() * imageHeight,
imageWidth, imageHeight);
if (bounds == null) {
bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight());
} else {
double minx = Math.min(tileBounds.getX(), bounds.getX());
double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX());
double miny = Math.min(tileBounds.getY(), bounds.getY());
double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY());
bounds = new Bbox(minx, miny, maxx - minx, maxy - miny);
}
}
return bounds;
}
private Bbox getWorldBounds(List<RasterTile> tiles) {
Bbox bounds = null;
for (RasterTile tile : tiles) {
Bbox tileBounds = new Bbox(tile.getBounds().getX(), tile.getBounds().getY(), tile.getBounds().getWidth(),
tile.getBounds().getHeight());
if (bounds == null) {
bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight());
} else {
double minx = Math.min(tileBounds.getX(), bounds.getX());
double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX());
double miny = Math.min(tileBounds.getY(), bounds.getY());
double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY());
bounds = new Bbox(minx, miny, maxx - minx, maxy - miny);
}
}
return bounds;
}
/**
* Get the layer opacity.
*
* @return layer opacity
*/
public float getOpacity() {
return opacity;
}
/**
* Set the layer opacity.
*
* @param opacity
* layer opacity
*/
public void setOpacity(float opacity) {
this.opacity = opacity;
}
@Override
public void fromDto(RasterLayerComponentInfo rasterInfo) {
super.fromDto(rasterInfo);
String style = rasterInfo.getStyle();
if (rasterInfo.getStyle() != null) {
String match = style;
// could be 'opacity:0.5;' or '0.5'
if (style.contains("opacity:")) {
match = style.substring(style.indexOf("opacity:") + 8);
}
if (match.contains(";")) {
match = match.substring(0, match.indexOf(";"));
}
try {
setOpacity(Float.valueOf(match));
} catch (NumberFormatException nfe) {
log.warn("Could not parse opacity " + style + "of raster layer " + getLayerId());
}
}
}
/**
* Add image in the document.
*
* @param context
* PDF context
* @param imageResult
* image
* @throws BadElementException
* PDF construction problem
* @throws IOException
* PDF construction problem
*/
protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {
Bbox imageBounds = imageResult.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lowerleft corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
// opacity
log.debug("before drawImage");
context.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),
getSize(), getOpacity());
log.debug("after drawImage");
}
/**
* Add image with a exception message in the PDF document.
*
* @param context
* PDF context
* @param e
* exception to put in image
*/
protected void addLoadError(PdfContext context, ImageException e) {
Bbox imageBounds = e.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lower left corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding failed message=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
float textHeight = context.getTextSize("failed", ERROR_FONT).getHeight() * 3f;
Rectangle rec = new Rectangle(x, y, x + width, y + height);
context.strokeRectangle(rec, Color.RED, 0.5f);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line1"), ERROR_FONT, new Rectangle(x, y
+ textHeight, x + width, y + height), Color.RED);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line2"), ERROR_FONT, rec, Color.RED);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line3"), ERROR_FONT, new Rectangle(x, y
- textHeight, x + width, y + height), Color.RED);
}
/**
* ???
*/
private class ImageResult {
private byte[] image;
private RasterTile rasterImage;
public ImageResult(RasterTile rasterImage) {
this.rasterImage = rasterImage;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public RasterTile getRasterImage() {
return rasterImage;
}
}
/**
* Image Exception
*/
private class ImageException extends Exception {
private static final long serialVersionUID = 151L;
private final RasterTile rasterImage;
/**
* Constructor.
*
* @param rasterImage
* image for which the exception occurred
* @param cause
* cause exception
*
* */
public ImageException(RasterTile rasterImage, Throwable cause) {
super(cause);
this.rasterImage = rasterImage;
}
/**
* Get image for which the exception occurred.
*
* @return image for which the exception occurred
*/
public RasterTile getRasterImage() {
return rasterImage;
}
}
/**
* ???
*/
private class RasterImageDownloadCallable implements Callable<ImageResult> {
private ImageResult result;
private int retries;
private String url;
public RasterImageDownloadCallable(int retries, RasterTile rasterImage) {
this.result = new ImageResult(rasterImage);
this.retries = retries;
String externalUrl = rasterImage.getUrl();
url = dispatcherUrlService.localize(externalUrl);
}
public ImageResult call() throws Exception {
log.debug("Fetching image: {}", url);
int triesLeft = retries;
while (true) {
InputStream inputStream = null;
try {
RasterLayer layer = configurationService.getRasterLayer(getLayerId());
inputStream = layerHttpService.getStream(url, layer);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
byte[] bytes = new byte[1024];
int readBytes;
while ((readBytes = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, readBytes);
}
outputStream.flush();
outputStream.close();
result.setImage(outputStream.toByteArray());
return result;
} catch (Exception e) { // NOSONAR
triesLeft--;
if (triesLeft == 0) {
throw new ImageException(result.getRasterImage(), e);
} else {
log.debug("Fetching image: retrying ", url);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
// converts an image to a RGBA direct color model using a workaround via buffered image
// directly calling the ColorConvert operation fails for unknown reasons ?!
/**
* Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the
* ColorConvert operation fails for unknown reasons ?!
*
* @param img
* image to convert
* @return converted image
*/
public PlanarImage toDirectColorModel(RenderedImage img) {
BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img
.getColorModel().isAlphaPremultiplied(), null);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(source, dest);
return PlanarImage.wrapRenderedImage(dest);
}
/**
* Lookup error message for internationalization bundle.
*
* @param key
* key to lookup
* @return internationalized value
*/
public String getNlsString(String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
|
plugin/print/common/src/main/java/org/geomajas/plugin/print/component/impl/RasterLayerComponentImpl.java
|
/*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.print.component.impl;
import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
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 javax.imageio.ImageIO;
import javax.media.jai.ImageLayout;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import javax.media.jai.operator.MosaicDescriptor;
import javax.media.jai.operator.TranslateDescriptor;
import org.geomajas.configuration.client.ClientMapInfo;
import org.geomajas.geometry.Bbox;
import org.geomajas.global.GeomajasException;
import org.geomajas.layer.RasterLayerService;
import org.geomajas.layer.tile.RasterTile;
import org.geomajas.plugin.print.component.LayoutConstraint;
import org.geomajas.plugin.print.component.PdfContext;
import org.geomajas.plugin.print.component.PrintComponentVisitor;
import org.geomajas.plugin.print.component.dto.RasterLayerComponentInfo;
import org.geomajas.plugin.print.component.service.PrintConfigurationService;
import org.geomajas.service.DispatcherUrlService;
import org.geomajas.service.GeoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.vividsolutions.jts.geom.Envelope;
/**
* Sub component of a map responsible for rendering raster layer.
*
* @author Jan De Moerloose
*/
@Component()
@Scope(value = "prototype")
public class RasterLayerComponentImpl extends BaseLayerComponentImpl<RasterLayerComponentInfo> {
protected static final int DOWNLOAD_MAX_ATTEMPTS = 2;
protected static final int DOWNLOAD_MAX_THREADS = 5;
protected static final long DOWNLOAD_TIMEOUT = 120000; // millis
protected static final long DOWNLOAD_TIMEOUT_ONE_TILE = 100; // millis
protected static final Font ERROR_FONT = new Font("SansSerif", Font.PLAIN, 6); //$NON-NLS-1$
private static final String BUNDLE_NAME = "org/geomajas/extension/print/rasterlayercomponent"; //$NON-NLS-1$
// do not make this static, different requests might need different bundles
@XStreamOmitField
private final ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
/** The calculated bounds. */
@XStreamOmitField
protected Envelope bbox;
/** List of the tile images. */
@XStreamOmitField
protected List<RasterTile> tiles;
/** The raster scale, may be different from map ppunit. */
@XStreamOmitField
protected double rasterScale;
@XStreamOmitField
private final Logger log = LoggerFactory.getLogger(RasterLayerComponentImpl.class);
@Autowired
@XStreamOmitField
private RasterLayerService rasterLayerService;
@Autowired
@XStreamOmitField
private PrintConfigurationService configurationService;
@Autowired
@XStreamOmitField
private GeoService geoService;
@Autowired
@XStreamOmitField
private DispatcherUrlService dispatcherUrlService;
private float opacity = 1.0f;
/** Constructor. */
public RasterLayerComponentImpl() {
getConstraint().setAlignmentX(LayoutConstraint.JUSTIFIED);
getConstraint().setAlignmentY(LayoutConstraint.JUSTIFIED);
}
/**
* Call back visitor.
*
* @param visitor
* visitor
*/
public void accept(PrintComponentVisitor visitor) {
}
@Override
public void render(PdfContext context) {
if (isVisible()) {
rasterScale = getMap().getPpUnit() * getMap().getRasterResolution() / 72;
bbox = createBbox();
if (log.isDebugEnabled()) {
log.debug("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "]");
}
ClientMapInfo map = configurationService.getMapInfo(getMap().getMapId(), getMap().getApplicationId());
try {
tiles = rasterLayerService.getTiles(getLayerId(), geoService.getCrs2(map.getCrs()), bbox, rasterScale);
if (tiles.size() > 0) {
Collection<Callable<ImageResult>> callables = new ArrayList<Callable<ImageResult>>(tiles.size());
// Build the image downloading threads
for (RasterTile tile : tiles) {
RasterImageDownloadCallable downloadThread = new RasterImageDownloadCallable(
DOWNLOAD_MAX_ATTEMPTS, tile);
callables.add(downloadThread);
}
// Loop until all images are downloaded or timeout is reached
long totalTimeout = DOWNLOAD_TIMEOUT + DOWNLOAD_TIMEOUT_ONE_TILE * tiles.size();
log.debug("=== total timeout (millis): {}", totalTimeout);
ExecutorService service = Executors.newFixedThreadPool(DOWNLOAD_MAX_THREADS);
List<Future<ImageResult>> futures = service.invokeAll(callables, totalTimeout,
TimeUnit.MILLISECONDS);
// determine the pixel bounds of the mosaic
Bbox pixelBounds = getPixelBounds(tiles);
int imageWidth = configurationService.getRasterLayerInfo(getLayerId()).getTileWidth();
int imageHeight = configurationService.getRasterLayerInfo(getLayerId()).getTileHeight();
// create the images for the mosaic
List<RenderedImage> images = new ArrayList<RenderedImage>();
for (Future<ImageResult> future : futures) {
if (future.isDone()) {
try {
ImageResult result;
result = future.get();
// create a rendered image
RenderedImage image = JAI.create("stream",
new ByteArraySeekableStream(result.getImage()));
// convert to common direct colormodel (some images have their own indexed color model)
// Sprint-51 If the image source is not available the java.awt.image will throw
// a runtime error causing the printing to fail. If this happens handle the error
// and and allow the print process to continue.
// convert to common direct colormodel (some images have their own indexed color model)
RenderedImage colored = null;
try {
colored = toDirectColorModel(image);
} catch (Exception e) {
String msg = getLayerId() + " returned a null image.";
msg += " The print plugin will not render this layer";
log.error(msg, e);
continue;
}
// translate to the correct position in the tile grid
double xOffset = result.getRasterImage().getCode().getX() * imageWidth
- pixelBounds.getX();
double yOffset = 0;
// TODO: in some cases, the y-index is up (e.g. WMS), should be down for
// all layers !!!!
if (isYIndexUp(tiles)) {
yOffset = result.getRasterImage().getCode().getY() * imageHeight
- pixelBounds.getY();
} else {
yOffset = (float) (pixelBounds.getMaxY() - (result.getRasterImage().getCode()
.getY() + 1)
* imageHeight);
}
log.debug("adding to(" + xOffset + "," + yOffset + "), url = "
+ result.getRasterImage().getUrl());
RenderedImage translated = TranslateDescriptor.create(colored, (float) xOffset,
(float) yOffset, new InterpolationNearest(), null);
images.add(translated);
} catch (ExecutionException e) {
addLoadError(context, (ImageException) (e.getCause()));
} catch (InterruptedException e) {
log.warn("missing tile in mosaic " + e.getMessage());
} catch (MalformedURLException e) {
log.warn("missing tile in mosaic " + e.getMessage());
} catch (IOException e) {
log.warn("missing tile in mosaic " + e.getMessage());
}
}
}
if (images.size() > 0) {
ImageLayout imageLayout = new ImageLayout(0, 0, (int) pixelBounds.getWidth(),
(int) pixelBounds.getHeight());
imageLayout.setTileWidth(imageWidth);
imageLayout.setTileHeight(imageHeight);
// create the mosaic image
ParameterBlock pbMosaic = new ParameterBlock();
pbMosaic.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY);
for (RenderedImage renderedImage : images) {
pbMosaic.addSource(renderedImage);
}
RenderedOp mosaic = JAI.create("mosaic", pbMosaic, new RenderingHints(JAI.KEY_IMAGE_LAYOUT,
imageLayout));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.debug("rendering to buffer...");
ImageIO.write(mosaic, "png", baos);
log.debug("rendering done, size = " + baos.toByteArray().length);
RasterTile mosaicTile = new RasterTile();
mosaicTile.setBounds(getWorldBounds(tiles));
ImageResult mosaicResult = new ImageResult(mosaicTile);
mosaicResult.setImage(baos.toByteArray());
addImage(context, mosaicResult);
} catch (IOException e) {
log.warn("could not write mosaic image " + e.getMessage());
} catch (BadElementException e) {
log.warn("could not write mosaic image " + e.getMessage());
}
}
}
} catch (GeomajasException e) {
log.warn("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "] failed : " + e.getMessage());
} catch (InterruptedException e) {
log.warn("rendering" + getLayerId() + " to [" + bbox.getMinX() + " " + bbox.getMinY() + " "
+ bbox.getWidth() + " " + bbox.getHeight() + "] failed : " + e.getMessage());
}
}
}
private boolean isYIndexUp(List<RasterTile> tiles) {
RasterTile first = tiles.iterator().next();
for (RasterTile tile : tiles) {
if (tile.getCode().getY() > first.getCode().getY()) {
return tile.getBounds().getY() > first.getBounds().getY();
} else if (tile.getCode().getY() < first.getCode().getY()) {
return tile.getBounds().getY() < first.getBounds().getY();
}
}
return false;
}
private Bbox getPixelBounds(List<RasterTile> tiles) {
Bbox bounds = null;
int imageWidth = configurationService.getRasterLayerInfo(getLayerId()).getTileWidth();
int imageHeight = configurationService.getRasterLayerInfo(getLayerId()).getTileHeight();
for (RasterTile tile : tiles) {
Bbox tileBounds = new Bbox(tile.getCode().getX() * imageWidth, tile.getCode().getY() * imageHeight,
imageWidth, imageHeight);
if (bounds == null) {
bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight());
} else {
double minx = Math.min(tileBounds.getX(), bounds.getX());
double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX());
double miny = Math.min(tileBounds.getY(), bounds.getY());
double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY());
bounds = new Bbox(minx, miny, maxx - minx, maxy - miny);
}
}
return bounds;
}
private Bbox getWorldBounds(List<RasterTile> tiles) {
Bbox bounds = null;
for (RasterTile tile : tiles) {
Bbox tileBounds = new Bbox(tile.getBounds().getX(), tile.getBounds().getY(), tile.getBounds().getWidth(),
tile.getBounds().getHeight());
if (bounds == null) {
bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight());
} else {
double minx = Math.min(tileBounds.getX(), bounds.getX());
double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX());
double miny = Math.min(tileBounds.getY(), bounds.getY());
double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY());
bounds = new Bbox(minx, miny, maxx - minx, maxy - miny);
}
}
return bounds;
}
/**
* Get the layer opacity.
*
* @return layer opacity
*/
public float getOpacity() {
return opacity;
}
/**
* Set the layer opacity.
*
* @param opacity
* layer opacity
*/
public void setOpacity(float opacity) {
this.opacity = opacity;
}
@Override
public void fromDto(RasterLayerComponentInfo rasterInfo) {
super.fromDto(rasterInfo);
String style = rasterInfo.getStyle();
if (rasterInfo.getStyle() != null) {
String match = style;
// could be 'opacity:0.5;' or '0.5'
if (style.contains("opacity:")) {
match = style.substring(style.indexOf("opacity:") + 8);
}
if (match.contains(";")) {
match = match.substring(0, match.indexOf(";"));
}
try {
setOpacity(Float.valueOf(match));
} catch (NumberFormatException nfe) {
log.warn("Could not parse opacity " + style + "of raster layer " + getLayerId());
}
}
}
/**
* Add image in the document.
*
* @param context
* PDF context
* @param imageResult
* image
* @throws BadElementException
* PDF construction problem
* @throws IOException
* PDF construction problem
*/
protected void addImage(PdfContext context, ImageResult imageResult) throws BadElementException, IOException {
Bbox imageBounds = imageResult.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lowerleft corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
// opacity
log.debug("before drawImage");
context.drawImage(Image.getInstance(imageResult.getImage()), new Rectangle(x, y, x + width, y + height),
getSize(), getOpacity());
log.debug("after drawImage");
}
/**
* Add image with a exception message in the PDF document.
*
* @param context
* PDF context
* @param e
* exception to put in image
*/
protected void addLoadError(PdfContext context, ImageException e) {
Bbox imageBounds = e.getRasterImage().getBounds();
float scaleFactor = (float) (72 / getMap().getRasterResolution());
float width = (float) imageBounds.getWidth() * scaleFactor;
float height = (float) imageBounds.getHeight() * scaleFactor;
// subtract screen position of lower-left corner
float x = (float) (imageBounds.getX() - rasterScale * bbox.getMinX()) * scaleFactor;
// shift y to lower left corner, flip y to user space and subtract
// screen position of lower-left
// corner
float y = (float) (-imageBounds.getY() - imageBounds.getHeight() - rasterScale * bbox.getMinY()) * scaleFactor;
if (log.isDebugEnabled()) {
log.debug("adding failed message=" + width + ",height=" + height + ",x=" + x + ",y=" + y);
}
float textHeight = context.getTextSize("failed", ERROR_FONT).getHeight() * 3f;
Rectangle rec = new Rectangle(x, y, x + width, y + height);
context.strokeRectangle(rec, Color.RED, 0.5f);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line1"), ERROR_FONT, new Rectangle(x, y
+ textHeight, x + width, y + height), Color.RED);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line2"), ERROR_FONT, rec, Color.RED);
context.drawText(getNlsString("RasterLayerComponent.loaderror.line3"), ERROR_FONT, new Rectangle(x, y
- textHeight, x + width, y + height), Color.RED);
}
/**
* ???
*/
private class ImageResult {
private byte[] image;
private RasterTile rasterImage;
public ImageResult(RasterTile rasterImage) {
this.rasterImage = rasterImage;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public RasterTile getRasterImage() {
return rasterImage;
}
}
/**
* Image Exception
*/
private class ImageException extends Exception {
private static final long serialVersionUID = 151L;
private final RasterTile rasterImage;
/**
* Constructor.
*
* @param rasterImage
* image for which the exception occurred
* @param cause
* cause exception
*
* */
public ImageException(RasterTile rasterImage, Throwable cause) {
super(cause);
this.rasterImage = rasterImage;
}
/**
* Get image for which the exception occurred.
*
* @return image for which the exception occurred
*/
public RasterTile getRasterImage() {
return rasterImage;
}
}
/**
* ???
*/
private class RasterImageDownloadCallable implements Callable<ImageResult> {
private ImageResult result;
private int retries;
private String url;
public RasterImageDownloadCallable(int retries, RasterTile rasterImage) {
this.result = new ImageResult(rasterImage);
this.retries = retries;
String externalUrl = rasterImage.getUrl();
url = dispatcherUrlService.localize(externalUrl);
}
public ImageResult call() throws Exception {
log.debug("Fetching image: {}", url);
int triesLeft = retries;
while (true) {
try {
URL imageUrl = new URL(url);
InputStream inputStream = imageUrl.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
byte[] bytes = new byte[1024];
int readBytes;
while ((readBytes = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, readBytes);
}
inputStream.close();
outputStream.flush();
outputStream.close();
result.setImage(outputStream.toByteArray());
return result;
} catch (Exception e) { // NOSONAR
triesLeft--;
if (triesLeft == 0) {
throw new ImageException(result.getRasterImage(), e);
} else {
log.debug("Fetching image: retrying ", url);
}
}
}
}
}
// converts an image to a RGBA direct color model using a workaround via buffered image
// directly calling the ColorConvert operation fails for unknown reasons ?!
/**
* Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the
* ColorConvert operation fails for unknown reasons ?!
*
* @param img
* image to convert
* @return converted image
*/
public PlanarImage toDirectColorModel(RenderedImage img) {
BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img
.getColorModel().isAlphaPremultiplied(), null);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(source, dest);
return PlanarImage.wrapRenderedImage(dest);
}
/**
* Lookup error message for internationalization bundle.
*
* @param key
* key to lookup
* @return internationalized value
*/
public String getNlsString(String key) {
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
|
GWTII-172: proxy support added
|
plugin/print/common/src/main/java/org/geomajas/plugin/print/component/impl/RasterLayerComponentImpl.java
|
GWTII-172: proxy support added
|
|
Java
|
agpl-3.0
|
c92889f3a170d681fae2cb933d269f90371bb18d
| 0
|
liquidJbilling/LT-Jbilling-MsgQ-3.1,PaloAlto/jbilling,PaloAlto/jbilling,liquidJbilling/LT-Jbilling-MsgQ-3.1,liquidJbilling/LT-Jbilling-MsgQ-3.1,liquidJbilling/LT-Jbilling-MsgQ-3.1
|
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2008 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.server.user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.CommonConstants;
import com.sapienter.jbilling.common.JBCrypto;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.entity.ContactDTO;
import com.sapienter.jbilling.server.util.Constants;
/**
* @author emilc
*/
public final class EntitySignup {
private Connection conn = null;
private UserDTOEx user;
private ContactDTO contact;
private Integer languageId;
class Table {
String name;
String columns[];
String data[][];
String international_columns[][][];
boolean isMassive;
int maxRows;
int minRows;
Column columnsMetaData[];
int nextId;
int index;
}
class Column {
String dataType;
int intRange1;
int intRange2;
String dateRange1;
int dateRangeDays;
boolean isNull;
String constantValue;
float floatFactor;
}
/**
*
* @param root
* It uses only the user name and password
* @param contact
* @param languageId
*/
public EntitySignup(UserDTOEx root, ContactDTO contact,
Integer languageId) {
checkMainRole(root);
this.user = root;
this.contact = contact;
this.languageId = languageId;
}
public int process() throws Exception {
try {
JNDILookup jndi = JNDILookup.getFactory();
// the connection will be closed by the RowSet as soon as it
// finished executing the command
conn = jndi.lookUpDataSource().getConnection();
int newEntity = initData();
conn.close();
return newEntity;
} catch (Exception e) {
try {
conn.close();
} catch(Exception x) {}
throw new Exception(e);
}
}
void processTable(Table table)
throws Exception {
StringBuffer sql = new StringBuffer();
if (table.columns[0].equals("i_id")) {
initTable(table);
}
int rowIdx = table.nextId;
try {
System.out.println("Now processing " +
table.name + " [" + table.index + "]");
// generate the INSERT string with this table's columns
sql.append("insert into " + table.name + " (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append(table.columns[columnsIdx].substring(2));
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(") values (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append("?");
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(")");
System.out.println(sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
// for each row to be inserted, apply the data to the '?'
int rowCount = 0;
for (rowCount = 0; table.data != null && rowCount < table.data.length;
rowCount++, rowIdx++) {
// normal tables don't have data for the first column (the id)
// but map tables have data for every column
int idxDifference = 0; // this will be for a map table
for (int columnIdx = 0;
columnIdx < table.columns.length;
columnIdx++) {
String field;
if (table.columns[columnIdx].equals("i_id")) {
// this is the id, which is automatically generated
idxDifference = 1; // this is a normal table
stmt.setInt(columnIdx + 1, rowIdx);
} else {
String type = table.columns[columnIdx].substring(0, 2);
field = table.data[rowCount][columnIdx - idxDifference];
if (type.equals("d_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.DATE);
} else {
java.sql.Date dateField = new Date(Util.parseDate(field).getTime());
stmt.setDate(columnIdx + 1, dateField);
}
} else if (type.equals("s_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.VARCHAR);
} else {
stmt.setString(columnIdx + 1, field);
}
} else if (type.equals("i_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.INTEGER);
} else {
stmt.setInt(columnIdx + 1, Integer.valueOf(field));
}
} else if (type.equals("f_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.FLOAT);
} else {
stmt.setFloat(columnIdx + 1, Float.valueOf(field));
}
} else {
throw new Exception("Don't know the type " + type);
}
}
}
if (stmt.executeUpdate() != 1) {
throw new Exception(
"insert failed. Row "
+ rowIdx
+ " table "
+ table.name);
}
// now take care of the pseudo columns with international
// text
if (table.international_columns != null) {
insertPseudoColumns(
table.index,
rowIdx,
table.international_columns[rowCount]);
}
}
System.out.println("inserted " + rowCount + " rows");
stmt.close();
updateBettyTablesRows(table.index, rowIdx);
table.nextId = rowIdx;
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
throw new Exception("Error inserting table " + table.name +
" row " + (rowIdx + 1));
}
}
Table addTable(String name, String columns[],
String data[][], boolean massive) {
return addTable(name, columns, data, null, massive);
}
Table addTable(String name, String columns[], String data[][],
String intColumns[][][], boolean massive) {
return addTable(name, columns, data, intColumns, massive, null, 0, 0);
}
Table addTable(
String name,
String columns[],
String data[][],
String intColumns[][][],
boolean massive,
Column metaData[],
int min, int max) {
Table table;
table = new Table();
table.name = name;
table.columns = columns;
table.data = data;
table.international_columns = intColumns;
table.isMassive = massive;
table.columnsMetaData = metaData;
table.maxRows = max;
table.minRows = min;
return table;
}
void updateBettyTablesRows(int tableId, int totalRows)
throws SQLException {
PreparedStatement stmt =
conn.prepareStatement(
"update jbilling_table set next_id = ? " + " where id = ?");
stmt.setInt(1, totalRows);
stmt.setInt(2, tableId);
stmt.executeUpdate();
stmt.close();
}
void initTable(Table table)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"select next_id, id from jbilling_table " +
" where name = ?");
stmt.setString(1, table.name);
ResultSet res = stmt.executeQuery();
if (res.next()) {
table.nextId = res.getInt(1);
table.index = res.getInt(2);
stmt = conn.prepareStatement(
"select max(id) from " + table.name);
res = stmt.executeQuery();
res.next();
int maxId = res.getInt(1);
if (table.nextId <= maxId) {
table.nextId = maxId + 1;
}
} else {
throw new SQLException("No rows for table " + table.name);
}
res.close();
stmt.close();
}
void insertPseudoColumns(int tableId, int rowId, String data[][])
throws SQLException {
String sql = "insert into international_description "
+ "(table_id, foreign_id, psudo_column,language_id,content) "
+ "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, tableId);
stmt.setInt(2, rowId);
for (int entry = 0; entry < data.length; entry++) {
// this would be the pseudo column
stmt.setString(3, data[entry][0]);
// and this the actual content
stmt.setString(5, data[entry][1]);
String language = null;
if (data[entry].length < 3 || data[entry][2] == null) {
language = "1"; //defaults to english
} else {
language = data[entry][2];
}
stmt.setInt(4, Integer.valueOf(language));
if (stmt.executeUpdate() != 1) {
throw new SQLException("Should've insterted one row into international_description");
}
}
stmt.close();
}
// idealy, this should be loaded from betty-schema.xml
int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id",
"i_subscriber_status"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString(), "1" }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id", "i_optlock" };
String orderPeriodData[][] = new String[1][4];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodData[0][3] = "1"; // version
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order", "i_optlock" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1","1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1","1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2","1" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1","1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1","1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1","1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1","1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2","1" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1","1" }, // Async payment processing (no parameters)
{ String.valueOf(newEntityId), "28","1","1" }, // BasicItemManager
{ String.valueOf(newEntityId), "33","1","1" }, // RulesMediationTask
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int firstPT = table.nextId - pluggableTaskData.length;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value",
"i_optlock"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(firstPT + 9), "design", null, "simple_invoice_b2b", null,"1" },
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table, firstPT, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, firstPT + 7, "smtp_server", null,
null, null);
addTaskParameter(table, firstPT + 7, "from", null,
contact.getEmail(), null);
addTaskParameter(table, firstPT + 7, "username", null,
null, null);
addTaskParameter(table, firstPT + 7, "password", null,
null, null);
addTaskParameter(table, firstPT + 7, "port", null,
null, null);
addTaskParameter(table, firstPT + 7, "reply_to", null,
null, null);
addTaskParameter(table, firstPT + 7, "bcc_to", null,
null, null);
addTaskParameter(table, firstPT + 7, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
void addTaskParameter(Table ptTable, int taskId,
String desc, Integer intP, String strP, Float floP)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task_parameter " +
"(id, task_id, name, int_value, str_value, float_value, optlock)" +
" values(?, ?, ?, ?, ?, ?, 1)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, taskId);
stmt.setString(3, desc);
if (intP != null) {
stmt.setInt(4, intP.intValue());
} else {
stmt.setNull(4, Types.INTEGER);
}
stmt.setString(5, strP);
if (floP != null) {
stmt.setFloat(6, floP.floatValue());
} else {
stmt.setNull(6, Types.FLOAT);
}
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
void addTask(Table ptTable, int entityId, int type, int position)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task (id, entity_id, type_id, processing_order)" +
" values(?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, entityId);
stmt.setInt(3, type);
stmt.setInt(4, position);
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
private static void checkMainRole(UserDTOEx root){
if (CommonConstants.TYPE_ROOT.equals(root.getMainRoleId())){
Logger.getLogger(EntitySignup.class).warn("Attention: Root user passed with roleId: " + root.getMainRoleId());
}
root.setMainRoleId(CommonConstants.TYPE_ROOT);
}
private static String getDBPassword(UserDTOEx root){
checkMainRole(root);
JBCrypto crypto = JBCrypto.getPasswordCrypto(root.getMainRoleId());
return crypto.encrypt(root.getPassword());
}
}
|
classes/com/sapienter/jbilling/server/user/EntitySignup.java
|
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2008 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.server.user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.CommonConstants;
import com.sapienter.jbilling.common.JBCrypto;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.entity.ContactDTO;
import com.sapienter.jbilling.server.util.Constants;
/**
* @author emilc
*/
public final class EntitySignup {
private Connection conn = null;
private UserDTOEx user;
private ContactDTO contact;
private Integer languageId;
class Table {
String name;
String columns[];
String data[][];
String international_columns[][][];
boolean isMassive;
int maxRows;
int minRows;
Column columnsMetaData[];
int nextId;
int index;
}
class Column {
String dataType;
int intRange1;
int intRange2;
String dateRange1;
int dateRangeDays;
boolean isNull;
String constantValue;
float floatFactor;
}
/**
*
* @param root
* It uses only the user name and password
* @param contact
* @param languageId
*/
public EntitySignup(UserDTOEx root, ContactDTO contact,
Integer languageId) {
checkMainRole(root);
this.user = root;
this.contact = contact;
this.languageId = languageId;
}
public int process() throws Exception {
try {
JNDILookup jndi = JNDILookup.getFactory();
// the connection will be closed by the RowSet as soon as it
// finished executing the command
conn = jndi.lookUpDataSource().getConnection();
int newEntity = initData();
conn.close();
return newEntity;
} catch (Exception e) {
try {
conn.close();
} catch(Exception x) {}
throw new Exception(e);
}
}
void processTable(Table table)
throws Exception {
StringBuffer sql = new StringBuffer();
if (table.columns[0].equals("i_id")) {
initTable(table);
}
int rowIdx = table.nextId;
try {
System.out.println("Now processing " +
table.name + " [" + table.index + "]");
// generate the INSERT string with this table's columns
sql.append("insert into " + table.name + " (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append(table.columns[columnsIdx].substring(2));
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(") values (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append("?");
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(")");
System.out.println(sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
// for each row to be inserted, apply the data to the '?'
int rowCount = 0;
for (rowCount = 0; table.data != null && rowCount < table.data.length;
rowCount++, rowIdx++) {
// normal tables don't have data for the first column (the id)
// but map tables have data for every column
int idxDifference = 0; // this will be for a map table
for (int columnIdx = 0;
columnIdx < table.columns.length;
columnIdx++) {
String field;
if (table.columns[columnIdx].equals("i_id")) {
// this is the id, which is automatically generated
idxDifference = 1; // this is a normal table
stmt.setInt(columnIdx + 1, rowIdx);
} else {
String type = table.columns[columnIdx].substring(0, 2);
field = table.data[rowCount][columnIdx - idxDifference];
if (type.equals("d_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.DATE);
} else {
java.sql.Date dateField = new Date(Util.parseDate(field).getTime());
stmt.setDate(columnIdx + 1, dateField);
}
} else if (type.equals("s_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.VARCHAR);
} else {
stmt.setString(columnIdx + 1, field);
}
} else if (type.equals("i_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.INTEGER);
} else {
stmt.setInt(columnIdx + 1, Integer.valueOf(field));
}
} else if (type.equals("f_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.FLOAT);
} else {
stmt.setFloat(columnIdx + 1, Float.valueOf(field));
}
} else {
throw new Exception("Don't know the type " + type);
}
}
}
if (stmt.executeUpdate() != 1) {
throw new Exception(
"insert failed. Row "
+ rowIdx
+ " table "
+ table.name);
}
// now take care of the pseudo columns with international
// text
if (table.international_columns != null) {
insertPseudoColumns(
table.index,
rowIdx,
table.international_columns[rowCount]);
}
}
System.out.println("inserted " + rowCount + " rows");
stmt.close();
updateBettyTablesRows(table.index, rowIdx);
table.nextId = rowIdx;
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
throw new Exception("Error inserting table " + table.name +
" row " + (rowIdx + 1));
}
}
Table addTable(String name, String columns[],
String data[][], boolean massive) {
return addTable(name, columns, data, null, massive);
}
Table addTable(String name, String columns[], String data[][],
String intColumns[][][], boolean massive) {
return addTable(name, columns, data, intColumns, massive, null, 0, 0);
}
Table addTable(
String name,
String columns[],
String data[][],
String intColumns[][][],
boolean massive,
Column metaData[],
int min, int max) {
Table table;
table = new Table();
table.name = name;
table.columns = columns;
table.data = data;
table.international_columns = intColumns;
table.isMassive = massive;
table.columnsMetaData = metaData;
table.maxRows = max;
table.minRows = min;
return table;
}
void updateBettyTablesRows(int tableId, int totalRows)
throws SQLException {
PreparedStatement stmt =
conn.prepareStatement(
"update jbilling_table set next_id = ? " + " where id = ?");
stmt.setInt(1, totalRows);
stmt.setInt(2, tableId);
stmt.executeUpdate();
stmt.close();
}
void initTable(Table table)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"select next_id, id from jbilling_table " +
" where name = ?");
stmt.setString(1, table.name);
ResultSet res = stmt.executeQuery();
if (res.next()) {
table.nextId = res.getInt(1);
table.index = res.getInt(2);
stmt = conn.prepareStatement(
"select max(id) from " + table.name);
res = stmt.executeQuery();
res.next();
int maxId = res.getInt(1);
if (table.nextId <= maxId) {
table.nextId = maxId + 1;
}
} else {
throw new SQLException("No rows for table " + table.name);
}
res.close();
stmt.close();
}
void insertPseudoColumns(int tableId, int rowId, String data[][])
throws SQLException {
String sql = "insert into international_description "
+ "(table_id, foreign_id, psudo_column,language_id,content) "
+ "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, tableId);
stmt.setInt(2, rowId);
for (int entry = 0; entry < data.length; entry++) {
// this would be the pseudo column
stmt.setString(3, data[entry][0]);
// and this the actual content
stmt.setString(5, data[entry][1]);
String language = null;
if (data[entry].length < 3 || data[entry][2] == null) {
language = "1"; //defaults to english
} else {
language = data[entry][2];
}
stmt.setInt(4, Integer.valueOf(language));
if (stmt.executeUpdate() != 1) {
throw new SQLException("Should've insterted one row into international_description");
}
}
stmt.close();
}
// idealy, this should be loaded from betty-schema.xml
int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id",
"i_subscriber_status"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString(), "1" }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id", "i_optlock" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodData[0][3] = "1"; // version
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order", "i_optlock" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1","1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1","1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2","1" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1","1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1","1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1","1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1","1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2","1" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1","1" }, // Async payment processing (no parameters)
{ String.valueOf(newEntityId), "28","1","1" }, // BasicItemManager
{ String.valueOf(newEntityId), "33","1","1" }, // RulesMediationTask
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int firstPT = table.nextId - pluggableTaskData.length;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value",
"i_optlock"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(firstPT + 9), "design", null, "simple_invoice_b2b", null,"1" },
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table, firstPT, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, firstPT + 7, "smtp_server", null,
null, null);
addTaskParameter(table, firstPT + 7, "from", null,
contact.getEmail(), null);
addTaskParameter(table, firstPT + 7, "username", null,
null, null);
addTaskParameter(table, firstPT + 7, "password", null,
null, null);
addTaskParameter(table, firstPT + 7, "port", null,
null, null);
addTaskParameter(table, firstPT + 7, "reply_to", null,
null, null);
addTaskParameter(table, firstPT + 7, "bcc_to", null,
null, null);
addTaskParameter(table, firstPT + 7, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
void addTaskParameter(Table ptTable, int taskId,
String desc, Integer intP, String strP, Float floP)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task_parameter " +
"(id, task_id, name, int_value, str_value, float_value, optlock)" +
" values(?, ?, ?, ?, ?, ?, 1)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, taskId);
stmt.setString(3, desc);
if (intP != null) {
stmt.setInt(4, intP.intValue());
} else {
stmt.setNull(4, Types.INTEGER);
}
stmt.setString(5, strP);
if (floP != null) {
stmt.setFloat(6, floP.floatValue());
} else {
stmt.setNull(6, Types.FLOAT);
}
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
void addTask(Table ptTable, int entityId, int type, int position)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task (id, entity_id, type_id, processing_order)" +
" values(?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, entityId);
stmt.setInt(3, type);
stmt.setInt(4, position);
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
private static void checkMainRole(UserDTOEx root){
if (CommonConstants.TYPE_ROOT.equals(root.getMainRoleId())){
Logger.getLogger(EntitySignup.class).warn("Attention: Root user passed with roleId: " + root.getMainRoleId());
}
root.setMainRoleId(CommonConstants.TYPE_ROOT);
}
private static String getDBPassword(UserDTOEx root){
checkMainRole(root);
JBCrypto crypto = JBCrypto.getPasswordCrypto(root.getMainRoleId());
return crypto.encrypt(root.getPassword());
}
}
|
Minor fix to new company creation
|
classes/com/sapienter/jbilling/server/user/EntitySignup.java
|
Minor fix to new company creation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.