gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
/** This code is property of the Corundum project managed under the Software Developers' Association of Arizona State University.
*
* Copying and use of this open-source code is permitted provided that the following requirements are met:
*
* - This code may not be used or distributed for private enterprise, including but not limited to personal or corporate profit. - Any products resulting from the copying,
* use, or modification of this code may not claim endorsement by the Corundum project or any of its members or associates without written formal permission from the endorsing
* party or parties. - This code may not be copied or used under any circumstances without the inclusion of this notice and mention of the contribution of the code by the
* Corundum project. In source code form, this notice must be included as a comment as it is here; in binary form, proper documentation must be included with the final product
* that includes this statement verbatim.
*
* @author REALDrummer */
package org.corundummc.biomes;
import org.corundummc.biomes.overworld.OverworldBiome.OverworldBiomeTypes;
import org.corundummc.biomes.worldwide.WorldwideBiome.WorldwideBiomeTypes;
import org.corundummc.blocks.Block;
import org.corundummc.entities.Entity;
import org.corundummc.utils.types.IDedType;
import org.corundummc.utils.types.Typed;
import org.corundummc.world.Location;
import org.corundummc.world.World;
import org.corundummc.world.Zone;
import net.minecraft.world.biome.BiomeGenBase;
/** TODO
*
* @param <S>
* is a self-parameterization; this type should be the same type as this class.
* @param <MC>
* determines the type of Minecraft BiomeGenBase <tt>Object</tt> that this class represents.
* @param <T>
* determines the type of {@link BiomeType} that represents the type of this class. */
public abstract class Biome<S extends Biome<S, MC, T>, MC extends BiomeGenBase, T extends Biome.BiomeType<T, MC, S>> extends Typed<T> {
/** Minecraft has no Biome object; the best way I thought to represent a Biome without using lots of C.P.U. and memory is to just store the location of one block in the
* biome; this could allow us to calculate whether or not other points are in this same biome and other properties will likely come from the biome's type */
protected final Location location;
protected Zone circumscribing_zone = null; /* stores the circumscribing zone after the first call of getCircumscribingZone() so that later calls to that method don't take
* up more memory and C.P.U. */
protected Biome(Location location) {
this.location = location;
}
public static interface BiomeTypes extends WorldwideBiomeTypes, OverworldBiomeTypes {
//
}
public abstract static class BiomeType<S extends BiomeType<S, MC, I>, MC extends BiomeGenBase, I extends Biome<I, MC, S>> extends IDedType<S> {
protected MC biomeMC;
protected BiomeType(MC biomeMC) {
super(biomeMC.biomeID);
this.biomeMC = biomeMC;
addValueAs(BiomeType.class);
}
// abstract utilities
public abstract I fromLocation(Location location);
// overridden utilities
@Override
public String getName() {
return biomeMC.biomeName.replaceAll("(?<[a-z])(?=[A-Z])", " ");
}
// static utilities
/** <b><u>This method may be ignored by plugin developers; it is not likely to be of use to you.</b></u><br>
* This method is used to create a new instance of {@link Entity Corundum Entity} to wrap around the given {@link net.minecraft.entity.Entity Minecraft Entity}.
*
* @param biomeMC
* is the Minecraft Entity that will wrapped with a new {@link Entity Corundum Entity} <tt>Object</tt>.
* @return a new Entity created using the given {@link net.minecraft.entity.Entity Minecraft Entity}. */
@SuppressWarnings("unchecked")
public static <MC extends BiomeGenBase> BiomeType<?, MC, ?> fromMC(MC biomeMC) {
return (BiomeType<?, MC, ?>) BiomeType.getByID(biomeMC.biomeID);
}
// pseudo-enum utilities
public static BiomeType<?, ?, ?> getByID(int id) {
return getByID(BiomeType.class, id);
}
public static BiomeType<?, ?, ?>[] values() {
return values(BiomeType.class);
}
}
// private utilities
private class EdgeFollower {
/** This <b>int</b> represents the x-coordinate at which the edge following begins. This is <i>not</i> necessarily the same as the x-coordinate of the location for this
* {@link Biome} because the x may be incremented to find the first edge to start following the edge. */
private final int start_x;
/** This <b>int</b> represents the z-coordinate at which the edge following begins; since we only move in the x-direction when finding the edge, this z-coordinate will
* be the same as the location of this {@link Biome}. */
private final int start_z;
/* This keeps track of the x- and z-coordinates of the block that the edge following first travels to from the start location; this is important to avoid an edge case
* described in the edge-following function. */
private Integer second_x = null, second_z = null;
/* This keeps track of the x- and z-coordinates that the edge-following function is currently visiting. */
private int x, z;
/* This keeps track of the x- and z-coordinates that the edge-following algorithm last visited. */
private int last_x, last_z;
/* These will be used in the for loops in the recursive edge-following function; I just initialized them here to save on stack memory. */
private int next_x, next_z;
/* This keeps track of the results, the lowest and highest x- and z-coordinates found while following the edge. */
private int lowest_x, lowest_z, highest_x, highest_z;
EdgeFollower() {
// first, find the edge by moving in the positive x direction until we hit a new biome
start_z = location.getBlockZ();
int temp_start_x = location.getBlockX();
while (isCorrectBiomeType(temp_start_x, start_z))
temp_start_x++;
start_x = temp_start_x;
// start x and z and the start x and z
x = start_x;
z = start_z;
// initialize last x and z to the coordinates of the block 1 past the start block in the positive x direction
last_x = x + 1;
last_z = z;
// initialize lowest and highest x and z values to the start x and z values
lowest_x = start_x;
highest_x = start_x;
lowest_z = start_z;
highest_z = start_z;
/* start following the edge recursively up/left by checking for blocks of the same biome starting from the last block explored in a counter-clockwise manner */
followTheEdge();
}
private void followTheEdge() {
/* if we've reached the start again, we MIGHT be done */
if (x == start_x && z == start_z && second_x != null && second_z != null) {
/* edge case!: the start x and z followed one edge, but if there was a one-block corridor at the start location, it will only follow the edge one direction and
* the other part of the biome connected by the one-block corridor will not be searched; therefore, we need to check for any parts of the biome that were not
* covered by the parsing so far by looking for blocks of the same biome type that were not to the up/left of the second and last parsed blocks */
findNext();
/* if the next block found is the second block searched from the start, there are no more edges to search; otherwise, we missed a portion of the biome that
* connects at our start location via a one-block corridor, so we need to follow the edge some more */
if (next_x != second_x || next_z != second_z) {
last_x = x;
last_z = z;
x = next_x;
z = next_z;
followTheEdge();
}
/* this check above allows the recursion to check every edge starting at the start x and z until it gets back to the first one it followed; then, it's done */
return;
}
// no base cases or edge cases? Great! find the next and follow it
findNext();
// if the second x- and z-coordinates are still null, assign them the next values
if (second_x == null) {
/* edge case!: if second x- and z-coordinates are not found and the next block given is not of the same biome type, it means no adjacent blocks are of the same
* biome and we have a one-block biome! */
if (!isCorrectBiomeType(next_x, next_z))
/* nothing more needs to be done; the highest and lowest x- and z-coordinates will be the same as the start x- and z-coordinates */
return;
else {
// if we don't have a one-block biome, set the second x- and z-coordinates
second_x = next_x;
second_z = next_z;
}
}
// update the highest and lowest x- and z-coordinates as needed
if (next_x < lowest_x)
lowest_x = next_x;
else if (next_x > highest_x)
highest_x = next_x;
if (next_z < lowest_z)
lowest_z = next_z;
else if (next_z > highest_z)
highest_z = next_z;
// follow the edge to the next x- and z-coordinates
last_x = x;
last_z = z;
x = next_x;
z = next_z;
followTheEdge();
}
/** This method uses the current x- and z-coordinates to find the first adjacent block of the same biome by checking in a counter-clockwise manner starting from (but
* not including) the last x- and z-coordinates; the results are stored in {@link #next_x} and {@link #next_z}. */
private void findNext() {
/* initialize the next x- and z-coordinates to the last x- and z-coordinates; they will be incremented clockwise about (x, z) before the first check so it will
* check the last x- and z-coordinates, allowing it to return the last block if that's the only way back to the rest of the biome in a one-block corridor dead end */
next_x = last_x;
next_z = last_z;
for (int i = 0; i < 8 /* there are 8 1x1 block columns adjacent to this column (including diagonals) */; i++) {
// iterate to the next (x, z) coordinate pair
/* the (x, z) coordinate pairs for the 1x1 block columns adjacent to the center block follow a cycle in the counter clockwise direction where the value shown
* is relative to the center block:
* x: 1 0-1-1-1 0 1 1
* z: 1 1 1 0-1-1-1 0;
* the difference between these values also cycles:
* x: 0-1-1 0 0 1 1 0
* z: 1 0 0-1-1 0 0 1
* this difference cycle is used in a series of if statements below to determine the next x- and z-coordinates to check */
if (next_x - x != -1 && next_z - z == 1)
next_x--;
else if (next_x - x == -1 && next_z - z != -1)
next_z--;
else if (next_x - x != 1 && next_z - z == -1)
next_x++;
else
next_z++;
/* if this current 1x1 column is of the right biome, return it immediately through next_x and next_z */
if (isCorrectBiomeType(next_x, next_z))
return;
}
}
private boolean isCorrectBiomeType(int x, int z) {
return location.getWorld().MC().getChunkFromChunkCoords(x, z).getBiomeArray()[x * 16 + z] == getTypeID();
}
// result getters
public int getLowestX() {
return lowest_x;
}
public int getHighestX() {
return highest_x;
}
public int getLowestZ() {
return lowest_z;
}
public int getHighestZ() {
return highest_z;
}
}
// static utilities
// type utilities
// instance utilities
/* TODO: public boolean contains(Location location): make an algorithm that tries to find a path connecting this.location with the given location only through the same
* type of biome; I've haeard that an algorithm called A-Star may be our best bet and we can optimize this with a few simple facts like 1) if it's outside the
* circumscribing zone, it's not in the biome (but only do that if the circumscribing zone has already been calculated) and 2) if the block's biome isn't the same type of
* biome, it's clearly not the same biome */
/** This method returns the {@link Location} used to initialize this {@link Biome} <tt>Object</tt>. This {@link Location} is inside the {@link Biome} somewhere, but is not
* chosen randomly. This can be useful if you just need any {@link Location} inside this {@link Biome} and you don't need it to be random.
*
* @return the {@link Location} used to initialize this {@link Biome}. */
public Location getLocation() {
return location;
}
// TODO: link "desert" and "river" biomes and "build height" (World.getBuildHeight()) below
/** This method returns a zone that "circumscribes" this contiguous {@link Biome}. In other words, it returns a zone that just barely fits around the whole entire
* {@link Biome}, so every {@link Block} in the {@link Biome} is in the zone, though not every {@link Block} in the {@link Zone} is part of the {@link Biome}. <br>
* <br>
* One {@link Biome} is a contiguous area of the same {@link BiomeType}; that means if a river biome goes all the way across a desert and cuts it into two pieces, those
* are
* considered two <i>separate</i> desert biomes. <br>
* <br>
* Because {@link Biome}s reach from the bottom of the {@link World} to the top, all circumscribing zones' y-coordinates go from the minimum value of an integer (see
* {@link Integer#MIN_VALUE}) to the maximum value of an integer (see {@link Integer#MAX_VALUE}) to cover all possible y-coordinates, including those below the bottom of
* the {@link World} and above the {@link World}'s build height. <br>
* <br>
* <b><i>NOTE:</b></i> Finding the edges of a {@link Biome} requires a very resource intensive algorithm. This means that if you have one {@link Biome}, feel free to
* call this method as much as you want; after the first call, it calculates and stores the result so that subsequent calls don't need to recalculate the {@link Zone}.
* However, be warned: avoid making a bunch of {@link Biome}s and get all their circumscribing zones because it will take lots and lots and lots of calculations!
*
* @return a {@link Zone} that perfectly circumscribes this contiguous {@link Biome}. */
public Zone getCircumscribingZone() {
// first, if the circumscribing zone has already been calculated, don't calculate it again
if (circumscribing_zone != null)
return circumscribing_zone;
/* use the EdgeFollower Object to find and follow the edge of the biome, keeping track of the highest and lowest x- and z-coordinates it encounters */
EdgeFollower results = new EdgeFollower();
// finally, put the results into a Zone
return circumscribing_zone =
new Zone(new Location(results.getLowestX(), Integer.MIN_VALUE, results.getLowestZ(), location.getWorld()), new Location(results.getHighestX(),
Integer.MAX_VALUE, results.getHighestZ(), location.getWorld()));
}
/* TODO: getRandomLocation() to get a random location in this biome; I recommend picking a random spot in the circumscribing zone and seeing if that point is inside this
* biome; NOTE: I recommend first implementing Zone.getRandomPoint() */
public World getWorld() {
return getLocation().getWorld();
}
}
| |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.vulkan.VK10.*;
/**
* See {@link VkPhysicalDeviceIDProperties}.
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkPhysicalDeviceIDPropertiesKHR {
* VkStructureType sType;
* void * pNext;
* uint8_t deviceUUID[VK_UUID_SIZE];
* uint8_t driverUUID[VK_UUID_SIZE];
* uint8_t deviceLUID[VK_LUID_SIZE];
* uint32_t deviceNodeMask;
* VkBool32 deviceLUIDValid;
* }</code></pre>
*/
public class VkPhysicalDeviceIDPropertiesKHR extends VkPhysicalDeviceIDProperties {
/**
* Creates a {@code VkPhysicalDeviceIDPropertiesKHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkPhysicalDeviceIDPropertiesKHR(ByteBuffer container) {
super(container);
}
/** Sets the specified value to the {@code sType} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the {@link VK11#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES} value to the {@code sType} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR sType$Default() { return sType(VK11.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES); }
/** Sets the specified value to the {@code pNext} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR pNext(@NativeType("void *") long value) { npNext(address(), value); return this; }
/** Initializes this struct with the specified values. */
@Override
public VkPhysicalDeviceIDPropertiesKHR set(
int sType,
long pNext
) {
sType(sType);
pNext(pNext);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkPhysicalDeviceIDPropertiesKHR set(VkPhysicalDeviceIDPropertiesKHR src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceIDPropertiesKHR malloc() {
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceIDPropertiesKHR calloc() {
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance allocated with {@link BufferUtils}. */
public static VkPhysicalDeviceIDPropertiesKHR create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, memAddress(container), container);
}
/** Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance for the specified memory address. */
public static VkPhysicalDeviceIDPropertiesKHR create(long address) {
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceIDPropertiesKHR createSafe(long address) {
return address == NULL ? null : wrap(VkPhysicalDeviceIDPropertiesKHR.class, address);
}
/**
* Returns a new {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceIDPropertiesKHR.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VkPhysicalDeviceIDPropertiesKHR.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }
/**
* Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceIDPropertiesKHR malloc(MemoryStack stack) {
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkPhysicalDeviceIDPropertiesKHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceIDPropertiesKHR calloc(MemoryStack stack) {
return wrap(VkPhysicalDeviceIDPropertiesKHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceIDPropertiesKHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceIDPropertiesKHR.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** An array of {@link VkPhysicalDeviceIDPropertiesKHR} structs. */
public static class Buffer extends VkPhysicalDeviceIDProperties.Buffer {
private static final VkPhysicalDeviceIDPropertiesKHR ELEMENT_FACTORY = VkPhysicalDeviceIDPropertiesKHR.create(-1L);
/**
* Creates a new {@code VkPhysicalDeviceIDPropertiesKHR.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkPhysicalDeviceIDPropertiesKHR#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkPhysicalDeviceIDPropertiesKHR getElementFactory() {
return ELEMENT_FACTORY;
}
/** Sets the specified value to the {@code sType} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR.Buffer sType(@NativeType("VkStructureType") int value) { VkPhysicalDeviceIDPropertiesKHR.nsType(address(), value); return this; }
/** Sets the {@link VK11#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES} value to the {@code sType} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR.Buffer sType$Default() { return sType(VK11.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES); }
/** Sets the specified value to the {@code pNext} field. */
@Override
public VkPhysicalDeviceIDPropertiesKHR.Buffer pNext(@NativeType("void *") long value) { VkPhysicalDeviceIDPropertiesKHR.npNext(address(), value); return this; }
}
}
| |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.actions;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.ActionResult;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.server.FailureDetails;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.SymlinkAction.Code;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import javax.annotation.Nullable;
/** Action to create a symbolic link. */
@AutoCodec
public final class SymlinkAction extends AbstractAction {
private static final String GUID = "7f4fab4d-d0a7-4f0f-8649-1d0337a21fee";
/** Null when {@link #getPrimaryInput} is the target of the symlink. */
@Nullable private final PathFragment inputPath;
@Nullable private final String progressMessage;
@VisibleForSerialization
enum TargetType {
/**
* The symlink points into a Fileset.
*
* <p>If this is set, the action also updates the mtime for its target thus forcing actions
* depending on it to be re-executed. This would not be necessary in an ideal world, but
* dependency checking for Filesets output trees is unsound because they are directories, so we
* need to force them to be considered changed this way. Yet Another Reason why Filests should
* go away.
*/
FILESET,
/**
* The symlink should point to an executable.
*
* <p>Blaze will verify that the target is indeed executable.
*/
EXECUTABLE,
/** Just a vanilla symlink. Don't do anything else other than creating the symlink. */
OTHER,
}
private final TargetType targetType;
/**
* Creates an action that creates a symlink pointing to an artifact.
*
* @param owner the action owner.
* @param input the {@link Artifact} the symlink will point to
* @param output the {@link Artifact} that will be created by executing this Action.
* @param progressMessage the progress message.
*/
public static SymlinkAction toArtifact(ActionOwner owner, Artifact input, Artifact output,
String progressMessage) {
return new SymlinkAction(owner, null, input, output, progressMessage, TargetType.OTHER);
}
public static SymlinkAction toExecutable(
ActionOwner owner, Artifact input, Artifact output, String progressMessage) {
return new SymlinkAction(owner, null, input, output, progressMessage, TargetType.EXECUTABLE);
}
@VisibleForSerialization
@AutoCodec.Instantiator
SymlinkAction(
ActionOwner owner,
PathFragment inputPath,
Artifact primaryInput,
Artifact primaryOutput,
String progressMessage,
TargetType targetType) {
super(
owner,
primaryInput != null
? NestedSetBuilder.create(Order.STABLE_ORDER, primaryInput)
: NestedSetBuilder.emptySet(Order.STABLE_ORDER),
ImmutableSet.of(primaryOutput));
this.inputPath = inputPath;
this.progressMessage = progressMessage;
this.targetType = targetType;
}
/**
* Creates a symlink to a Fileset.
*
* <p>This is different from a regular {@link SymlinkAction} in that the target is in the output
* tree but not an artifact and that when running this action, the mtime of its target is updated
* (necessary because dependency checking of Filesets is unsound). For more information, see the
* Javadoc of {@code TargetType.FILESET}.
*
* <p><b>WARNING:</b>Do not use this for anything else other than Filesets. If you do, your
* correctness will depend on a subtle interaction between various parts of Blaze.
*
* @param owner the action owner.
* @param execPath where the symlink will point to
* @param primaryInput the {@link Artifact} that is required to build the inputPath.
* @param primaryOutput the {@link Artifact} that will be created by executing this Action.
* @param progressMessage the progress message.
*/
public static SymlinkAction toFileset(
ActionOwner owner,
PathFragment execPath,
Artifact primaryInput,
Artifact primaryOutput,
String progressMessage) {
Preconditions.checkState(!execPath.isAbsolute());
return new SymlinkAction(
owner, execPath, primaryInput, primaryOutput, progressMessage, TargetType.FILESET);
}
public static SymlinkAction createUnresolved(
ActionOwner owner, Artifact primaryOutput, PathFragment targetPath, String progressMessage) {
Preconditions.checkArgument(primaryOutput.isSymlink());
return new SymlinkAction(
owner, targetPath, null, primaryOutput, progressMessage, TargetType.OTHER);
}
/**
* Creates a new SymlinkAction instance, where an input artifact is not present. This is useful
* when dealing with special cases where input paths that are outside the exec root directory
* tree. Currently, the only instance where this happens is for FDO builds where the profile file
* is outside the exec root structure.
*
* <p>Do <b>NOT</b> use this method unless there is no other way; unconditionally executed actions
* are costly: even if change pruning kicks in and downstream actions are not re-executed, they
* trigger unconditional Skyframe invalidation of their reverse dependencies.
*
* @param owner the action owner.
* @param absolutePath where the symlink will point to
* @param output the Artifact that will be created by executing this Action.
* @param progressMessage the progress message.
*/
public static SymlinkAction toAbsolutePath(ActionOwner owner, PathFragment absolutePath,
Artifact output, String progressMessage) {
Preconditions.checkState(absolutePath.isAbsolute());
return new SymlinkAction(owner, absolutePath, null, output, progressMessage, TargetType.OTHER);
}
public PathFragment getInputPath() {
return inputPath == null ? getPrimaryInput().getExecPath() : inputPath;
}
public Path getOutputPath(ActionExecutionContext actionExecutionContext) {
return actionExecutionContext.getInputPath(getPrimaryOutput());
}
@Override
public ActionResult execute(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException {
maybeVerifyTargetIsExecutable(actionExecutionContext);
Path srcPath;
if (inputPath == null) {
srcPath = actionExecutionContext.getInputPath(getPrimaryInput());
} else {
srcPath = actionExecutionContext.getExecRoot().getRelative(inputPath);
}
try {
getOutputPath(actionExecutionContext).createSymbolicLink(srcPath);
} catch (IOException e) {
String message =
String.format(
"failed to create symbolic link '%s' to '%s' due to I/O error: %s",
Iterables.getOnlyElement(getOutputs()).prettyPrint(), printInputs(), e.getMessage());
DetailedExitCode code = createDetailedExitCode(message, Code.LINK_CREATION_IO_EXCEPTION);
throw new ActionExecutionException(message, e, this, false, code);
}
updateInputMtimeIfNeeded(actionExecutionContext);
return ActionResult.EMPTY;
}
private void maybeVerifyTargetIsExecutable(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException {
if (targetType != TargetType.EXECUTABLE) {
return;
}
Path inputPath = actionExecutionContext.getInputPath(getPrimaryInput());
try {
// Validate that input path is a file with the executable bit set.
if (!inputPath.isFile()) {
String message =
String.format("'%s' is not a file", getInputs().getSingleton().prettyPrint());
throw new ActionExecutionException(
message, this, false, createDetailedExitCode(message, Code.EXECUTABLE_INPUT_NOT_FILE));
}
if (!inputPath.isExecutable()) {
String message =
String.format(
"failed to create symbolic link '%s': file '%s' is not executable",
Iterables.getOnlyElement(getOutputs()).prettyPrint(),
getInputs().getSingleton().prettyPrint());
throw new ActionExecutionException(
message, this, false, createDetailedExitCode(message, Code.EXECUTABLE_INPUT_IS_NOT));
}
} catch (IOException e) {
String message =
String.format(
"failed to create symbolic link '%s' to the '%s' due to I/O error: %s",
Iterables.getOnlyElement(getOutputs()).prettyPrint(),
getInputs().getSingleton().prettyPrint(),
e.getMessage());
DetailedExitCode detailedExitCode =
createDetailedExitCode(message, Code.EXECUTABLE_INPUT_CHECK_IO_EXCEPTION);
throw new ActionExecutionException(message, e, this, false, detailedExitCode);
}
}
private void updateInputMtimeIfNeeded(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException {
if (targetType != TargetType.FILESET) {
return;
}
try {
// Update the mtime of the target of the symlink to force downstream re-execution of actions.
// This is needed because dependency checking of Fileset output trees is unsound (it's a
// directory).
// Note that utime() on a symlink actually changes the mtime of its target.
Path linkPath = getOutputPath(actionExecutionContext);
if (linkPath.exists()) {
// -1L means "use the current time".
linkPath.setLastModifiedTime(-1L);
} else {
// Should only happen if the Fileset included no links.
actionExecutionContext.getExecRoot().getRelative(getInputPath()).createDirectory();
}
} catch (IOException e) {
String message =
String.format(
"failed to touch symbolic link '%s' to the '%s' due to I/O error: %s",
Iterables.getOnlyElement(getOutputs()).prettyPrint(),
getInputs().getSingleton().prettyPrint(),
e.getMessage());
DetailedExitCode code = createDetailedExitCode(message, Code.LINK_TOUCH_IO_EXCEPTION);
throw new ActionExecutionException(message, e, this, false, code);
}
}
private String printInputs() {
if (getInputs().isEmpty()) {
return inputPath.getPathString();
} else if (getInputs().isSingleton()) {
return getInputs().getSingleton().prettyPrint();
} else {
throw new IllegalStateException(
"Inputs unexpectedly contains more than 1 element: " + getInputs());
}
}
@Override
protected void computeKey(
ActionKeyContext actionKeyContext,
@Nullable ArtifactExpander artifactExpander,
Fingerprint fp) {
fp.addString(GUID);
// We don't normally need to add inputs to the key. In this case, however, the inputPath can be
// different from the actual input artifact.
if (inputPath != null) {
fp.addPath(inputPath);
}
}
@Override
public String getMnemonic() {
return targetType == TargetType.EXECUTABLE ? "ExecutableSymlink" : "Symlink";
}
@Override
public boolean isVolatile() {
return inputPath != null && inputPath.isAbsolute();
}
@Override
public boolean executeUnconditionally() {
// If the SymlinkAction points to an absolute path, we can't verify that its output artifact did
// not change purely by looking at the output tree. Thus, we re-execute the action just to be
// safe. Change pruning will take care of not re-running dependent actions and this is used only
// in very rare cases (only C++ FDO and even then, only twice per build at most) anyway.
return inputPath != null && inputPath.isAbsolute();
}
@Override
protected String getRawProgressMessage() {
return progressMessage;
}
@Override
public boolean mayInsensitivelyPropagateInputs() {
return true;
}
private static DetailedExitCode createDetailedExitCode(String message, Code detailedCode) {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(message)
.setSymlinkAction(FailureDetails.SymlinkAction.newBuilder().setCode(detailedCode))
.build());
}
}
| |
/*
* 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.oodt.cas.crawl.typedetection;
import org.apache.oodt.cas.crawl.structs.exceptions.CrawlerActionException;
import org.apache.oodt.cas.metadata.exceptions.MetExtractionException;
import org.apache.oodt.cas.metadata.util.PathUtils;
import org.apache.oodt.commons.xml.XMLUtils;
import com.google.common.base.Strings;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
//JDK imports
//W3C imports
//Google imports
/**
* Static reader class for {@link MimeExtractor}s.
*
* @author mattmann (Chris Mattmann)
* @author bfoster (Brian Foster)
*/
public final class MimeExtractorConfigReader implements
MimeExtractorConfigMetKeys {
private static Logger LOG = Logger.getLogger(MimeExtractorConfigReader.class.getName());
private MimeExtractorConfigReader() throws InstantiationException {
throw new InstantiationException("Don't construct reader classes!");
}
public static MimeExtractorRepo read(String mapFilePath)
throws ClassNotFoundException, FileNotFoundException, MetExtractionException, InstantiationException,
IllegalAccessException, CrawlerActionException {
try {
Document doc = XMLUtils.getDocumentRoot(new FileInputStream(
mapFilePath));
Element root = doc.getDocumentElement();
MimeExtractorRepo extractorRepo = new MimeExtractorRepo();
extractorRepo.setMagic(Boolean.valueOf(
root.getAttribute(MAGIC_ATTR)));
String mimeTypeFile = PathUtils.replaceEnvVariables(root
.getAttribute(MIME_REPO_ATTR));
if (!mimeTypeFile.startsWith("/")) {
mimeTypeFile = new File(new File(mapFilePath).getParentFile(),
mimeTypeFile).getAbsolutePath();
}
extractorRepo.setMimeRepoFile(mimeTypeFile);
Element defaultExtractorElem = XMLUtils.getFirstElement(
DEFAULT_EXTRACTOR_TAG, root);
if (defaultExtractorElem != null) {
NodeList defaultExtractorElems = defaultExtractorElem
.getElementsByTagName(EXTRACTOR_TAG);
LinkedList<MetExtractorSpec> defaultExtractorSpecs = new LinkedList<MetExtractorSpec>();
for (int i = 0; i < defaultExtractorElems.getLength(); i++) {
Element extractorElem = (Element) defaultExtractorElems
.item(i);
Element preCondsElem = XMLUtils.getFirstElement(
PRECONDITION_COMPARATORS_TAG, extractorElem);
LinkedList<String> preCondComparatorIds = new LinkedList<String>();
if (preCondsElem != null) {
NodeList preCondComparators =
preCondsElem.getElementsByTagName(PRECONDITION_COMPARATOR_TAG);
for (int k = 0; k < preCondComparators.getLength(); k++) {
preCondComparatorIds.add(((Element) preCondComparators
.item(k)).getAttribute(ID_ATTR));
}
}
// This seems wrong, so added support for CLASS_ATTR while still
// supporting EXTRACTOR_CLASS_TAG as an attribute for specifying
// extractor class.
String extractorClass = extractorElem.getAttribute(CLASS_ATTR);
if (Strings.isNullOrEmpty(extractorClass)) {
extractorClass = extractorElem.getAttribute(EXTRACTOR_CLASS_TAG);
}
String extractorConfigFile = getFilePathFromElement(
extractorElem, EXTRACTOR_CONFIG_TAG);
if (extractorConfigFile != null && !extractorConfigFile.startsWith("/")) {
extractorConfigFile = new File(new File(mapFilePath).getParentFile(),
extractorConfigFile).getAbsolutePath();
}
defaultExtractorSpecs
.add(new MetExtractorSpec(extractorClass,
extractorConfigFile,
preCondComparatorIds));
}
extractorRepo
.setDefaultMetExtractorSpecs(defaultExtractorSpecs);
extractorRepo.setDefaultNamingConventionId(
getNamingConventionId(defaultExtractorElem));
}
NodeList mimeElems = root.getElementsByTagName(MIME_TAG);
for (int i = 0; i < mimeElems.getLength(); i++) {
Element mimeElem = (Element) mimeElems.item(i);
String mimeType = mimeElem.getAttribute(MIME_TYPE_ATTR);
LinkedList<MetExtractorSpec> specs = new LinkedList<MetExtractorSpec>();
// Load naming convention class.
extractorRepo.setNamingConventionId(mimeType,
getNamingConventionId(mimeElem));
NodeList extractorSpecElems = mimeElem
.getElementsByTagName(EXTRACTOR_TAG);
if (extractorSpecElems != null
&& extractorSpecElems.getLength() > 0) {
for (int j = 0; j < extractorSpecElems.getLength(); j++) {
Element extractorSpecElem = (Element) extractorSpecElems
.item(j);
MetExtractorSpec spec = new MetExtractorSpec();
spec.setMetExtractor(extractorSpecElem
.getAttribute(CLASS_ATTR));
// get config file if specified
String configFilePath = getFilePathFromElement(
extractorSpecElem, EXTRACTOR_CONFIG_TAG);
if (configFilePath != null) {
if (!configFilePath.startsWith("/")) {
configFilePath = new File(new File(mapFilePath).getParentFile(),
configFilePath).getAbsolutePath();
}
spec.setExtractorConfigFile(configFilePath);
}
// get preconditions file if specified
Element preCondsElem = XMLUtils.getFirstElement(
PRECONDITION_COMPARATORS_TAG, extractorSpecElem);
if (preCondsElem != null) {
NodeList preCondComparators = preCondsElem
.getElementsByTagName(PRECONDITION_COMPARATOR_TAG);
LinkedList<String> preCondComparatorIds = new LinkedList<String>();
for (int k = 0; k < preCondComparators.getLength(); k++) {
preCondComparatorIds
.add(((Element) preCondComparators.item(k))
.getAttribute(ID_ATTR));
}
spec.setPreConditionComparatorIds(preCondComparatorIds);
}
specs.add(spec);
}
}
extractorRepo.addMetExtractorSpecs(mimeType, specs);
}
return extractorRepo;
} catch (IllegalAccessException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
} catch (InstantiationException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
} catch (MetExtractionException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
} catch (FileNotFoundException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
} catch (CrawlerActionException e) {
LOG.log(Level.SEVERE, e.getMessage());
throw e;
}
}
private static String getNamingConventionId(Element parent) throws CrawlerActionException {
NodeList namingConventions = parent
.getElementsByTagName(NAMING_CONVENTION_TAG);
if (namingConventions != null && namingConventions.getLength() > 0) {
if (namingConventions.getLength() > 1) {
throw new CrawlerActionException("Can only have 1 '"
+ NAMING_CONVENTION_TAG + "' tag per mimetype");
}
Element namingConvention = (Element) namingConventions.item(0);
return namingConvention.getAttribute(ID_ATTR);
}
return null;
}
private static String getFilePathFromElement(Element root, String elemName) {
String filePath = null;
Element elem = XMLUtils.getFirstElement(elemName, root);
if (elem != null) {
filePath = elem.getAttribute(FILE_ATTR);
if (Boolean.valueOf(elem.getAttribute(ENV_REPLACE_ATTR))) {
filePath = PathUtils.replaceEnvVariables(filePath);
}
}
return filePath;
}
}
| |
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.iacuc.actions;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kuali.kra.bo.CoeusModule;
import org.kuali.kra.bo.CoeusSubModule;
import org.kuali.kra.common.notification.bo.NotificationTypeRecipient;
import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.iacuc.IacucProtocolDocument;
import org.kuali.kra.iacuc.IacucProtocolForm;
import org.kuali.kra.iacuc.actions.abandon.IacucProtocolAbandonService;
import org.kuali.kra.iacuc.actions.amendrenew.CreateIacucAmendmentEvent;
import org.kuali.kra.iacuc.actions.amendrenew.CreateIacucContinuationEvent;
import org.kuali.kra.iacuc.actions.amendrenew.CreateIacucRenewalEvent;
import org.kuali.kra.iacuc.actions.amendrenew.IacucProtocolAmendRenewService;
import org.kuali.kra.iacuc.actions.amendrenew.IacucProtocolAmendmentBean;
import org.kuali.kra.iacuc.actions.approve.IacucProtocolApproveBean;
import org.kuali.kra.iacuc.actions.approve.IacucProtocolApproveEvent;
import org.kuali.kra.iacuc.actions.approve.IacucProtocolApproveService;
import org.kuali.kra.iacuc.actions.assignCmt.IacucProtocolAssignCmtBean;
import org.kuali.kra.iacuc.actions.assignCmt.IacucProtocolAssignCmtEvent;
import org.kuali.kra.iacuc.actions.assignCmt.IacucProtocolAssignCmtService;
import org.kuali.kra.iacuc.actions.assignagenda.IacucProtocolAssignToAgendaBean;
import org.kuali.kra.iacuc.actions.assignagenda.IacucProtocolAssignToAgendaEvent;
import org.kuali.kra.iacuc.actions.assignagenda.IacucProtocolAssignToAgendaService;
import org.kuali.kra.iacuc.actions.correction.IacucAdminCorrectionBean;
import org.kuali.kra.iacuc.actions.correction.IacucProtocolAdminCorrectionEvent;
import org.kuali.kra.iacuc.actions.decision.IacucCommitteeDecision;
import org.kuali.kra.iacuc.actions.decision.IacucCommitteeDecisionEvent;
import org.kuali.kra.iacuc.actions.decision.IacucCommitteeDecisionService;
import org.kuali.kra.iacuc.actions.genericactions.IacucProtocolGenericActionBean;
import org.kuali.kra.iacuc.actions.genericactions.IacucProtocolGenericActionEvent;
import org.kuali.kra.iacuc.actions.genericactions.IacucProtocolGenericActionService;
import org.kuali.kra.iacuc.actions.modifysubmission.IacucProtocolModifySubmissionBean;
import org.kuali.kra.iacuc.actions.modifysubmission.IacucProtocolModifySubmissionEvent;
import org.kuali.kra.iacuc.actions.modifysubmission.IacucProtocolModifySubmissionService;
import org.kuali.kra.iacuc.actions.noreview.IacucProtocolReviewNotRequiredBean;
import org.kuali.kra.iacuc.actions.noreview.IacucProtocolReviewNotRequiredEvent;
import org.kuali.kra.iacuc.actions.noreview.IacucProtocolReviewNotRequiredService;
import org.kuali.kra.iacuc.actions.notifyiacuc.IacucProtocolNotifyIacucService;
import org.kuali.kra.iacuc.actions.notifyiacuc.NotifyIacucNotificationRenderer;
import org.kuali.kra.iacuc.actions.request.IacucProtocolRequestBean;
import org.kuali.kra.iacuc.actions.request.IacucProtocolRequestEvent;
import org.kuali.kra.iacuc.actions.request.IacucProtocolRequestRule;
import org.kuali.kra.iacuc.actions.request.IacucProtocolRequestService;
import org.kuali.kra.iacuc.actions.reviewcomments.IacucReviewCommentsBean;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolActionService;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolReviewType;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolReviewerBean;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmission;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmissionStatus;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmissionType;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmitAction;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmitActionService;
import org.kuali.kra.iacuc.actions.table.IacucProtocolTableBean;
import org.kuali.kra.iacuc.actions.table.IacucProtocolTableService;
import org.kuali.kra.iacuc.actions.withdraw.IacucProtocolWithdrawService;
import org.kuali.kra.iacuc.auth.IacucGenericProtocolAuthorizer;
import org.kuali.kra.iacuc.auth.IacucProtocolTask;
import org.kuali.kra.iacuc.correspondence.IacucProtocolActionsCorrespondence;
import org.kuali.kra.iacuc.correspondence.IacucProtocolCorrespondence;
import org.kuali.kra.iacuc.infrastructure.IacucConstants;
import org.kuali.kra.iacuc.notification.IacucProtocolAssignReviewerNotificationRenderer;
import org.kuali.kra.iacuc.notification.IacucProtocolNotification;
import org.kuali.kra.iacuc.notification.IacucProtocolNotificationContext;
import org.kuali.kra.iacuc.notification.IacucProtocolNotificationRenderer;
import org.kuali.kra.iacuc.notification.IacucProtocolNotificationRequestBean;
import org.kuali.kra.iacuc.notification.IacucProtocolRequestActionNotificationRenderer;
import org.kuali.kra.iacuc.notification.IacucProtocolReviewDeterminationNotificationRenderer;
import org.kuali.kra.iacuc.notification.IacucProtocolWithReasonNotificationRenderer;
import org.kuali.kra.iacuc.notification.IacucRequestActionNotificationBean;
import org.kuali.kra.iacuc.onlinereview.IacucProtocolOnlineReview;
import org.kuali.kra.iacuc.questionnaire.IacucProtocolModuleQuestionnaireBean;
import org.kuali.kra.iacuc.questionnaire.IacucProtocolQuestionnaireAuditRule;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.ProtocolDocumentBase;
import org.kuali.kra.protocol.ProtocolFormBase;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.actions.ProtocolActionBean;
import org.kuali.kra.protocol.actions.ProtocolActionRequestServiceImpl;
import org.kuali.kra.protocol.actions.ProtocolActionTypeBase;
import org.kuali.kra.protocol.actions.correction.AdminCorrectionBean;
import org.kuali.kra.protocol.actions.correspondence.ProtocolActionsCorrespondenceBase;
import org.kuali.kra.protocol.actions.submit.ProtocolReviewerBeanBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase;
import org.kuali.kra.protocol.auth.ProtocolTaskBase;
import org.kuali.kra.protocol.correspondence.ProtocolCorrespondence;
import org.kuali.kra.protocol.notification.ProtocolNotification;
import org.kuali.kra.protocol.notification.ProtocolNotificationContextBase;
import org.kuali.kra.protocol.notification.ProtocolNotificationRequestBeanBase;
import org.kuali.kra.protocol.questionnaire.ProtocolQuestionnaireAuditRuleBase;
import org.kuali.kra.questionnaire.answer.AnswerHeader;
import org.kuali.kra.questionnaire.answer.ModuleQuestionnaireBean;
import org.kuali.rice.kns.document.authorization.DocumentAuthorizerBase;
import org.kuali.rice.kns.util.WebUtils;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;
import org.springframework.util.CollectionUtils;
public class IacucProtocolActionRequestServiceImpl extends ProtocolActionRequestServiceImpl implements IacucProtocolActionRequestService {
private static final Log LOG = LogFactory.getLog(IacucProtocolActionRequestServiceImpl.class);
// map to decide the followup action page to open. "value" part is the action tab "title"
private static Map<String, String> motionTypeMap = new HashMap<String, String>() {
{
put("1", "Approve Action");
put("2", "Disapprove");
put("3", "Return for Specific Minor Revisions");
put("4", "Return for Substantive Revisions Required");
}
};
protected static List <String> requestSubmissionTypes = Arrays.asList(new String[] {IacucProtocolSubmissionType.REQUEST_SUSPEND,
IacucProtocolSubmissionType.REQUEST_TO_LIFT_HOLD,
IacucProtocolSubmissionType.REQUEST_TO_DEACTIVATE});
private IacucProtocolApproveService protocolApproveService;
private IacucProtocolSubmitActionService protocolSubmitActionService;
private IacucProtocolAmendRenewService protocolAmendRenewService;
private IacucProtocolAssignToAgendaService protocolAssignToAgendaService;
private IacucProtocolReviewNotRequiredService protocolReviewNotRequiredService;
private IacucProtocolRequestService protocolRequestService;
private IacucProtocolGenericActionService protocolGenericActionService;
private IacucProtocolAbandonService protocolAbandonService;
private IacucProtocolModifySubmissionService modifySubmissionService;
private IacucProtocolTableService protocolTableService;
private IacucProtocolWithdrawService protocolWithdrawService;
private IacucProtocolNotifyIacucService protocolNotifyService;
private IacucCommitteeDecisionService committeeDecisionService;
private IacucProtocolAssignCmtService assignToCmtService;
private IacucProtocolActionService protocolActionService;
private static final String ACTION_NAME_CONTINUATION_WITHOUT_AMENDMENT = "Create Continuation without Amendment";
private static final String ACTION_NAME_CONTINUATION_WITH_AMENDMENT = "Create Continuation with Amendment";
private static final String ACTION_NAME_REMOVE_FROM_AGENDA = "Removed Agenda";
private static final String ACTION_NAME_ACKNOWLEDGEMENT = "IACUC Acknowledgement";
private static final String ACTION_NAME_HOLD = "IACUC Hold";
private static final String ACTION_NAME_LIFT_HOLD = "IACUC Lift Hold";
private static final String ACTION_NAME_DEACTIVATED = "Deactivated";
private static final String ACTION_NAME_MODIFY_SUBMISSION = "Modify Submission";
private static final String ACTION_NAME_TABLE_PROTOCOL = "Table ProtocolBase";
private static final String ACTION_NAME_ADMINISTRATIVELY_WITHDRAW = "Administratively Withdraw";
private static final String ACTION_NAME_NOTIFY = "Notify IACUC";
private static final String ACTION_NAME_REVIEW_TYPE_DETERMINATION = "Send Review Type Determination Notification";
private static final String ACTION_NAME_ADMINISTRATIVELY_INCOMPLETE = "Administratively Mark Incomplete";
private static final String ACTION_NAME_ASSIGN_TO_COMMITTEE = "Assign to Committee";
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isFullApprovalAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isFullApprovalAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocolApproveBean actionBean = (IacucProtocolApproveBean) protocolForm.getActionHelper().getProtocolFullApprovalBean();
if (hasPermission(TaskName.APPROVE_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolApproveEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isCreateAmendmentAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isCreateAmendmentAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolAmendmentBean protocolAmendmentBean = (IacucProtocolAmendmentBean) protocolForm.getActionHelper().getProtocolAmendmentBean();
if (hasPermission(TaskName.CREATE_IACUC_PROTOCOL_AMENDMENT, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new CreateIacucAmendmentEvent(document, Constants.PROTOCOL_CREATE_AMENDMENT_KEY, protocolAmendmentBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isCreateRenewalAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isCreateRenewalAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
String renewalSummary = protocolForm.getActionHelper().getRenewalSummary();
if (hasPermission(TaskName.CREATE_IACUC_PROTOCOL_RENEWAL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new CreateIacucRenewalEvent(document, Constants.PROTOCOL_CREATE_RENEWAL_SUMMARY_KEY, renewalSummary));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isCreateRenewalWithAmendmentAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isCreateRenewalWithAmendmentAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolAmendmentBean renewAmendmentBean = (IacucProtocolAmendmentBean)protocolForm.getActionHelper().getProtocolRenewAmendmentBean();
if (hasPermission(TaskName.CREATE_IACUC_PROTOCOL_RENEWAL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new CreateIacucAmendmentEvent(document, Constants.PROTOCOL_CREATE_RENEWAL_WITH_AMENDMENT_KEY, renewAmendmentBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isCreateContinuationAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isCreateContinuationAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
String continuationSummary = actionHelper.getContinuationSummary();
if (hasPermission(TaskName.CREATE_IACUC_PROTOCOL_CONTINUATION, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new CreateIacucContinuationEvent(document, Constants.PROTOCOL_CREATE_CONTINUATION_SUMMARY_KEY, continuationSummary));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isCreateContinuationWithAmendmentAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isCreateContinuationWithAmendmentAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolAmendmentBean continuationAmendmentBean = (IacucProtocolAmendmentBean)actionHelper.getProtocolContinuationAmendmentBean();
if (hasPermission(TaskName.CREATE_IACUC_PROTOCOL_CONTINUATION, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new CreateIacucAmendmentEvent(document, Constants.PROTOCOL_CREATE_CONTINUATION_WITH_AMENDMENT_KEY, continuationAmendmentBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAssignToAgendaAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAssignToAgendaAuthorized(IacucProtocolForm protocolForm) {
// set the task name to prevent entered data from being overwritten (in case of user errors) due to bean refresh in the action helper's prepare view
protocolForm.getActionHelper().setCurrentTask(TaskName.ASSIGN_TO_AGENDA);
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
IacucProtocolAssignToAgendaBean actionBean = (IacucProtocolAssignToAgendaBean) protocolForm.getActionHelper().getAssignToAgendaBean();
if (!hasDocumentStateChanged(protocolForm)) {
if (hasPermission(TaskName.ASSIGN_TO_AGENDA, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolAssignToAgendaEvent(document, actionBean));
actionBean.prepareView();
}
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isRemoveFromAgendaAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isRemoveFromAgendaAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
requestAuthorized = hasPermission(TaskName.REMOVE_FROM_AGENDA, (IacucProtocol) document.getProtocol());
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isProtocolReviewNotRequiredAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isProtocolReviewNotRequiredAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolReviewNotRequiredBean actionBean = (IacucProtocolReviewNotRequiredBean) actionHelper.getProtocolReviewNotRequiredBean();
if (hasPermission(TaskName.REVIEW_NOT_REQUIRED_IACUC_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolReviewNotRequiredEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isGrantAdminApprovalAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isGrantAdminApprovalAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolApproveBean actionBean = (IacucProtocolApproveBean) protocolForm.getActionHelper().getProtocolAdminApprovalBean();
if (hasPermission(TaskName.ADMIN_APPROVE_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolApproveEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isRequestActionAuthorized(org.kuali.kra.iacuc.IacucProtocolForm, java.lang.String)
*/
public boolean isRequestActionAuthorized(IacucProtocolForm protocolForm, String taskName) {
boolean requestAuthorized = false;
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
if (StringUtils.isNotBlank(taskName)) {
requestAuthorized = hasPermission(taskName, (IacucProtocol) document.getProtocol());
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isDisapproveProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isDisapproveProtocolAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolDisapproveBean();
if (hasPermission(TaskName.DISAPPROVE_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isTerminateProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isTerminateProtocolAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolTerminateBean();
if (hasGenericPermission(IacucGenericProtocolAuthorizer.TERMINATE_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isExpireProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isExpireProtocolAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolExpireBean();
if (hasGenericPermission(IacucGenericProtocolAuthorizer.EXPIRE_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isSuspendProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isSuspendProtocolAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSuspendBean();
if (hasGenericPermission(IacucGenericProtocolAuthorizer.SUSPEND_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAcknowledgementAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAcknowledgementAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucAcknowledgeBean();
if (hasPermission(TaskName.IACUC_ACKNOWLEDGEMENT, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isHoldAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isHoldAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolHoldBean();
if (hasPermission(TaskName.IACUC_PROTOCOL_HOLD, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isLiftHoldAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isLiftHoldAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolLiftHoldBean();
if (hasPermission(TaskName.IACUC_PROTOCOL_LIFT_HOLD, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isReturnForSMRAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isReturnForSMRAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSMRBean();
if (hasPermission(TaskName.RETURN_FOR_SMR, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isReturnForSRRAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isReturnForSRRAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSRRBean();
if (hasPermission(TaskName.RETURN_FOR_SRR, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isReturnToPIAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isReturnToPIAuthorized(IacucProtocolForm protocolForm) {
boolean requestAuthorized = false;
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolReturnToPIBean();
if (hasPermission(TaskName.RETURN_TO_PI_PROTOCOL, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isDeactivateAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isDeactivateAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
if (hasPermission(TaskName.IACUC_PROTOCOL_DEACTIVATE, (IacucProtocol) document.getProtocol())) {
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolGenericActionBean actionBean = actionHelper.getIacucProtocolDeactivateBean();
requestAuthorized = applyRules(new IacucProtocolGenericActionEvent(document, actionBean));
}
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isOpenProtocolForAdminCorrectionAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isOpenProtocolForAdminCorrectionAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
AdminCorrectionBean actionBean = (AdminCorrectionBean)protocolForm.getActionHelper().getProtocolAdminCorrectionBean();
if (!hasDocumentStateChanged(protocolForm)) {
if (hasPermission(TaskName.IACUC_PROTOCOL_ADMIN_CORRECTION, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolAdminCorrectionEvent(document, Constants.PROTOCOL_ADMIN_CORRECTION_PROPERTY_KEY,actionBean));
}
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAbandonAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAbandonAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
requestAuthorized = hasPermission(TaskName.IACUC_ABANDON_PROTOCOL, (IacucProtocol) document.getProtocol());
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isModifySubmissionActionAuthorized(org.kuali.kra.iacuc.IacucProtocolForm, java.util.List)
*/
public boolean isModifySubmissionActionAuthorized(IacucProtocolForm protocolForm, List<ProtocolReviewerBeanBase> reviewers) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
IacucProtocolModifySubmissionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolModifySubmissionBean();
if (!hasDocumentStateChanged(protocolForm)) {
if (hasPermission(TaskName.IACUC_MODIFY_PROTOCOL_SUBMISSION, (IacucProtocol) document.getProtocol())) {
actionBean.setReviewers(reviewers);
requestAuthorized = applyRules(new IacucProtocolModifySubmissionEvent(document, actionBean));
actionBean.prepareView();
}
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isTableProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isTableProtocolAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
requestAuthorized = hasPermission(TaskName.IACUC_PROTOCOL_TABLE, (IacucProtocol) document.getProtocol());
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAdministrativelyWithdrawProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAdministrativelyWithdrawProtocolAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
requestAuthorized = hasPermission(TaskName.ADMIN_WITHDRAW_PROTOCOL, (IacucProtocol) document.getProtocol());
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isWithdrawProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isWithdrawProtocolAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
requestAuthorized = hasPermission(TaskName.PROTOCOL_WITHDRAW, (IacucProtocol) document.getProtocol());
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAdministrativelyMarkIncompleteProtocolAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAdministrativelyMarkIncompleteProtocolAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
requestAuthorized = hasPermission(TaskName.ADMIN_INCOMPLETE_PROTOCOL, (IacucProtocol) document.getProtocol());
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isSubmitCommitteeDecisionAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isSubmitCommitteeDecisionAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
if (!hasDocumentStateChanged(protocolForm)) {
IacucCommitteeDecision actionBean = (IacucCommitteeDecision) protocolForm.getActionHelper().getCommitteeDecision();
requestAuthorized = applyRules(new IacucCommitteeDecisionEvent(document, actionBean));
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isAssignCommitteeAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isAssignCommitteeAuthorized(IacucProtocolForm protocolForm) {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
boolean requestAuthorized = false;
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolAssignCmtBean actionBean = actionHelper.getProtocolAssignCmtBean();
if (!hasDocumentStateChanged(protocolForm)) {
if (hasPermission(TaskName.IACUC_ASSIGN_TO_COMMITTEE, (IacucProtocol) document.getProtocol())) {
requestAuthorized = applyRules(new IacucProtocolAssignCmtEvent(document, actionBean));
}
} else {
updateDocumentStatusChangedMessage();
}
return requestAuthorized;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#isWithdrawRequestActionAuthorized(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public boolean isWithdrawRequestActionAuthorized(IacucProtocolForm protocolForm) {
return hasPermission(TaskName.IACUC_WITHDRAW_SUBMISSION, protocolForm.getProtocolDocument().getProtocol());
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#grantFullApproval(org.kuali.kra.iacuc.IacucProtocolForm)
*/
@SuppressWarnings("deprecation")
public void grantFullApproval(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = document.getIacucProtocol();
IacucProtocolApproveBean actionBean = (IacucProtocolApproveBean) protocolForm.getActionHelper().getProtocolFullApprovalBean();
getProtocolApproveService().grantFullApproval(protocol, actionBean);
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
IacucProtocolSubmission submission = (IacucProtocolSubmission)protocol.getProtocolSubmission();
String actionType;
String actionDescription;
String actionDescription2;
if (StringUtils.equals(submission.getProtocolReviewTypeCode(),IacucProtocolReviewType.DESIGNATED_MEMBER_REVIEW)) {
actionType = IacucProtocolActionType.DESIGNATED_REVIEW_APPROVAL;
actionDescription = "Designated Member Approval";
actionDescription2 = "Designated Member Approved";
}
else {
actionType = IacucProtocolActionType.IACUC_APPROVED;
actionDescription = "Full Approval";
actionDescription2 = "Approved";
}
generateActionCorrespondence(actionType, protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(actionDescription);
protocolForm.getProtocolHelper().prepareView();
if (protocolForm.getActionHelper().getProtocolCorrespondence() != null) {
GlobalVariables.getUserSession().addObject("approvalComplCorrespondence", GlobalVariables.getUserSession().retrieveObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY));
// temporarily remove this key which is generated by super.approve
GlobalVariables.getUserSession().removeObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY);
} else {
IacucProtocolNotificationRenderer renderer = new IacucProtocolNotificationRenderer((IacucProtocol) document.getProtocol());
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext((IacucProtocol) document.getProtocol(), actionType, actionDescription2, renderer);
getNotificationService().sendNotificationAndPersist(context, new IacucProtocolNotification(), protocol);
}
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#submitForReview(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public void submitForReview(IacucProtocolForm protocolForm, List<ProtocolReviewerBeanBase> reviewers) throws Exception {
IacucProtocolDocument protocolDocument = protocolForm.getIacucProtocolDocument();
IacucProtocol protocol = protocolDocument.getIacucProtocol();
IacucProtocolSubmitAction submitAction = (IacucProtocolSubmitAction) protocolForm.getActionHelper().getProtocolSubmitAction();
submitAction.setReviewers(reviewers);
getProtocolSubmitActionService().submitToIacucForReview(protocol, submitAction);
generateActionCorrespondence(IacucProtocolActionType.SUBMITTED_TO_IACUC, protocolForm.getProtocolDocument().getProtocol());
// first, send out notification that protocol has been submitted
IacucProtocolNotificationRenderer submitRenderer = new IacucProtocolNotificationRenderer(protocol);
IacucProtocolNotificationContext submitContext = new IacucProtocolNotificationContext(protocol, null,
IacucProtocolActionType.SUBMITTED_TO_IACUC, "Submit", submitRenderer);
getNotificationService().sendNotificationAndPersist(submitContext, new IacucProtocolNotification(), protocol);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#createAmendment(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String createAmendment(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
String newDocId = getProtocolAmendRenewService().createAmendment(protocolForm.getProtocolDocument(), protocolForm.getActionHelper().getProtocolAmendmentBean());
generateActionCorrespondence(IacucProtocolActionType.AMENDMENT_CREATED, protocolForm.getProtocolDocument().getProtocol());
refreshAfterProtocolAction(protocolForm, newDocId, ACTION_NAME_AMENDMENT, true);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.AMENDMENT_CREATED_NOTIFICATION, "Amendment Created");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#createRenewal(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String createRenewal(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
String newDocId = getProtocolAmendRenewService().createRenewal(protocolForm.getProtocolDocument(),protocolForm.getActionHelper().getRenewalSummary());
generateActionCorrespondence(IacucProtocolActionType.RENEWAL_CREATED, protocolForm.getProtocolDocument().getProtocol());
refreshAfterProtocolAction(protocolForm, newDocId, ACTION_NAME_RENEWAL_WITHOUT_AMENDMENT, true);
// Form fields copy needed to support modifyAmendmentSections
protocolForm.getActionHelper().getProtocolAmendmentBean().setSummary(protocolForm.getActionHelper().getRenewalSummary());
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.RENEWAL_CREATED_NOTIFICATION, "Renewal Created");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#createRenewalWithAmendment(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String createRenewalWithAmendment(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
IacucProtocolDocument protocolDocument = protocolForm.getIacucProtocolDocument();
IacucProtocolAmendmentBean renewAmendmentBean = (IacucProtocolAmendmentBean)protocolForm.getActionHelper().getProtocolRenewAmendmentBean();
String newDocId = getProtocolAmendRenewService().createRenewalWithAmendment(protocolDocument,
renewAmendmentBean);
generateActionCorrespondence(IacucProtocolActionType.RENEWAL_WITH_AMENDMENT_CREATED, protocolForm.getProtocolDocument().getProtocol());
refreshAfterProtocolAction(protocolForm, newDocId, ACTION_NAME_RENEWAL_WITH_AMENDMENT, true);
// Form fields copy needed to support modifyAmendmentSections
protocolForm.getActionHelper().setProtocolAmendmentBean(renewAmendmentBean);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.RENEWAL_WITH_AMENDMENT_CREATED, "Renewal With Amendment Created");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#createContinuation(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String createContinuation(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
IacucProtocolDocument protocolDocument = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
String newDocId = getProtocolAmendRenewService().createContinuation(protocolDocument, actionHelper.getContinuationSummary());
generateActionCorrespondence(IacucProtocolActionType.CONTINUATION, protocolForm.getProtocolDocument().getProtocol());
refreshAfterProtocolAction(protocolForm, newDocId, ACTION_NAME_CONTINUATION_WITHOUT_AMENDMENT, true);
// Form fields copy needed to support modifyAmendmentSections
protocolForm.getActionHelper().getProtocolAmendmentBean().setSummary(actionHelper.getContinuationSummary());
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.CONTINUATION_CREATED_NOTIFICATION, "Continuation Created");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#createContinuationWithAmendment(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String createContinuationWithAmendment(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
IacucProtocolDocument protocolDocument = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolAmendmentBean continuationAmendmentBean = (IacucProtocolAmendmentBean)actionHelper.getProtocolContinuationAmendmentBean();
String newDocId = getProtocolAmendRenewService().createContinuationWithAmendment(protocolDocument,
continuationAmendmentBean);
generateActionCorrespondence(IacucProtocolActionType.CONTINUATION_AMENDMENT, protocolForm.getProtocolDocument().getProtocol());
refreshAfterProtocolAction(protocolForm, newDocId, ACTION_NAME_CONTINUATION_WITH_AMENDMENT, true);
// Form fields copy needed to support modifyAmendmentSections
protocolForm.getActionHelper().setProtocolAmendmentBean(continuationAmendmentBean);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.CONTINUATION_AMENDMENT, "Continuation With Amendment Created");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#assignToAgenda(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String assignToAgenda(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = (IacucProtocol) protocolForm.getProtocolDocument().getProtocol();
IacucProtocolAssignToAgendaBean actionBean = (IacucProtocolAssignToAgendaBean) protocolForm.getActionHelper().getAssignToAgendaBean();
getProtocolAssignToAgendaService().assignToAgenda(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.ASSIGNED_TO_AGENDA, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_ASSIGN_TO_AGENDA);
ProtocolActionBase lastAction = protocolForm.getProtocolDocument().getProtocol().getLastProtocolAction();
ProtocolActionTypeBase lastActionType = lastAction.getProtocolActionType();
String description = lastActionType.getDescription();
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.ASSIGNED_TO_AGENDA, description);
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_ACTIONS_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#removeFromAgenda(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String removeFromAgenda(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = (IacucProtocol) protocolForm.getProtocolDocument().getProtocol();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolGenericActionBean actionBean = actionHelper.getIacucProtocolRemoveFromAgendaBean();
getProtocolAssignToAgendaService().removeFromAgenda(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.REMOVE_FROM_AGENDA, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_REMOVE_FROM_AGENDA);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.REMOVE_FROM_AGENDA, actionBean.getComments());
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_ACTIONS_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#protocolReviewNotRequired(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String protocolReviewNotRequired(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolReviewNotRequiredBean actionBean = (IacucProtocolReviewNotRequiredBean) actionHelper.getProtocolReviewNotRequiredBean();
getProtocolReviewNotRequiredService().reviewNotRequired(document, actionBean);
generateActionCorrespondence(IacucProtocolActionType.IACUC_REVIEW_NOT_REQUIRED, protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(ACTION_NAME_REVIEW_NOT_REQUIRED);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(document.getIacucProtocol(), IacucProtocolActionType.IACUC_REVIEW_NOT_REQUIRED, "Review Not Required");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#grantAdminApproval(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String grantAdminApproval(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocolApproveBean actionBean = (IacucProtocolApproveBean) protocolForm.getActionHelper().getProtocolAdminApprovalBean();
getProtocolApproveService().grantAdminApproval(document.getProtocol(), actionBean);
generateActionCorrespondence(IacucProtocolActionType.ADMINISTRATIVE_APPROVAL, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess("Administrative Approval");
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol) document.getProtocol(), IacucProtocolActionType.ADMINISTRATIVE_APPROVAL, "Admin Approval");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#performRequestAction(org.kuali.kra.iacuc.IacucProtocolForm, java.lang.String)
*/
public String performRequestAction(IacucProtocolForm protocolForm, String taskName) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument)protocolForm.getProtocolDocument();
IacucProtocolRequestAction requestAction = IacucProtocolRequestAction.valueOfTaskName(taskName);
IacucProtocolRequestBean requestBean = getProtocolRequestBean(protocolForm, taskName);
if (requestBean != null) {
boolean valid = applyRules(new IacucProtocolRequestEvent<IacucProtocolRequestRule>(document, requestAction.getErrorPath(), requestBean));
requestBean.setAnswerHeaders(getAnswerHeaders(protocolForm, requestAction.getActionTypeCode()));
valid &= isMandatoryQuestionnaireComplete(requestBean.getAnswerHeaders(), "actionHelper." + requestAction.getBeanName() + ".datavalidation");
if (valid) {
getProtocolRequestService().submitRequest(protocolForm.getIacucProtocolDocument().getIacucProtocol(), requestBean);
generateActionCorrespondence(requestBean.getProtocolActionTypeCode(), protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(requestAction.getActionName());
return sendRequestNotification(protocolForm, requestBean.getProtocolActionTypeCode(), requestBean.getReason(), IacucConstants.PROTOCOL_ACTIONS_TAB);
}
}
return Constants.MAPPING_BASIC;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#disapproveProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String disapproveProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolDisapproveBean();
getProtocolGenericActionService().disapprove(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.IACUC_DISAPPROVED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_DISAPPROVE);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol) protocolForm.getProtocolDocument().getProtocol(), IacucProtocolActionType.IACUC_DISAPPROVED, "Disapproved");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#expireProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String expireProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolExpireBean();
getProtocolGenericActionService().expire(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.EXPIRED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_EXPIRE);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol) protocolForm.getProtocolDocument().getProtocol(), IacucProtocolActionType.EXPIRED, "Expired");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#terminateProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String terminateProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolTerminateBean();
getProtocolGenericActionService().terminate(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.TERMINATED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_TERMINATE);
IacucProtocolNotificationRequestBean notificationBean =
new IacucProtocolNotificationRequestBean((IacucProtocol) protocolForm.getProtocolDocument().getProtocol(), IacucProtocolActionType.TERMINATED, "Terminated");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#suspendProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String suspendProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSuspendBean();
getProtocolGenericActionService().suspend(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.SUSPENDED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_SUSPEND);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol) protocolForm.getProtocolDocument().getProtocol(), IacucProtocolActionType.SUSPENDED, "Suspended");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#acknowledgement(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String acknowledgement(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucAcknowledgeBean();
getProtocolGenericActionService().iacucAcknowledgement(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.IACUC_ACKNOWLEDGEMENT, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_ACKNOWLEDGEMENT);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.IACUC_ACKNOWLEDGEMENT, "IACUC Acknowledgement");
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_ACTIONS_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#hold(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String hold(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolHoldBean();
getProtocolGenericActionService().iacucHold(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.HOLD, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_HOLD);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol) protocolForm.getProtocolDocument().getProtocol(), IacucProtocolActionType.HOLD, "IACUC Hold");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#liftHold(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String liftHold(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolLiftHoldBean();
getProtocolGenericActionService().iacucLiftHold(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.LIFT_HOLD, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_LIFT_HOLD);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.LIFT_HOLD, "IACUC Lift Hold");
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#returnForSMR(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String returnForSMR(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSMRBean();
ProtocolDocumentBase newDocument = getProtocolGenericActionService().returnForSMR(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.IACUC_MINOR_REVISIONS_REQUIRED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
refreshAfterProtocolAction(protocolForm, newDocument.getDocumentNumber(), ACTION_NAME_SMR, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.IACUC_MINOR_REVISIONS_REQUIRED, "Minor Revisions Required");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#returnForSRR(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String returnForSRR(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolSRRBean();
ProtocolDocumentBase newDocument = getProtocolGenericActionService().returnForSRR(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.IACUC_MAJOR_REVISIONS_REQUIRED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
refreshAfterProtocolAction(protocolForm, newDocument.getDocumentNumber(), ACTION_NAME_SRR, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.IACUC_MAJOR_REVISIONS_REQUIRED, "Major Revisions Required");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#returnToPI(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String returnToPI(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolGenericActionBean actionBean = (IacucProtocolGenericActionBean) protocolForm.getActionHelper().getProtocolReturnToPIBean();
ProtocolDocumentBase newDocument = getProtocolGenericActionService().returnToPI(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.RETURNED_TO_PI, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
refreshAfterProtocolAction(protocolForm, newDocument.getDocumentNumber(), ACTION_NAME_RETURN_TO_PI, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.RETURNED_TO_PI, "Return To PI");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#deactivate(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String deactivate(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolGenericActionBean actionBean = actionHelper.getIacucProtocolDeactivateBean();
getProtocolGenericActionService().iacucDeactivate(protocol, actionBean);
generateActionCorrespondence(IacucProtocolActionType.DEACTIVATED, protocolForm.getProtocolDocument().getProtocol());
saveReviewComments(protocolForm, (IacucReviewCommentsBean) actionBean.getReviewCommentsBean());
recordProtocolActionSuccess(ACTION_NAME_DEACTIVATED);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.DEACTIVATED, "Deactivated");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#openProtocolForAdminCorrection(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String openProtocolForAdminCorrection(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
document.getProtocol().setCorrectionMode(true);
protocolForm.getProtocolHelper().prepareView();
IacucAdminCorrectionBean adminCorrectionBean = (IacucAdminCorrectionBean)protocolForm.getActionHelper().getProtocolAdminCorrectionBean();
document.updateProtocolStatus(IacucProtocolActionType.ADMINISTRATIVE_CORRECTION, adminCorrectionBean.getComments());
generateActionCorrespondence(IacucProtocolActionType.ADMINISTRATIVE_CORRECTION, protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(ACTION_NAME_MANAGE_ADMINISTRATIVE_CORRECTION);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocol, IacucProtocolActionType.ADMINISTRATIVE_CORRECTION, "Administrative Correction");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#abandon(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String abandon(IacucProtocolForm protocolForm) throws Exception {
getProtocolAbandonService().abandonProtocol(protocolForm.getProtocolDocument().getProtocol(),
protocolForm.getActionHelper().getProtocolAbandonBean());
generateActionCorrespondence(IacucProtocolActionType.IACUC_ABANDON, protocolForm.getProtocolDocument().getProtocol());
protocolForm.getProtocolHelper().prepareView();
recordProtocolActionSuccess(ACTION_NAME_RECORD_ABANDON);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(protocolForm.getIacucProtocolDocument().getIacucProtocol(),IacucProtocolActionType.IACUC_ABANDON, "Abandon");
protocolForm.getActionHelper().setProtocolCorrespondence(getProtocolCorrespondence(protocolForm, IacucConstants.PROTOCOL_ACTIONS_TAB, notificationBean, false));
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#modifySubmissionAction(org.kuali.kra.iacuc.IacucProtocolForm, java.util.List)
*/
public String modifySubmissionAction(IacucProtocolForm protocolForm, List<ProtocolReviewerBeanBase> reviewers) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolModifySubmissionBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolModifySubmissionBean();
actionBean.setReviewers(reviewers);
getModifySubmissionService().modifySubmission(document, actionBean, reviewers);
recordProtocolActionSuccess(ACTION_NAME_MODIFY_SUBMISSION);
performNotificationRendering(protocolForm, reviewers);
IacucProtocolNotificationRenderer assignRenderer = new IacucProtocolNotificationRenderer(protocol);
IacucProtocolNotificationContext assignContext = new IacucProtocolNotificationContext(protocol, null,
IacucProtocolActionType.MODIFY_PROTOCOL_SUBMISSION, "Modified", assignRenderer);
getNotificationService().sendNotificationAndPersist(assignContext, new IacucProtocolNotification(), protocol);
protocolForm.setReinitializeModifySubmissionFields(true);
generateActionCorrespondence(IacucProtocolActionType.MODIFY_PROTOCOL_SUBMISSION, protocolForm.getProtocolDocument().getProtocol());
return Constants.MAPPING_BASIC;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#tableProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String tableProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
IacucProtocolTableBean actionBean = ((IacucActionHelper) protocolForm.getActionHelper()).getIacucProtocolTableBean();
IacucProtocolDocument pd = getProtocolTableService().tableProtocol(protocol, actionBean);
IacucProtocol newIacucProtocol = (IacucProtocol)pd.getProtocol();
generateActionCorrespondence(IacucProtocolActionType.TABLED, newIacucProtocol);
refreshAfterProtocolAction(protocolForm, pd.getDocumentNumber(), ACTION_NAME_TABLE_PROTOCOL, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(newIacucProtocol, IacucProtocolActionType.TABLED, "Tabled");
ProtocolCorrespondence newProtocolCorrespondence = getProtocolCorrespondence(newIacucProtocol, IacucConstants.PROTOCOL_TAB, notificationBean, false);
protocolForm.getActionHelper().setProtocolCorrespondence(newProtocolCorrespondence);
synchronizeCorrespondenceAndNotification(protocol, newProtocolCorrespondence, notificationBean, protocolForm, newIacucProtocol);
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#administrativelyWithdrawProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String administrativelyWithdrawProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
boolean isVersion = isVersion(protocol);
ProtocolDocumentBase pd = getProtocolWithdrawService().administrativelyWithdraw(protocol, protocolForm.getActionHelper().getProtocolAdminWithdrawBean());
IacucProtocol newIacucProtocol = (IacucProtocol)pd.getProtocol();
generateActionCorrespondence(IacucProtocolActionType.ADMINISTRATIVELY_WITHDRAWN, newIacucProtocol);
refreshAfterProtocolAction(protocolForm, pd.getDocumentNumber(), ACTION_NAME_ADMINISTRATIVELY_WITHDRAW, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(newIacucProtocol, IacucProtocolActionType.ADMINISTRATIVELY_WITHDRAWN, "Administratively Withdrawn");
ProtocolCorrespondence newProtocolCorrespondence = getProtocolCorrespondence(newIacucProtocol, IacucConstants.PROTOCOL_TAB, notificationBean, false);
protocolForm.getActionHelper().setProtocolCorrespondence(newProtocolCorrespondence);
synchronizeWithdrawProcess(isVersion, protocol, newProtocolCorrespondence, notificationBean, protocolForm, newIacucProtocol);
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#withdrawProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String withdrawProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = (IacucProtocolDocument) protocolForm.getProtocolDocument();
IacucProtocol protocol = (IacucProtocol) document.getProtocol();
boolean isVersion = isVersion(protocol);
ProtocolDocumentBase pd = getProtocolWithdrawService().withdraw(protocol, protocolForm.getActionHelper().getProtocolWithdrawBean());
IacucProtocol newIacucProtocol = (IacucProtocol)pd.getProtocol();
generateActionCorrespondence(IacucProtocolActionType.IACUC_WITHDRAWN, newIacucProtocol);
refreshAfterProtocolAction(protocolForm, pd.getDocumentNumber(), ACTION_NAME_WITHDRAW, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(newIacucProtocol, IacucProtocolActionType.IACUC_WITHDRAWN, "Withdrawn");
ProtocolCorrespondence newProtocolCorrespondence = getProtocolCorrespondence(newIacucProtocol, IacucConstants.PROTOCOL_TAB, notificationBean, false);
protocolForm.getActionHelper().setProtocolCorrespondence(newProtocolCorrespondence);
synchronizeWithdrawProcess(isVersion, protocol, newProtocolCorrespondence, notificationBean, protocolForm, newIacucProtocol);
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* This method is to check whether we have created a version during withdraw process
* If there is a new version, make sure we have linked correspondence and notification to both previous and new protocol
* during withdraw action
* @param previousProtocol
* @param newProtocolCorrespondence
* @param notificationBean
* @param protocolForm
* @param currentProtocol
*/
private void synchronizeWithdrawProcess(boolean isVersion, IacucProtocol previousProtocol, ProtocolCorrespondence newProtocolCorrespondence,
IacucProtocolNotificationRequestBean notificationBean, IacucProtocolForm protocolForm, IacucProtocol currentProtocol) {
if(isVersion) {
synchronizeCorrespondenceAndNotification(previousProtocol, newProtocolCorrespondence, notificationBean, protocolForm, currentProtocol);
}
}
/**
* This method is to make sure we have linked correspondence and notification to both previous and versioned protocol
* @param isVersion
* @param previousProtocol
* @param newProtocolCorrespondence
* @param notificationBean
* @param protocolForm
* @param currentProtocol
*/
private void synchronizeCorrespondenceAndNotification(IacucProtocol previousProtocol, ProtocolCorrespondence newProtocolCorrespondence,
IacucProtocolNotificationRequestBean notificationBean, IacucProtocolForm protocolForm, IacucProtocol currentProtocol) {
ProtocolNotificationContextBase context = getProtocolNotificationContextHook(notificationBean, protocolForm);
ProtocolBase notificationProtocol = null;
if(newProtocolCorrespondence != null) {
getProtocolActionCorrespondenceGenerationService().attachProtocolCorrespondence(previousProtocol, newProtocolCorrespondence.getCorrespondence(),
newProtocolCorrespondence.getProtoCorrespTypeCode());
notificationProtocol = previousProtocol;
}else {
notificationProtocol = currentProtocol;
}
getNotificationService().sendNotificationAndPersist(context, getProtocolNotificationInstanceHook(), notificationProtocol);
}
private boolean isVersion(IacucProtocol protocol) {
boolean isVersion = IacucProtocolStatus.IN_PROGRESS.equals(protocol.getProtocolStatusCode()) ||
IacucProtocolStatus.SUBMITTED_TO_IACUC.equals(protocol.getProtocolStatusCode()) ||
IacucProtocolStatus.TABLED.equals(protocol.getProtocolStatusCode());
return isVersion;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#notifyProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String notifyProtocol(IacucProtocolForm protocolForm) throws Exception {
String returnPath = Constants.MAPPING_BASIC;
IacucActionHelper actionHelper = (IacucActionHelper) protocolForm.getActionHelper();
actionHelper.getIacucProtocolNotifyIacucBean().setAnswerHeaders(getAnswerHeaders(protocolForm, IacucProtocolActionType.NOTIFY_IACUC));
if (isMandatoryQuestionnaireComplete(actionHelper.getIacucProtocolNotifyIacucBean().getAnswerHeaders(), "actionHelper.protocolNotifyIacucBean.datavalidation")) {
getProtocolNotifyService().submitIacucNotification((IacucProtocol)protocolForm.getProtocolDocument().getProtocol(),
actionHelper.getIacucProtocolNotifyIacucBean());
protocolForm.getQuestionnaireHelper().setAnswerHeaders(new ArrayList<AnswerHeader>());
protocolForm.setReinitializeModifySubmissionFields(true);
LOG.info("notifyIacucProtocol " + protocolForm.getProtocolDocument().getDocumentNumber());
generateActionCorrespondence(IacucProtocolActionType.NOTIFY_IACUC, protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(ACTION_NAME_NOTIFY);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean((IacucProtocol)protocolForm.getProtocolDocument().getProtocol(),IacucProtocolActionType.NOTIFY_IACUC, "Notify IACUC");
returnPath = getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_ACTIONS_TAB);
}
return returnPath;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#sendReviewDeterminationNotificationAction(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String sendReviewDeterminationNotificationAction(IacucProtocolForm protocolForm) throws Exception {
String returnPath = Constants.MAPPING_BASIC;
IacucActionHelper actionHelper = (IacucActionHelper) protocolForm.getActionHelper();
IacucProtocol protocol = (IacucProtocol) protocolForm.getProtocolDocument().getProtocol();
IacucProtocolModifySubmissionBean bean = actionHelper.getIacucProtocolModifySubmissionBean();
Date dueDate = bean.getDueDate();
IacucProtocolReviewDeterminationNotificationRenderer renderer = new IacucProtocolReviewDeterminationNotificationRenderer(protocol, dueDate);
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext(protocol, IacucProtocolActionType.REVIEW_TYPE_DETERMINATION, "Review Type Determination", renderer);
if (protocolForm.getNotificationHelper().getPromptUserForNotificationEditor(context)) {
protocolForm.getNotificationHelper().initializeDefaultValues(context);
returnPath = IacucConstants.NOTIFICATION_EDITOR;
} else {
getNotificationService().sendNotificationAndPersist(context, new IacucProtocolNotification(), protocol);
}
generateActionCorrespondence(IacucProtocolActionType.REVIEW_TYPE_DETERMINATION, protocolForm.getProtocolDocument().getProtocol());
recordProtocolActionSuccess(ACTION_NAME_REVIEW_TYPE_DETERMINATION);
return returnPath;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#administrativelyMarkIncompleteProtocol(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String administrativelyMarkIncompleteProtocol(IacucProtocolForm protocolForm) throws Exception {
IacucProtocol protocol = (IacucProtocol) protocolForm.getProtocolDocument().getProtocol();
boolean isVersion = isVersion(protocol);
ProtocolDocumentBase pd = getProtocolWithdrawService().administrativelyMarkIncomplete(protocol, protocolForm.getActionHelper().getProtocolAdminIncompleteBean());
IacucProtocol newIacucProtocol = (IacucProtocol)pd.getProtocol();
generateActionCorrespondence(IacucProtocolActionType.ADMINISTRATIVELY_INCOMPLETE, newIacucProtocol);
refreshAfterProtocolAction(protocolForm, pd.getDocumentNumber(), ACTION_NAME_ADMINISTRATIVELY_INCOMPLETE, false);
IacucProtocolNotificationRequestBean notificationBean = new IacucProtocolNotificationRequestBean(newIacucProtocol, IacucProtocolActionType.ADMINISTRATIVELY_INCOMPLETE, "Administratively Marked Incomplete");
ProtocolCorrespondence newProtocolCorrespondence = getProtocolCorrespondence(newIacucProtocol, IacucConstants.PROTOCOL_TAB, notificationBean, false);
protocolForm.getActionHelper().setProtocolCorrespondence(newProtocolCorrespondence);
synchronizeWithdrawProcess(isVersion, protocol, newProtocolCorrespondence, notificationBean, protocolForm, newIacucProtocol);
return getRedirectPathAfterProtocolAction(protocolForm, notificationBean, IacucConstants.PROTOCOL_TAB);
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#submitCommitteeDecision(org.kuali.kra.iacuc.IacucProtocolForm)
*/
@SuppressWarnings("deprecation")
public String submitCommitteeDecision(IacucProtocolForm protocolForm) throws Exception {
IacucCommitteeDecision actionBean = (IacucCommitteeDecision) protocolForm.getActionHelper().getCommitteeDecision();
getCommitteeDecisionService().processCommitteeDecision(protocolForm.getProtocolDocument().getProtocol(), actionBean);
saveReviewComments(protocolForm, actionBean.getReviewCommentsBean());
protocolForm.getTabStates().put(":" + WebUtils.generateTabKey(motionTypeMap.get(actionBean.getMotionTypeCode())), "OPEN");
recordProtocolActionSuccess(ACTION_NAME_RECORD_COMMITTEE_DECISION);
generateActionCorrespondence(IacucProtocolActionType.RECORD_COMMITTEE_DECISION, protocolForm.getProtocolDocument().getProtocol());
return Constants.MAPPING_BASIC;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#assignCommittee(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String assignCommittee(IacucProtocolForm protocolForm) throws Exception {
IacucActionHelper actionHelper = (IacucActionHelper)protocolForm.getActionHelper();
IacucProtocolAssignCmtBean actionBean = actionHelper.getProtocolAssignCmtBean();
if( protocolForm.getProtocolDocument().getProtocol().getProtocolSubmission() != null) {
getAssignToCmtService().assignToCommittee(protocolForm.getProtocolDocument().getProtocol(), actionBean);
recordProtocolActionSuccess(ACTION_NAME_ASSIGN_TO_COMMITTEE);
protocolForm.setReinitializeModifySubmissionFields(true);
generateActionCorrespondence(IacucProtocolActionType.ASSIGNED_TO_COMMITTEE, protocolForm.getProtocolDocument().getProtocol());
}
return Constants.MAPPING_BASIC;
}
public String performNotificationRendering(IacucProtocolForm protocolForm, List<ProtocolReviewerBeanBase> beans) {
String returnPath = Constants.MAPPING_BASIC;
IacucProtocol protocol = (IacucProtocol) protocolForm.getProtocolDocument().getProtocol();
IacucProtocolAssignReviewerNotificationRenderer renderer = new IacucProtocolAssignReviewerNotificationRenderer(protocol, "added");
List<ProtocolNotificationRequestBeanBase> addReviewerNotificationBeans = getNotificationRequestBeans(beans,
IacucProtocolReviewerBean.CREATE, true);
List<ProtocolNotificationRequestBeanBase> removeReviewerNotificationBeans = getNotificationRequestBeans(beans,
IacucProtocolReviewerBean.REMOVE, false);
if (!CollectionUtils.isEmpty(addReviewerNotificationBeans)) {
ProtocolNotificationRequestBeanBase notificationBean = addReviewerNotificationBeans.get(0);
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext((IacucProtocol)notificationBean.getProtocol(),
(IacucProtocolOnlineReview)notificationBean.getProtocolOnlineReview(), notificationBean.getActionType(),
notificationBean.getDescription(), renderer);
if (protocolForm.getNotificationHelper().getPromptUserForNotificationEditor(context)) {
boolean sendNotification = checkToSendNotification(protocolForm, renderer, addReviewerNotificationBeans, IacucConstants.PROTOCOL_ACTIONS_TAB);
returnPath = sendNotification ? IacucConstants.NOTIFICATION_EDITOR : IacucConstants.PROTOCOL_ACTIONS_TAB;
if (!CollectionUtils.isEmpty(removeReviewerNotificationBeans)) {
GlobalVariables.getUserSession().addObject("removeReviewer", removeReviewerNotificationBeans);
}
}
}else {
if (!CollectionUtils.isEmpty(removeReviewerNotificationBeans)) {
renderer = new IacucProtocolAssignReviewerNotificationRenderer(protocol, "removed");
ProtocolNotificationRequestBeanBase notificationBean = removeReviewerNotificationBeans.get(0);
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext(protocol,
(IacucProtocolOnlineReview)notificationBean.getProtocolOnlineReview(), notificationBean.getActionType(),
notificationBean.getDescription(), renderer);
if (protocolForm.getNotificationHelper().getPromptUserForNotificationEditor(context)) {
boolean sendNotification = checkToSendNotification(protocolForm, renderer, removeReviewerNotificationBeans, IacucConstants.PROTOCOL_ACTIONS_TAB);
returnPath = sendNotification ? IacucConstants.NOTIFICATION_EDITOR : IacucConstants.PROTOCOL_ACTIONS_TAB;
}
}
}
return returnPath;
}
private List<ProtocolNotificationRequestBeanBase> getNotificationRequestBeans(List<ProtocolReviewerBeanBase> beans, String actionFlag, boolean notNullFlag) {
List<ProtocolNotificationRequestBeanBase> notificationRequestBeans = new ArrayList<ProtocolNotificationRequestBeanBase>();
for (ProtocolReviewerBeanBase bean : beans) {
if (StringUtils.equals(actionFlag, bean.getActionFlag()) && (notNullFlag == !StringUtils.isEmpty(bean.getReviewerTypeCode()))) {
notificationRequestBeans.add(bean.getNotificationRequestBean());
}
}
return notificationRequestBeans;
}
protected boolean checkToSendNotification(ProtocolFormBase protocolForm, IacucProtocolNotificationRenderer renderer, List<ProtocolNotificationRequestBeanBase> notificationRequestBeans, String promptAfterNotification) {
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext((IacucProtocol) notificationRequestBeans.get(0).getProtocol(),
(IacucProtocolOnlineReview)notificationRequestBeans.get(0).getProtocolOnlineReview(), notificationRequestBeans.get(0).getActionType(),
notificationRequestBeans.get(0).getDescription(), renderer);
context.setPopulateRole(true);
if (protocolForm.getNotificationHelper().getPromptUserForNotificationEditor(context)) {
protocolForm.getNotificationHelper().initializeDefaultValues(context);
List<NotificationTypeRecipient> notificationRecipients = protocolForm.getNotificationHelper()
.getNotificationRecipients();
List<NotificationTypeRecipient> allRecipients = new ArrayList<NotificationTypeRecipient>();
for (NotificationTypeRecipient recipient : notificationRecipients) {
try {
NotificationTypeRecipient copiedRecipient = (NotificationTypeRecipient) ObjectUtils.deepCopy(recipient);
// populate role qualifier with proper context
context.populateRoleQualifiers(copiedRecipient);
allRecipients.add(copiedRecipient);
}
catch (Exception ex) {
LOG.error(ex.getMessage());
}
}
int i = 1;
// add all new reviewer to recipients
while (notificationRequestBeans.size() > i) {
context = new IacucProtocolNotificationContext((IacucProtocol) notificationRequestBeans.get(i).getProtocol(),
(IacucProtocolOnlineReview) notificationRequestBeans.get(i).getProtocolOnlineReview(),
notificationRequestBeans.get(i).getActionType(),
notificationRequestBeans.get(i).getDescription(), renderer);
context.setPopulateRole(true);
protocolForm.getNotificationHelper().initializeDefaultValues(context);
List<NotificationTypeRecipient> recipients = protocolForm.getNotificationHelper().getNotificationRecipients();
for (NotificationTypeRecipient recipient : recipients) {
try {
/* NOTE : need to deepcopy here. If not, then all reviewer role will have same
* notification recipient object returned from service call
*/
NotificationTypeRecipient copiedRecipient = (NotificationTypeRecipient) ObjectUtils.deepCopy(recipient);
context.populateRoleQualifiers(copiedRecipient);
allRecipients.add(copiedRecipient);
}
catch (Exception ex) {
LOG.error(ex.getMessage());
}
}
i++;
}
protocolForm.getNotificationHelper().setNotificationRecipients(allRecipients);
if (promptAfterNotification == null) {
context.setForwardName(RETURN_TO_HOLDING_PAGE);
} else {
context.setForwardName(promptAfterNotification);
}
return true;
}else {
return false;
}
}
private IacucProtocolRequestBean getProtocolRequestBean(ProtocolFormBase protocolForm, String taskName) {
IacucProtocolRequestBean protocolRequestBean = null;
ProtocolActionBean protocolActionBean = getActionBean(protocolForm, taskName);
if (protocolActionBean != null && protocolActionBean instanceof IacucProtocolRequestBean) {
protocolRequestBean = (IacucProtocolRequestBean) protocolActionBean;
}
return protocolRequestBean;
}
/**
* @see org.kuali.kra.iacuc.actions.IacucProtocolActionRequestService#withdrawRequestAction(org.kuali.kra.iacuc.IacucProtocolForm)
*/
public String withdrawRequestAction(IacucProtocolForm protocolForm) throws Exception {
IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
IacucProtocol protocol = protocolForm.getIacucProtocolDocument().getIacucProtocol();
IacucProtocolRequestAction requestAction = IacucProtocolRequestAction.valueOfTaskName(TaskName.IACUC_WITHDRAW_SUBMISSION);
IacucProtocolRequestBean requestBean = getProtocolRequestBean(protocolForm, TaskName.IACUC_WITHDRAW_SUBMISSION);
if (requestBean != null) {
boolean valid = applyRules(new IacucProtocolRequestEvent<IacucProtocolRequestRule>(document, requestAction.getErrorPath(), requestBean));
if (valid) {
// find recently submitted action request and complete it
List<ProtocolSubmissionBase> submissions = protocol.getProtocolSubmissions();
ProtocolSubmissionBase submission = null;
for (ProtocolSubmissionBase sub: submissions) {
if (requestSubmissionTypes.contains(sub.getSubmissionTypeCode())) {
submission = sub;
}
}
if (submission != null) {
submission.setSubmissionStatusCode(IacucProtocolSubmissionStatus.WITHDRAWN);
IacucProtocolAction protocolAction = new IacucProtocolAction(protocol, (IacucProtocolSubmission) submission, IacucProtocolActionType.IACUC_WITHDRAW_SUBMISSION);
protocolAction.setComments(requestBean.getReason());
protocolAction.setActionDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
protocolAction.setSubmissionIdFk(submission.getSubmissionId());
protocolAction.setSubmissionNumber(submission.getSubmissionNumber());
document.getProtocol().getProtocolActions().add(protocolAction);
getProtocolActionService().updateProtocolStatus(protocolAction, document.getProtocol());
getBusinessObjectService().save(submission);
recordProtocolActionSuccess(requestAction.getActionName());
return sendRequestNotification(protocolForm, requestBean.getProtocolActionTypeCode(), requestBean.getReason(), IacucConstants.PROTOCOL_ACTIONS_TAB);
}
}
}
return Constants.MAPPING_BASIC;
}
@Override
protected ProtocolTaskBase getProtocolTaskInstanceHook(String taskName, ProtocolBase protocol) {
IacucProtocolTask task = new IacucProtocolTask(taskName, (IacucProtocol)protocol);
return task;
}
@Override
protected ProtocolActionsCorrespondenceBase getNewProtocolActionsCorrespondence(String protocolActionTypeCode) {
return new IacucProtocolActionsCorrespondence(protocolActionTypeCode);
}
@Override
protected Class<? extends ProtocolActionTypeBase> getProtocolActionTypeBOClassHook() {
return IacucProtocolActionType.class;
}
@Override
protected String getProtocolCreatedActionTypeHook() {
return IacucProtocolActionType.IACUC_PROTOCOL_CREATED;
}
public IacucProtocolApproveService getProtocolApproveService() {
return protocolApproveService;
}
public void setProtocolApproveService(IacucProtocolApproveService protocolApproveService) {
this.protocolApproveService = protocolApproveService;
}
@Override
protected Class<? extends ProtocolBase> getProtocolBOClassHook() {
return IacucProtocol.class;
}
@Override
protected ProtocolTaskBase getProtocolGenericActionTaskInstanceHook(String genericActionName,
ProtocolBase protocol) {
IacucProtocolTask task = new IacucProtocolTask(TaskName.GENERIC_IACUC_PROTOCOL_ACTION, (IacucProtocol)protocol, genericActionName);
return task;
}
@Override
protected String getProtocolRejectedInRoutingActionTypeHook() {
return IacucProtocolActionType.REJECTED_IN_ROUTING;
}
@Override
protected String getProtocolRecalledInRoutingActionTypeHook() {
//This action type is not supported in IACUC
return null;
}
public IacucProtocolSubmitActionService getProtocolSubmitActionService() {
return protocolSubmitActionService;
}
public void setProtocolSubmitActionService(IacucProtocolSubmitActionService protocolSubmitActionService) {
this.protocolSubmitActionService = protocolSubmitActionService;
}
public IacucProtocolAmendRenewService getProtocolAmendRenewService() {
return protocolAmendRenewService;
}
public void setProtocolAmendRenewService(IacucProtocolAmendRenewService protocolAmendRenewService) {
this.protocolAmendRenewService = protocolAmendRenewService;
}
public IacucProtocolActionService getProtocolActionService() {
return protocolActionService;
}
public void setProtocolActionService(IacucProtocolActionService protocolActionService) {
this.protocolActionService = protocolActionService;
}
@Override
protected String getNotificationEditorHook() {
return IacucConstants.NOTIFICATION_EDITOR;
}
@Override
protected ProtocolNotification getProtocolNotificationInstanceHook() {
return new IacucProtocolNotification();
}
@Override
protected ProtocolNotificationContextBase getProtocolNotificationContextHook(
ProtocolNotificationRequestBeanBase notificationRequestBean, ProtocolFormBase protocolForm) {
IacucProtocolNotificationRenderer renderer = null;
IacucProtocol protocol = (IacucProtocol)notificationRequestBean.getProtocol();
if (StringUtils.equals(IacucProtocolActionType.NOTIFY_IACUC, notificationRequestBean.getActionType())) {
renderer = new NotifyIacucNotificationRenderer(protocol, ((IacucActionHelper)protocolForm.getActionHelper()).getIacucProtocolNotifyIacucBean().getComment());
} else if (StringUtils.equals(IacucProtocolActionType.IACUC_DELETED, notificationRequestBean.getActionType()) ||
StringUtils.equals(IacucProtocolActionType.IACUC_WITHDRAWN, notificationRequestBean.getActionType())) {
renderer = new IacucProtocolWithReasonNotificationRenderer(protocol, protocolForm.getActionHelper().getProtocolDeleteBean());
} else if (StringUtils.equals(IacucProtocolActionType.REQUEST_DEACTIVATE, notificationRequestBean.getActionType()) ||
StringUtils.equals(IacucProtocolActionType.REQUEST_LIFT_HOLD, notificationRequestBean.getActionType())) {
IacucRequestActionNotificationBean requestNotificationRequestBean = (IacucRequestActionNotificationBean)notificationRequestBean;
renderer = new IacucProtocolRequestActionNotificationRenderer(protocol, requestNotificationRequestBean.getReason());
} else if (StringUtils.equals(IacucProtocolActionType.IACUC_REQUEST_SUSPEND, notificationRequestBean.getActionType())) {
IacucProtocolRequestBean iacucProtocolSuspendRequestBean = ((IacucActionHelper)protocolForm.getActionHelper()).getIacucProtocolSuspendRequestBean();
renderer = new NotifyIacucNotificationRenderer(protocol, iacucProtocolSuspendRequestBean.getReason());
} else {
renderer = new IacucProtocolNotificationRenderer(protocol);
}
IacucProtocolNotificationContext context = new IacucProtocolNotificationContext(protocol, notificationRequestBean.getActionType(), notificationRequestBean.getDescription(), renderer);
return context;
}
@Override
protected Class<? extends ProtocolCorrespondence> getProtocolCorrespondenceBOClassHook() {
return IacucProtocolCorrespondence.class;
}
public IacucProtocolAssignToAgendaService getProtocolAssignToAgendaService() {
return protocolAssignToAgendaService;
}
public void setProtocolAssignToAgendaService(IacucProtocolAssignToAgendaService protocolAssignToAgendaService) {
this.protocolAssignToAgendaService = protocolAssignToAgendaService;
}
public IacucProtocolReviewNotRequiredService getProtocolReviewNotRequiredService() {
return protocolReviewNotRequiredService;
}
public void setProtocolReviewNotRequiredService(IacucProtocolReviewNotRequiredService protocolReviewNotRequiredService) {
this.protocolReviewNotRequiredService = protocolReviewNotRequiredService;
}
@Override
protected ModuleQuestionnaireBean getProtocolModuleQuestionnaireBeanInstanceHook(ProtocolFormBase protocolForm,
String actionTypeCode) {
return new IacucProtocolModuleQuestionnaireBean(CoeusModule.IACUC_PROTOCOL_MODULE_CODE, protocolForm.getProtocolDocument().getProtocol().getProtocolNumber() + "T", CoeusSubModule.PROTOCOL_SUBMISSION, actionTypeCode, false);
}
public IacucProtocolRequestService getProtocolRequestService() {
return protocolRequestService;
}
public void setProtocolRequestService(IacucProtocolRequestService protocolRequestService) {
this.protocolRequestService = protocolRequestService;
}
@Override
protected ProtocolNotificationRequestBeanBase getRequestActionNotificationBeanInstanceHook(ProtocolBase protocol,
String protocolActionTypeCode, String description, String reason) {
return new IacucRequestActionNotificationBean((IacucProtocol)protocol, protocolActionTypeCode, description, reason);
}
@Override
protected ProtocolQuestionnaireAuditRuleBase getProtocolQuestionnaireAuditRuleInstanceHook() {
return new IacucProtocolQuestionnaireAuditRule();
}
public IacucProtocolGenericActionService getProtocolGenericActionService() {
return protocolGenericActionService;
}
public void setProtocolGenericActionService(IacucProtocolGenericActionService protocolGenericActionService) {
this.protocolGenericActionService = protocolGenericActionService;
}
public IacucProtocolAbandonService getProtocolAbandonService() {
return protocolAbandonService;
}
public void setProtocolAbandonService(IacucProtocolAbandonService protocolAbandonService) {
this.protocolAbandonService = protocolAbandonService;
}
public IacucProtocolModifySubmissionService getModifySubmissionService() {
return modifySubmissionService;
}
public void setModifySubmissionService(IacucProtocolModifySubmissionService modifySubmissionService) {
this.modifySubmissionService = modifySubmissionService;
}
public IacucProtocolTableService getProtocolTableService() {
return protocolTableService;
}
public void setProtocolTableService(IacucProtocolTableService protocolTableService) {
this.protocolTableService = protocolTableService;
}
public IacucProtocolWithdrawService getProtocolWithdrawService() {
return protocolWithdrawService;
}
public void setProtocolWithdrawService(IacucProtocolWithdrawService protocolWithdrawService) {
this.protocolWithdrawService = protocolWithdrawService;
}
public IacucProtocolNotifyIacucService getProtocolNotifyService() {
return protocolNotifyService;
}
public void setProtocolNotifyService(IacucProtocolNotifyIacucService protocolNotifyService) {
this.protocolNotifyService = protocolNotifyService;
}
public IacucCommitteeDecisionService getCommitteeDecisionService() {
return committeeDecisionService;
}
public void setCommitteeDecisionService(IacucCommitteeDecisionService committeeDecisionService) {
this.committeeDecisionService = committeeDecisionService;
}
public IacucProtocolAssignCmtService getAssignToCmtService() {
return assignToCmtService;
}
public void setAssignToCmtService(IacucProtocolAssignCmtService assignToCmtService) {
this.assignToCmtService = assignToCmtService;
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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 io.netty.util.internal;
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s.
* Note that this class is for internal use only and is subject to change at any time. Use {@link FastThreadLocal}
* unless you know what you are doing.
*/
public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(InternalThreadLocalMap.class);
private static final ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap =
new ThreadLocal<InternalThreadLocalMap>();
private static final AtomicInteger nextIndex = new AtomicInteger();
private static final int DEFAULT_ARRAY_LIST_INITIAL_CAPACITY = 8;
private static final int STRING_BUILDER_INITIAL_SIZE;
private static final int STRING_BUILDER_MAX_SIZE;
private static final int HANDLER_SHARABLE_CACHE_INITIAL_CAPACITY = 4;
private static final int INDEXED_VARIABLE_TABLE_INITIAL_SIZE = 32;
public static final Object UNSET = new Object();
/** Used by {@link FastThreadLocal} */
private Object[] indexedVariables;
// Core thread-locals
private int futureListenerStackDepth;
private int localChannelReaderStackDepth;
private Map<Class<?>, Boolean> handlerSharableCache;
private IntegerHolder counterHashCode;
private ThreadLocalRandom random;
private Map<Class<?>, TypeParameterMatcher> typeParameterMatcherGetCache;
private Map<Class<?>, Map<String, TypeParameterMatcher>> typeParameterMatcherFindCache;
// String-related thread-locals
private StringBuilder stringBuilder;
private Map<Charset, CharsetEncoder> charsetEncoderCache;
private Map<Charset, CharsetDecoder> charsetDecoderCache;
// ArrayList-related thread-locals
private ArrayList<Object> arrayList;
private BitSet cleanerFlags;
/** @deprecated These padding fields will be removed in the future. */
public long rp1, rp2, rp3, rp4, rp5, rp6, rp7, rp8, rp9;
static {
STRING_BUILDER_INITIAL_SIZE =
SystemPropertyUtil.getInt("io.netty.threadLocalMap.stringBuilder.initialSize", 1024);
logger.debug("-Dio.netty.threadLocalMap.stringBuilder.initialSize: {}", STRING_BUILDER_INITIAL_SIZE);
STRING_BUILDER_MAX_SIZE = SystemPropertyUtil.getInt("io.netty.threadLocalMap.stringBuilder.maxSize", 1024 * 4);
logger.debug("-Dio.netty.threadLocalMap.stringBuilder.maxSize: {}", STRING_BUILDER_MAX_SIZE);
}
public static InternalThreadLocalMap getIfSet() {
Thread thread = Thread.currentThread();
if (thread instanceof FastThreadLocalThread) {
return ((FastThreadLocalThread) thread).threadLocalMap();
}
return slowThreadLocalMap.get();
}
public static InternalThreadLocalMap get() {
Thread thread = Thread.currentThread();
if (thread instanceof FastThreadLocalThread) {
return fastGet((FastThreadLocalThread) thread);
} else {
return slowGet();
}
}
private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) {
InternalThreadLocalMap threadLocalMap = thread.threadLocalMap();
if (threadLocalMap == null) {
thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap());
}
return threadLocalMap;
}
private static InternalThreadLocalMap slowGet() {
InternalThreadLocalMap ret = slowThreadLocalMap.get();
if (ret == null) {
ret = new InternalThreadLocalMap();
slowThreadLocalMap.set(ret);
}
return ret;
}
public static void remove() {
Thread thread = Thread.currentThread();
if (thread instanceof FastThreadLocalThread) {
((FastThreadLocalThread) thread).setThreadLocalMap(null);
} else {
slowThreadLocalMap.remove();
}
}
public static void destroy() {
slowThreadLocalMap.remove();
}
public static int nextVariableIndex() {
int index = nextIndex.getAndIncrement();
if (index < 0) {
nextIndex.decrementAndGet();
throw new IllegalStateException("too many thread-local indexed variables");
}
return index;
}
public static int lastVariableIndex() {
return nextIndex.get() - 1;
}
private InternalThreadLocalMap() {
indexedVariables = newIndexedVariableTable();
}
private static Object[] newIndexedVariableTable() {
Object[] array = new Object[INDEXED_VARIABLE_TABLE_INITIAL_SIZE];
Arrays.fill(array, UNSET);
return array;
}
public int size() {
int count = 0;
if (futureListenerStackDepth != 0) {
count ++;
}
if (localChannelReaderStackDepth != 0) {
count ++;
}
if (handlerSharableCache != null) {
count ++;
}
if (counterHashCode != null) {
count ++;
}
if (random != null) {
count ++;
}
if (typeParameterMatcherGetCache != null) {
count ++;
}
if (typeParameterMatcherFindCache != null) {
count ++;
}
if (stringBuilder != null) {
count ++;
}
if (charsetEncoderCache != null) {
count ++;
}
if (charsetDecoderCache != null) {
count ++;
}
if (arrayList != null) {
count ++;
}
for (Object o: indexedVariables) {
if (o != UNSET) {
count ++;
}
}
// We should subtract 1 from the count because the first element in 'indexedVariables' is reserved
// by 'FastThreadLocal' to keep the list of 'FastThreadLocal's to remove on 'FastThreadLocal.removeAll()'.
return count - 1;
}
public StringBuilder stringBuilder() {
StringBuilder sb = stringBuilder;
if (sb == null) {
return stringBuilder = new StringBuilder(STRING_BUILDER_INITIAL_SIZE);
}
if (sb.capacity() > STRING_BUILDER_MAX_SIZE) {
sb.setLength(STRING_BUILDER_INITIAL_SIZE);
sb.trimToSize();
}
sb.setLength(0);
return sb;
}
public Map<Charset, CharsetEncoder> charsetEncoderCache() {
Map<Charset, CharsetEncoder> cache = charsetEncoderCache;
if (cache == null) {
charsetEncoderCache = cache = new IdentityHashMap<Charset, CharsetEncoder>();
}
return cache;
}
public Map<Charset, CharsetDecoder> charsetDecoderCache() {
Map<Charset, CharsetDecoder> cache = charsetDecoderCache;
if (cache == null) {
charsetDecoderCache = cache = new IdentityHashMap<Charset, CharsetDecoder>();
}
return cache;
}
public <E> ArrayList<E> arrayList() {
return arrayList(DEFAULT_ARRAY_LIST_INITIAL_CAPACITY);
}
@SuppressWarnings("unchecked")
public <E> ArrayList<E> arrayList(int minCapacity) {
ArrayList<E> list = (ArrayList<E>) arrayList;
if (list == null) {
arrayList = new ArrayList<Object>(minCapacity);
return (ArrayList<E>) arrayList;
}
list.clear();
list.ensureCapacity(minCapacity);
return list;
}
public int futureListenerStackDepth() {
return futureListenerStackDepth;
}
public void setFutureListenerStackDepth(int futureListenerStackDepth) {
this.futureListenerStackDepth = futureListenerStackDepth;
}
public ThreadLocalRandom random() {
ThreadLocalRandom r = random;
if (r == null) {
random = r = new ThreadLocalRandom();
}
return r;
}
public Map<Class<?>, TypeParameterMatcher> typeParameterMatcherGetCache() {
Map<Class<?>, TypeParameterMatcher> cache = typeParameterMatcherGetCache;
if (cache == null) {
typeParameterMatcherGetCache = cache = new IdentityHashMap<Class<?>, TypeParameterMatcher>();
}
return cache;
}
public Map<Class<?>, Map<String, TypeParameterMatcher>> typeParameterMatcherFindCache() {
Map<Class<?>, Map<String, TypeParameterMatcher>> cache = typeParameterMatcherFindCache;
if (cache == null) {
typeParameterMatcherFindCache = cache = new IdentityHashMap<Class<?>, Map<String, TypeParameterMatcher>>();
}
return cache;
}
@Deprecated
public IntegerHolder counterHashCode() {
return counterHashCode;
}
@Deprecated
public void setCounterHashCode(IntegerHolder counterHashCode) {
this.counterHashCode = counterHashCode;
}
public Map<Class<?>, Boolean> handlerSharableCache() {
Map<Class<?>, Boolean> cache = handlerSharableCache;
if (cache == null) {
// Start with small capacity to keep memory overhead as low as possible.
handlerSharableCache = cache = new WeakHashMap<Class<?>, Boolean>(HANDLER_SHARABLE_CACHE_INITIAL_CAPACITY);
}
return cache;
}
public int localChannelReaderStackDepth() {
return localChannelReaderStackDepth;
}
public void setLocalChannelReaderStackDepth(int localChannelReaderStackDepth) {
this.localChannelReaderStackDepth = localChannelReaderStackDepth;
}
public Object indexedVariable(int index) {
Object[] lookup = indexedVariables;
return index < lookup.length? lookup[index] : UNSET;
}
/**
* @return {@code true} if and only if a new thread-local variable has been created
*/
public boolean setIndexedVariable(int index, Object value) {
Object[] lookup = indexedVariables;
if (index < lookup.length) {
Object oldValue = lookup[index];
lookup[index] = value;
return oldValue == UNSET;
} else {
expandIndexedVariableTableAndSet(index, value);
return true;
}
}
private void expandIndexedVariableTableAndSet(int index, Object value) {
Object[] oldArray = indexedVariables;
final int oldCapacity = oldArray.length;
int newCapacity = index;
newCapacity |= newCapacity >>> 1;
newCapacity |= newCapacity >>> 2;
newCapacity |= newCapacity >>> 4;
newCapacity |= newCapacity >>> 8;
newCapacity |= newCapacity >>> 16;
newCapacity ++;
Object[] newArray = Arrays.copyOf(oldArray, newCapacity);
Arrays.fill(newArray, oldCapacity, newArray.length, UNSET);
newArray[index] = value;
indexedVariables = newArray;
}
public Object removeIndexedVariable(int index) {
Object[] lookup = indexedVariables;
if (index < lookup.length) {
Object v = lookup[index];
lookup[index] = UNSET;
return v;
} else {
return UNSET;
}
}
public boolean isIndexedVariableSet(int index) {
Object[] lookup = indexedVariables;
return index < lookup.length && lookup[index] != UNSET;
}
public boolean isCleanerFlagSet(int index) {
return cleanerFlags != null && cleanerFlags.get(index);
}
public void setCleanerFlag(int index) {
if (cleanerFlags == null) {
cleanerFlags = new BitSet();
}
cleanerFlags.set(index);
}
}
| |
/*
* 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.cookbook;
import static com.google.datastore.v1beta3.client.DatastoreHelper.getString;
import static com.google.datastore.v1beta3.client.DatastoreHelper.makeFilter;
import static com.google.datastore.v1beta3.client.DatastoreHelper.makeKey;
import static com.google.datastore.v1beta3.client.DatastoreHelper.makeValue;
import org.apache.beam.examples.WordCount;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.DatastoreIO;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.io.TextIO;
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.MapElements;
import org.apache.beam.sdk.transforms.ParDo;
import com.google.datastore.v1beta3.Entity;
import com.google.datastore.v1beta3.Key;
import com.google.datastore.v1beta3.PropertyFilter;
import com.google.datastore.v1beta3.Query;
import com.google.datastore.v1beta3.Value;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
/**
* A WordCount example using DatastoreIO.
*
* <p>This example shows how to use DatastoreIO to read from Datastore and
* write the results to Cloud Storage. Note that this example will write
* data to Datastore, which may incur charge for Datastore operations.
*
* <p>To run this example, users need to use gcloud to get credential for Datastore:
* <pre>{@code
* $ gcloud auth login
* }</pre>
*
* <p>To run this pipeline locally, the following options must be provided:
* <pre>{@code
* --project=YOUR_PROJECT_ID
* --output=[YOUR_LOCAL_FILE | gs://YOUR_OUTPUT_PATH]
* }</pre>
*
* <p>To run this example using Dataflow service, you must additionally
* provide either {@literal --tempLocation} or {@literal --tempLocation}, and
* select one of the Dataflow pipeline runners, eg
* {@literal --runner=BlockingDataflowRunner}.
*
* <p><b>Note:</b> this example creates entities with <i>Ancestor keys</i> to ensure that all
* entities created are in the same entity group. Similarly, the query used to read from the Cloud
* Datastore uses an <i>Ancestor filter</i>. Ancestors are used to ensure strongly consistent
* results in Cloud Datastore. For more information, see the Cloud Datastore documentation on
* <a href="https://cloud.google.com/datastore/docs/concepts/structuring_for_strong_consistency">
* Structing Data for Strong Consistency</a>.
*/
public class DatastoreWordCount {
/**
* A DoFn that gets the content of an entity (one line in a
* Shakespeare play) and converts it to a string.
*/
static class GetContentFn extends DoFn<Entity, String> {
@Override
public void processElement(ProcessContext c) {
Map<String, Value> props = c.element().getProperties();
Value value = props.get("content");
if (value != null) {
c.output(getString(value));
}
}
}
/**
* A helper function to create the ancestor key for all created and queried entities.
*
* <p>We use ancestor keys and ancestor queries for strong consistency. See
* {@link DatastoreWordCount} javadoc for more information.
*/
static Key makeAncestorKey(@Nullable String namespace, String kind) {
Key.Builder keyBuilder = makeKey(kind, "root");
if (namespace != null) {
keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace);
}
return keyBuilder.build();
}
/**
* A DoFn that creates entity for every line in Shakespeare.
*/
static class CreateEntityFn extends DoFn<String, Entity> {
private final String namespace;
private final String kind;
private final Key ancestorKey;
CreateEntityFn(String namespace, String kind) {
this.namespace = namespace;
this.kind = kind;
// Build the ancestor key for all created entities once, including the namespace.
ancestorKey = makeAncestorKey(namespace, kind);
}
public Entity makeEntity(String content) {
Entity.Builder entityBuilder = Entity.newBuilder();
// All created entities have the same ancestor Key.
Key.Builder keyBuilder = makeKey(ancestorKey, kind, UUID.randomUUID().toString());
// NOTE: Namespace is not inherited between keys created with DatastoreHelper.makeKey, so
// we must set the namespace on keyBuilder. TODO: Once partitionId inheritance is added,
// we can simplify this code.
if (namespace != null) {
keyBuilder.getPartitionIdBuilder().setNamespaceId(namespace);
}
entityBuilder.setKey(keyBuilder.build());
entityBuilder.getMutableProperties().put("content", makeValue(content).build());
return entityBuilder.build();
}
@Override
public void processElement(ProcessContext c) {
c.output(makeEntity(c.element()));
}
}
/**
* Options supported by {@link DatastoreWordCount}.
*
* <p>Inherits standard configuration options.
*/
public static interface Options extends PipelineOptions {
@Description("Path of the file to read from and store to Datastore")
@Default.String("gs://dataflow-samples/shakespeare/kinglear.txt")
String getInput();
void setInput(String value);
@Description("Path of the file to write to")
@Validation.Required
String getOutput();
void setOutput(String value);
@Description("Project ID to read from datastore")
@Validation.Required
String getProject();
void setProject(String value);
@Description("Datastore Entity kind")
@Default.String("shakespeare-demo")
String getKind();
void setKind(String value);
@Description("Datastore Namespace")
String getNamespace();
void setNamespace(@Nullable String value);
@Description("Read an existing project, do not write first")
boolean isReadOnly();
void setReadOnly(boolean value);
@Description("Number of output shards")
@Default.Integer(0) // If the system should choose automatically.
int getNumShards();
void setNumShards(int value);
}
/**
* An example that creates a pipeline to populate DatastoreIO from a
* text input. Forces use of DirectRunner for local execution mode.
*/
public static void writeDataToDatastore(Options options) {
Pipeline p = Pipeline.create(options);
p.apply("ReadLines", TextIO.Read.from(options.getInput()))
.apply(ParDo.of(new CreateEntityFn(options.getNamespace(), options.getKind())))
.apply(DatastoreIO.writeTo(options.getProject()));
p.run();
}
/**
* Build a Cloud Datastore ancestor query for the specified {@link Options#getNamespace} and
* {@link Options#getKind}.
*
* <p>We use ancestor keys and ancestor queries for strong consistency. See
* {@link DatastoreWordCount} javadoc for more information.
*
* @see <a href="https://cloud.google.com/datastore/docs/concepts/queries#Datastore_Ancestor_filters">Ancestor filters</a>
*/
static Query makeAncestorKindQuery(Options options) {
Query.Builder q = Query.newBuilder();
q.addKindBuilder().setName(options.getKind());
q.setFilter(makeFilter(
"__key__",
PropertyFilter.Operator.HAS_ANCESTOR,
makeValue(makeAncestorKey(options.getNamespace(), options.getKind()))));
return q.build();
}
/**
* An example that creates a pipeline to do DatastoreIO.Read from Datastore.
*/
public static void readDataFromDatastore(Options options) {
Query query = makeAncestorKindQuery(options);
// For Datastore sources, the read namespace can be set on the entire query.
DatastoreIO.Source source = DatastoreIO.source()
.withProject(options.getProject())
.withQuery(query)
.withNamespace(options.getNamespace());
Pipeline p = Pipeline.create(options);
p.apply("ReadShakespeareFromDatastore", Read.from(source))
.apply("StringifyEntity", ParDo.of(new GetContentFn()))
.apply("CountWords", new WordCount.CountWords())
.apply("PrintWordCount", MapElements.via(new WordCount.FormatAsTextFn()))
.apply("WriteLines", TextIO.Write.to(options.getOutput())
.withNumShards(options.getNumShards()));
p.run();
}
/**
* An example to demo how to use {@link DatastoreIO}. The runner here is
* customizable, which means users could pass either {@code DirectRunner}
* or {@code DataflowRunner} in the pipeline options.
*/
public static void main(String args[]) {
// The options are used in two places, for Dataflow service, and
// building DatastoreIO.Read object
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
if (!options.isReadOnly()) {
// First example: write data to Datastore for reading later.
//
// NOTE: this write does not delete any existing Entities in the Datastore, so if run
// multiple times with the same output project, there may be duplicate entries. The
// Datastore Query tool in the Google Developers Console can be used to inspect or erase all
// entries with a particular namespace and/or kind.
DatastoreWordCount.writeDataToDatastore(options);
}
// Second example: do parallel read from Datastore.
DatastoreWordCount.readDataFromDatastore(options);
}
}
| |
/* Copyright (c) 2011 Danish Maritime Authority.
*
* 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 dk.dma.dmiweather.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import dk.dma.common.dto.GeoCoordinate;
import dk.dma.common.exception.APIException;
import dk.dma.common.exception.ErrorMessage;
import dk.dma.dmiweather.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import static org.junit.Assert.*;
/**
* Tests with known data. To verify the data you can open the file in openCPN, https://opencpn.org/OpenCPN/info/downloads.html
* @author Klaus Groenbaek
* Created 31/03/17.
*/
@Slf4j
public class GridWeatherServiceTest {
@Test
public void topLeftVerticalLine2() throws Exception {
GridResponse response = makeRequest(r -> r.setNorthWest(new GeoCoordinate(9.0, 57.5))
.setSouthEast(new GeoCoordinate(9.0, 57.45)), true, Instant.now());
assertEquals("Point should all be empty", 0, response.getPoints().size());
}
@Test
public void allData() throws Exception {
GridResponse response = makeRequest(r-> r.setNorthWest(new GeoCoordinate(9.0, 57.5))
.setSouthEast(new GeoCoordinate(15.0, 53.0)).getParameters().setSeaLevel(true), false, Instant.now());
assertEquals("Number of dataPoints", 433 *541, response.getPoints().size());
// find the first datapoint with values
GridDataPoint found = null;
for (GridDataPoint dataPoint : response.getPoints()) {
if (dataPoint.getSeaLevel() != null && dataPoint.getWindDirection() != null && dataPoint.getWindSpeed() != null) {
found = dataPoint;
break;
}
}
assertTrue("Did not find a data point with all requested values", found != null);
}
@Test
public void allDataSampled() throws Exception {
int nx = 20;
int ny = 30;
GridResponse response = makeRequest(r-> r.setNorthWest(new GeoCoordinate(9.0, 57.5))
.setSouthEast(new GeoCoordinate(15.0, 53.0)).setNx(nx).setNy(ny).getParameters().setSeaLevel(true), false, Instant.now());
assertEquals("Number of dataPoints", nx * ny, response.getPoints().size());
List<GridDataPoint> found = new ArrayList<>();
for (GridDataPoint dataPoint : response.getPoints()) {
if (dataPoint.getSeaLevel() != null && dataPoint.getWindDirection() != null && dataPoint.getWindSpeed() != null) {
found.add(dataPoint);
}
}
assertEquals("Number of found data values after sampling", 183, found.size());
}
@Test
public void tooFarWest() throws Exception {
outsideGrid(r -> r.setNorthWest(new GeoCoordinate(8.0, 57.5))
.setSouthEast(new GeoCoordinate(15.0, 53.0)));
}
@Test
public void tooFarEast() throws Exception {
outsideGrid(r -> r.setNorthWest(new GeoCoordinate(9.0, 57.5))
.setSouthEast(new GeoCoordinate(16.0, 53.0)));
}
@Test
public void tooFarNorth() throws Exception {
outsideGrid(r -> r.setNorthWest(new GeoCoordinate(9.0, 59.5))
.setSouthEast(new GeoCoordinate(15.0, 53.0)));
}
@Test
public void tooFarSouth() throws Exception {
outsideGrid(r -> r.setNorthWest(new GeoCoordinate(9.0, 57.5))
.setSouthEast(new GeoCoordinate(15.0, 51.0)));
}
@Test
public void beforeFirstForcast() throws Exception {
try {
makeRequest(r->r.setTime(r.getTime().minus(3, ChronoUnit.DAYS)).setNorthWest(new GeoCoordinate(10.52, 57.5))
.setSouthEast(new GeoCoordinate(10.57, 57.5)), true, Instant.now());
fail("Should throw exception.");
} catch (APIException e) {
assertEquals(ErrorMessage.OUT_OF_DATE_RANGE, e.getError());
}
}
@Test
public void notOnTheHourRequest() throws Exception {
ZonedDateTime departure = ZonedDateTime.now(ZoneOffset.UTC).withMonth(3).withDayOfMonth(30).withHour(12).withMinute(29).withSecond(0).withNano(0);
GridResponse response = makeRequest(r -> r.setTime(departure.toInstant()).setNorthWest(new GeoCoordinate(10.52, 57.5))
.setSouthEast(new GeoCoordinate(10.57, 57.5)), false, Instant.now());
assertEquals(departure.withMinute(0).toInstant(), response.getForecastDate()) ;
}
@Test
public void notOnTheHourRequest2() throws Exception {
ZonedDateTime departure = ZonedDateTime.now(ZoneOffset.UTC).withMonth(3).withDayOfMonth(30).withHour(12).withMinute(31).withSecond(0).withNano(0);
GridResponse response = makeRequest(r -> r.setTime(departure.toInstant()).setNorthWest(new GeoCoordinate(10.52, 57.5))
.setSouthEast(new GeoCoordinate(10.57, 57.5)), false, Instant.now());
assertEquals(departure.withMinute(0).plusHours(1).toInstant(), response.getForecastDate()) ;
}
@Test
public void westLargerThanEast() throws Exception {
try {
makeRequest(r -> r.setNorthWest(new GeoCoordinate(12.0, 57.5))
.setSouthEast(new GeoCoordinate(11.0, 53.0)), true, Instant.now());
fail("Request not valid");
} catch (APIException e) {
assertEquals(ErrorMessage.INVALID_GRID_LOT, e.getError());
}
}
@Test
public void southLargerThanNorth() throws Exception {
try {
makeRequest(r -> r.setNorthWest(new GeoCoordinate(11.0, 54.5))
.setSouthEast(new GeoCoordinate(12.0, 55.0)), true, Instant.now());
fail("Request not valid");
} catch (APIException e) {
assertEquals(ErrorMessage.INVALID_GRID_LAT, e.getError());
}
}
private void outsideGrid(CoordinateConfigurer configurer) throws IOException {
try {
makeRequest(configurer, false, Instant.now());
fail("Should throw IllegalArgumentException");
} catch (APIException e) {
assertEquals(ErrorMessage.OUTSIDE_GRID, e.getError());
}
}
private void check(CoordinateConfigurer configurer, String resultFile) throws IOException {
Instant now = Instant.now();
GridResponse response = makeRequest(configurer, false, now);
log.info(new ObjectMapper().registerModule(new JavaTimeModule()).writerWithDefaultPrettyPrinter().writeValueAsString(response));
ClassPathResource json = new ClassPathResource(resultFile, getClass());
try (InputStream inputStream = json.getInputStream()) {
GridResponse expected = new ObjectMapper().registerModule(new JavaTimeModule()).readValue(inputStream, GridResponse.class);
expected.setQueryTime(response.getQueryTime()); // copy the query time since we don't control that
for (ForecastInfo forecastInfo : expected.getForecasts()) {
forecastInfo.setCreationDate(now);
}
assertEquals(expected, response);
}
}
private GridResponse makeRequest(CoordinateConfigurer configurer, boolean removeEmpty, Instant now) throws IOException {
ClassPathResource resource1 = new ClassPathResource("DMI_metocean_DK.2017033012.grb", getClass());
ClassPathResource resource2 = new ClassPathResource("DMI_metocean_DK.2017033013.grb", getClass());
WeatherService service = new WeatherService(3, 5);
Map<File, Instant> map = new HashMap<>();
map.put(resource1.getFile(), now);
map.put(resource2.getFile(), now);
service.newFiles( map, ForecastConfiguration.DANISH_METOCEAN_SHELF);
ZonedDateTime departure = ZonedDateTime.now(ZoneOffset.UTC).withMonth(3).withDayOfMonth(30).withHour(12).withMinute(0).withSecond(0).withNano(0);
// Request for a rather small piece close to Skagen where the first non-null data points exist
GridRequest request = new GridRequest().setParameters(new GridParameters().setWind(true)).setTime(departure.toInstant());
configurer.setCoordinates(request);
return service.request(request, removeEmpty, false);
}
@FunctionalInterface
private interface CoordinateConfigurer {
void setCoordinates(GridRequest request);
}
}
| |
package org.drools.compiler.rule.builder.dialect.mvel;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.drools.compiler.commons.jci.readers.MemoryResourceReader;
import org.drools.compiler.compiler.AnalysisResult;
import org.drools.compiler.compiler.BoundIdentifiers;
import org.drools.compiler.compiler.DescrBuildError;
import org.drools.compiler.compiler.Dialect;
import org.drools.compiler.compiler.ImportError;
import org.drools.compiler.compiler.PackageRegistry;
import org.drools.compiler.lang.descr.AccumulateDescr;
import org.drools.compiler.lang.descr.AndDescr;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.CollectDescr;
import org.drools.compiler.lang.descr.ConditionalBranchDescr;
import org.drools.compiler.lang.descr.EntryPointDescr;
import org.drools.compiler.lang.descr.EvalDescr;
import org.drools.compiler.lang.descr.ExistsDescr;
import org.drools.compiler.lang.descr.ForallDescr;
import org.drools.compiler.lang.descr.FromDescr;
import org.drools.compiler.lang.descr.FunctionDescr;
import org.drools.compiler.lang.descr.ImportDescr;
import org.drools.compiler.lang.descr.NamedConsequenceDescr;
import org.drools.compiler.lang.descr.NotDescr;
import org.drools.compiler.lang.descr.OrDescr;
import org.drools.compiler.lang.descr.PatternDescr;
import org.drools.compiler.lang.descr.ProcessDescr;
import org.drools.compiler.lang.descr.QueryDescr;
import org.drools.compiler.lang.descr.RuleDescr;
import org.drools.compiler.lang.descr.WindowReferenceDescr;
import org.drools.compiler.rule.builder.AccumulateBuilder;
import org.drools.compiler.rule.builder.CollectBuilder;
import org.drools.compiler.rule.builder.ConditionalBranchBuilder;
import org.drools.compiler.rule.builder.ConsequenceBuilder;
import org.drools.compiler.rule.builder.EnabledBuilder;
import org.drools.compiler.rule.builder.EngineElementBuilder;
import org.drools.compiler.rule.builder.EntryPointBuilder;
import org.drools.compiler.rule.builder.ForallBuilder;
import org.drools.compiler.rule.builder.FromBuilder;
import org.drools.compiler.rule.builder.GroupElementBuilder;
import org.drools.compiler.rule.builder.NamedConsequenceBuilder;
import org.drools.compiler.rule.builder.PackageBuildContext;
import org.drools.compiler.rule.builder.PatternBuilder;
import org.drools.compiler.rule.builder.PredicateBuilder;
import org.drools.compiler.rule.builder.QueryBuilder;
import org.drools.compiler.rule.builder.ReturnValueBuilder;
import org.drools.compiler.rule.builder.RuleBuildContext;
import org.drools.compiler.rule.builder.RuleClassBuilder;
import org.drools.compiler.rule.builder.RuleConditionBuilder;
import org.drools.compiler.rule.builder.SalienceBuilder;
import org.drools.compiler.rule.builder.WindowReferenceBuilder;
import org.drools.compiler.rule.builder.dialect.DialectUtil;
import org.drools.compiler.rule.builder.dialect.java.JavaFunctionBuilder;
import org.drools.core.base.EvaluatorWrapper;
import org.drools.core.base.TypeResolver;
import org.drools.core.base.mvel.MVELCompilationUnit;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.rule.Declaration;
import org.drools.core.rule.LineMappings;
import org.drools.core.rule.MVELDialectRuntimeData;
import org.drools.core.spi.KnowledgeHelper;
import org.drools.core.util.StringUtils;
import org.kie.api.definition.rule.Rule;
import org.kie.api.io.Resource;
import org.kie.internal.builder.KnowledgeBuilderResult;
import org.mvel2.MVEL;
import org.mvel2.optimizers.OptimizerFactory;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MVELDialect
implements
Dialect,
Externalizable {
private String id = "mvel";
private final static String EXPRESSION_DIALECT_NAME = "MVEL";
protected static final PatternBuilder PATTERN_BUILDER = new PatternBuilder();
protected static final QueryBuilder QUERY_BUILDER = new QueryBuilder();
protected static final MVELAccumulateBuilder ACCUMULATE_BUILDER = new MVELAccumulateBuilder();
protected static final SalienceBuilder SALIENCE_BUILDER = new MVELSalienceBuilder();
protected static final EnabledBuilder ENABLED_BUILDER = new MVELEnabledBuilder();
protected static final MVELEvalBuilder EVAL_BUILDER = new MVELEvalBuilder();
protected static final MVELPredicateBuilder PREDICATE_BUILDER = new MVELPredicateBuilder();
protected static final MVELReturnValueBuilder RETURN_VALUE_BUILDER = new MVELReturnValueBuilder();
protected static final MVELConsequenceBuilder CONSEQUENCE_BUILDER = new MVELConsequenceBuilder();
protected static final MVELFromBuilder FROM_BUILDER = new MVELFromBuilder();
protected static final JavaFunctionBuilder FUNCTION_BUILDER = new JavaFunctionBuilder();
protected static final CollectBuilder COLLECT_BUILDER = new CollectBuilder();
protected static final ForallBuilder FORALL_BUILDER = new ForallBuilder();
protected static final EntryPointBuilder ENTRY_POINT_BUILDER = new EntryPointBuilder();
protected static final WindowReferenceBuilder WINDOW_REFERENCE_BUILDER = new WindowReferenceBuilder();
protected static final GroupElementBuilder GE_BUILDER = new GroupElementBuilder();
protected static final NamedConsequenceBuilder NAMED_CONSEQUENCE_BUILDER = new NamedConsequenceBuilder();
protected static final ConditionalBranchBuilder CONDITIONAL_BRANCH_BUILDER = new ConditionalBranchBuilder();
// a map of registered builders
private static Map<Class< ? >, EngineElementBuilder> builders;
static {
initBuilder();
}
private static final MVELExprAnalyzer analyzer = new MVELExprAnalyzer();
private final Map interceptors = MVELCompilationUnit.INTERCEPTORS;
protected List<KnowledgeBuilderResult> results;
// private final JavaFunctionBuilder function = new JavaFunctionBuilder();
protected MemoryResourceReader src;
protected InternalKnowledgePackage pkg;
private MVELDialectConfiguration configuration;
private PackageRegistry packageRegistry;
private boolean strictMode;
private int languageLevel;
private MVELDialectRuntimeData data;
private final ClassLoader rootClassLoader;
static {
// always use mvel reflective optimizer
OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);
}
public MVELDialect(ClassLoader rootClassLoader,
KnowledgeBuilderConfigurationImpl pkgConf,
PackageRegistry pkgRegistry,
InternalKnowledgePackage pkg) {
this( rootClassLoader,
pkgConf,
pkgRegistry,
pkg,
"mvel" );
}
public MVELDialect(ClassLoader rootClassLoader,
KnowledgeBuilderConfigurationImpl pkgConf,
PackageRegistry pkgRegistry,
InternalKnowledgePackage pkg,
String id) {
this.rootClassLoader = rootClassLoader;
this.id = id;
this.pkg = pkg;
this.packageRegistry = pkgRegistry;
this.configuration = (MVELDialectConfiguration) pkgConf.getDialectConfiguration("mvel");
setLanguageLevel( this.configuration.getLangLevel() );
this.strictMode = this.configuration.isStrict();
// setting MVEL option directly
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
this.results = new ArrayList<KnowledgeBuilderResult>();
// this.data = new MVELDialectRuntimeData(
// this.pkg.getDialectRuntimeRegistry() );
//
// this.pkg.getDialectRuntimeRegistry().setDialectData( ID,
// this.data );
// initialise the dialect runtime data if it doesn't already exist
if ( pkg.getDialectRuntimeRegistry().getDialectData( getId() ) == null ) {
data = new MVELDialectRuntimeData();
this.pkg.getDialectRuntimeRegistry().setDialectData( getId(),
data );
data.onAdd( this.pkg.getDialectRuntimeRegistry(),
rootClassLoader );
} else {
data = (MVELDialectRuntimeData) this.pkg.getDialectRuntimeRegistry().getDialectData( "mvel" );
}
this.results = new ArrayList<KnowledgeBuilderResult>();
this.src = new MemoryResourceReader();
if ( this.pkg != null ) {
this.addImport( new ImportDescr( this.pkg.getName() + ".*" ) );
}
this.addImport( new ImportDescr( "java.lang.*" ) );
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
results = (List<KnowledgeBuilderResult>) in.readObject();
src = (MemoryResourceReader) in.readObject();
pkg = (InternalKnowledgePackage) in.readObject();
packageRegistry = (PackageRegistry) in.readObject();
configuration = (MVELDialectConfiguration) in.readObject();
strictMode = in.readBoolean();
data = (MVELDialectRuntimeData) this.pkg.getDialectRuntimeRegistry().getDialectData( "mvel" );
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( results );
out.writeObject( src );
out.writeObject( pkg );
out.writeObject( packageRegistry );
out.writeObject( configuration );
out.writeBoolean( strictMode );
out.writeObject( data );
}
public void setLanguageLevel(int languageLevel) {
this.languageLevel = languageLevel;
}
// public static void setLanguageLevel(int level) {
// synchronized ( lang ) {
// // this synchronisation is needed as setLanguageLevel is not thread safe
// // and we do not want to be calling this while something else is being
// parsed.
// // the flag ensures it is just called once and no more.
// if ( languageSet.booleanValue() == false ) {
// languageSet = new Boolean( true );
// AbstractParser.setLanguageLevel( level );
// }
// }
// }
public static void initBuilder() {
if ( builders != null ) {
return;
}
reinitBuilder();
}
public static void reinitBuilder() {
// statically adding all builders to the map
// but in the future we can move that to a configuration
// if we want to
builders = new HashMap<Class< ? >, EngineElementBuilder>();
builders.put( AndDescr.class,
GE_BUILDER );
builders.put( OrDescr.class,
GE_BUILDER );
builders.put( NotDescr.class,
GE_BUILDER );
builders.put( ExistsDescr.class,
GE_BUILDER );
builders.put( PatternDescr.class,
PATTERN_BUILDER );
builders.put( FromDescr.class,
FROM_BUILDER );
builders.put( QueryDescr.class,
QUERY_BUILDER );
builders.put( AccumulateDescr.class,
ACCUMULATE_BUILDER );
builders.put( EvalDescr.class,
EVAL_BUILDER );
builders.put( CollectDescr.class,
COLLECT_BUILDER );
builders.put( ForallDescr.class,
FORALL_BUILDER );
builders.put( FunctionDescr.class,
FUNCTION_BUILDER );
builders.put( EntryPointDescr.class,
ENTRY_POINT_BUILDER );
builders.put( WindowReferenceDescr.class,
WINDOW_REFERENCE_BUILDER );
builders.put( NamedConsequenceDescr.class,
NAMED_CONSEQUENCE_BUILDER );
builders.put( ConditionalBranchDescr.class,
CONDITIONAL_BRANCH_BUILDER );
}
public void init(RuleDescr ruleDescr) {
// MVEL:test null to Fix failing test on
// org.kie.rule.builder.dialect.
// mvel.MVELConsequenceBuilderTest.testImperativeCodeError()
// @todo: why is this here, MVEL doesn't compile anything? mdp
String pkgName = this.pkg == null ? "" : this.pkg.getName();
final String ruleClassName = DialectUtil.getUniqueLegalName( pkgName,
ruleDescr.getName(),
ruleDescr.getConsequence().hashCode(),
"mvel",
"Rule",
this.src );
ruleDescr.setClassName( StringUtils.ucFirst( ruleClassName ) );
}
public void init(final ProcessDescr processDescr) {
final String processDescrClassName = DialectUtil.getUniqueLegalName( this.pkg.getName(),
processDescr.getName(),
processDescr.getProcessId().hashCode(),
"mvel",
"Process",
this.src );
processDescr.setClassName( StringUtils.ucFirst( processDescrClassName ) );
}
public String getExpressionDialectName() {
return EXPRESSION_DIALECT_NAME;
}
public void addRule(RuleBuildContext context) {
// MVEL: Compiler change
final RuleDescr ruleDescr = context.getRuleDescr();
// setup the line mappins for this rule
final String name = this.pkg.getName() + "." + StringUtils.ucFirst( ruleDescr.getClassName() );
final LineMappings mapping = new LineMappings( name );
mapping.setStartLine( ruleDescr.getConsequenceLine() );
mapping.setOffset( ruleDescr.getConsequenceOffset() );
context.getPkg().getDialectRuntimeRegistry().getLineMappings().put( name,
mapping );
}
public void addFunction(FunctionDescr functionDescr,
TypeResolver typeResolver,
Resource resource) {
// Serializable s1 = compile( (String) functionDescr.getText(),
// null,
// null,
// null,
// null,
// null );
//
// final ParserContext parserContext = getParserContext( analysis,
// outerDeclarations,
// otherInputVariables,
// context );
// return MVELCompilationUnit.compile( text, pkgBuilder.getRootClassLoader(), parserContext, languageLevel );
//
// Map<String, org.mvel2.ast.Function> map = org.mvel2.util.CompilerTools.extractAllDeclaredFunctions( (org.mvel2.compiler.CompiledExpression) s1 );
// MVELDialectRuntimeData data = (MVELDialectRuntimeData) this.packageRegistry.getDialectRuntimeRegistry().getDialectData( getId() );
// for ( org.mvel2.ast.Function function : map.values() ) {
// data.addFunction( function );
// }
}
public void preCompileAddFunction(FunctionDescr functionDescr,
TypeResolver typeResolver) {
}
public void postCompileAddFunction(FunctionDescr functionDescr,
TypeResolver typeResolver) {
}
public void addImport(ImportDescr importDescr) {
String importEntry = importDescr.getTarget();
if ( importEntry.endsWith( ".*" ) ) {
importEntry = importEntry.substring( 0,
importEntry.length() - 2 );
data.addPackageImport( importEntry );
} else {
try {
Class cls = this.packageRegistry.getTypeResolver().resolveType( importEntry );
data.addImport( cls.getSimpleName(), cls );
} catch ( ClassNotFoundException e ) {
this.results.add( new ImportError( importDescr, 1 ) );
}
}
}
public void addStaticImport(ImportDescr importDescr) {
String staticImportEntry = importDescr.getTarget();
if ( staticImportEntry.endsWith( "*" ) ) {
addStaticPackageImport( importDescr );
return;
}
int index = staticImportEntry.lastIndexOf( '.' );
String className = staticImportEntry.substring( 0, index );
String methodName = staticImportEntry.substring( index + 1 );
try {
Class cls = this.packageRegistry.getPackageClassLoader().loadClass( className );
if ( cls != null ) {
// First try and find a matching method
for ( Method method : cls.getDeclaredMethods() ) {
if ( method.getName().equals( methodName ) ) {
this.data.addImport( methodName, method );
return;
}
}
//no matching method, so now try and find a matching public property
for ( Field field : cls.getFields() ) {
if ( field.isAccessible() && field.getName().equals( methodName ) ) {
this.data.addImport( methodName, field );
return;
}
}
}
} catch ( ClassNotFoundException e ) {
}
// we never managed to make the import, so log an error
this.results.add( new ImportError( importDescr, -1 ) );
}
public void addStaticPackageImport(ImportDescr importDescr) {
String staticImportEntry = importDescr.getTarget();
int index = staticImportEntry.lastIndexOf( '.' );
String className = staticImportEntry.substring( 0, index );
Class cls = null;
try {
cls = rootClassLoader.loadClass(className);
} catch ( ClassNotFoundException e ) {
}
if ( cls == null ) {
results.add( new ImportError( importDescr, -1 ) );
return;
}
for ( Method method : cls.getDeclaredMethods() ) {
if ( (method.getModifiers() | Modifier.STATIC) > 0 ) {
this.data.addImport( method.getName(), method );
}
}
for ( Field field : cls.getFields() ) {
if ( field.isAccessible() && (field.getModifiers() | Modifier.STATIC) > 0 ) {
this.data.addImport( field.getName(), field );
return;
}
}
}
// private Map staticFieldImports = new HashMap();
// private Map staticMethodImports = new HashMap();
public boolean isStrictMode() {
return strictMode;
}
public void setStrictMode(boolean strictMode) {
this.strictMode = strictMode;
}
public void compileAll() {
}
public AnalysisResult analyzeExpression(final PackageBuildContext context,
final BaseDescr descr,
final Object content,
final BoundIdentifiers availableIdentifiers) {
return analyzeExpression( context,
descr,
content,
availableIdentifiers,
null );
}
public AnalysisResult analyzeExpression(final PackageBuildContext context,
final BaseDescr descr,
final Object content,
final BoundIdentifiers availableIdentifiers,
final Map<String, Class< ? >> localTypes) {
AnalysisResult result = null;
// the following is required for proper error handling
BaseDescr temp = context.getParentDescr();
context.setParentDescr( descr );
try {
result = analyzer.analyzeExpression( context,
(String) content,
availableIdentifiers,
localTypes,
"drools",
KnowledgeHelper.class );
} catch ( final Exception e ) {
DialectUtil.copyErrorLocation( e, descr );
context.addError( new DescrBuildError( context.getParentDescr(),
descr,
null,
"Unable to determine the used declarations.\n" + e.getMessage() ) );
} finally {
// setting it back to original parent descr
context.setParentDescr( temp );
}
return result;
}
public AnalysisResult analyzeBlock(final PackageBuildContext context,
final BaseDescr descr,
final String text,
final BoundIdentifiers availableIdentifiers) {
return analyzeBlock( context,
descr,
null,
text,
availableIdentifiers,
null,
"drools",
KnowledgeHelper.class );
}
public AnalysisResult analyzeBlock(final PackageBuildContext context,
final BaseDescr descr,
final Map interceptors,
final String text,
final BoundIdentifiers availableIdentifiers,
final Map<String, Class< ? >> localTypes,
String contextIndeifier,
Class kcontextClass) {
return analyzer.analyzeExpression( context,
text,
availableIdentifiers,
localTypes,
contextIndeifier,
kcontextClass );
}
public MVELCompilationUnit getMVELCompilationUnit(final String expression,
final AnalysisResult analysis,
Declaration[] previousDeclarations,
Declaration[] localDeclarations,
final Map<String, Class< ? >> otherInputVariables,
final PackageBuildContext context,
String contextIndeifier,
Class kcontextClass) {
return getMVELCompilationUnit( expression,
analysis,
previousDeclarations,
localDeclarations,
otherInputVariables,
context,
contextIndeifier,
kcontextClass,
false );
}
public MVELCompilationUnit getMVELCompilationUnit(final String expression,
final AnalysisResult analysis,
Declaration[] previousDeclarations,
Declaration[] localDeclarations,
final Map<String, Class< ? >> otherInputVariables,
final PackageBuildContext context,
String contextIndeifier,
Class kcontextClass,
boolean readLocalsFromTuple) {
Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>();
List<String> ids = new ArrayList<String>();
if ( analysis.getBoundIdentifiers().getThisClass() != null || (localDeclarations != null && localDeclarations.length > 0) ) {
Class cls = analysis.getBoundIdentifiers().getThisClass();
ids.add( "this" );
resolvedInputs.put( "this",
(cls != null) ? cls : Object.class ); // the only time cls is null is in accumumulate's acc/reverse
}
ids.add( contextIndeifier );
resolvedInputs.put( contextIndeifier,
kcontextClass );
ids.add( "kcontext" );
resolvedInputs.put( "kcontext",
kcontextClass );
ids.add( "rule" );
resolvedInputs.put( "rule",
Rule.class );
List<String> strList = new ArrayList<String>();
for ( Entry<String, Class< ? >> e : analysis.getBoundIdentifiers().getGlobals().entrySet() ) {
strList.add( e.getKey() );
ids.add( e.getKey() );
resolvedInputs.put( e.getKey(), e.getValue() );
}
String[] globalIdentifiers = strList.toArray( new String[strList.size()] );
strList.clear();
for ( String op : analysis.getBoundIdentifiers().getOperators().keySet() ) {
strList.add( op );
ids.add( op );
resolvedInputs.put( op, context.getConfiguration().getComponentFactory().getExpressionProcessor().getEvaluatorWrapperClass() );
}
EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()];
for ( int i = 0; i < operators.length; i++ ) {
operators[i] = analysis.getBoundIdentifiers().getOperators().get( strList.get( i ) );
}
if ( previousDeclarations != null ) {
for ( Declaration decl : previousDeclarations ) {
if ( analysis.getBoundIdentifiers().getDeclrClasses().containsKey( decl.getIdentifier() ) ) {
ids.add( decl.getIdentifier() );
resolvedInputs.put( decl.getIdentifier(),
decl.getExtractor().getExtractToClass() );
}
}
}
if ( localDeclarations != null ) {
for ( Declaration decl : localDeclarations ) {
if ( analysis.getBoundIdentifiers().getDeclrClasses().containsKey( decl.getIdentifier() ) ) {
ids.add( decl.getIdentifier() );
resolvedInputs.put( decl.getIdentifier(),
decl.getExtractor().getExtractToClass() );
}
}
}
// "not bound" identifiers could be drools, kcontext and rule
// but in the case of accumulate it could be vars from the "init" section.
//String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()];
strList = new ArrayList<String>();
if ( otherInputVariables != null ) {
MVELAnalysisResult mvelAnalysis = (MVELAnalysisResult) analysis;
for ( Entry<String, Class< ? >> stringClassEntry : otherInputVariables.entrySet() ) {
if ( (!analysis.getNotBoundedIdentifiers().contains( stringClassEntry.getKey() ) && !mvelAnalysis.getMvelVariables().keySet().contains( stringClassEntry.getKey() )) || "rule".equals( stringClassEntry.getKey() ) ) {
// no point including them if they aren't used
// and rule was already included
continue;
}
ids.add( stringClassEntry.getKey() );
strList.add( stringClassEntry.getKey() );
resolvedInputs.put( stringClassEntry.getKey(), stringClassEntry.getValue() );
}
}
String[] otherIdentifiers = strList.toArray( new String[strList.size()] );
String[] inputIdentifiers = new String[resolvedInputs.size()];
String[] inputTypes = new String[resolvedInputs.size()];
int i = 0;
for ( String id : ids ) {
inputIdentifiers[i] = id;
inputTypes[i++] = resolvedInputs.get( id ).getName();
}
String name;
if ( context != null && context.getPkg() != null && context.getPkg().getName() != null ) {
if ( context instanceof RuleBuildContext ) {
name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName();
} else {
name = context.getPkg().getName() + ".Unknown";
}
} else {
name = "Unknown";
}
return new MVELCompilationUnit( name,
expression,
globalIdentifiers,
operators,
previousDeclarations,
localDeclarations,
otherIdentifiers,
inputIdentifiers,
inputTypes,
languageLevel,
((MVELAnalysisResult) analysis).isTypesafe(),
readLocalsFromTuple );
}
public EngineElementBuilder getBuilder(final Class clazz) {
return builders.get( clazz );
}
public Map<Class< ? >, EngineElementBuilder> getBuilders() {
return builders;
}
public PatternBuilder getPatternBuilder() {
return PATTERN_BUILDER;
}
public QueryBuilder getQueryBuilder() {
return QUERY_BUILDER;
}
public AccumulateBuilder getAccumulateBuilder() {
return ACCUMULATE_BUILDER;
}
public ConsequenceBuilder getConsequenceBuilder() {
return CONSEQUENCE_BUILDER;
}
public RuleConditionBuilder getEvalBuilder() {
return EVAL_BUILDER;
}
public FromBuilder getFromBuilder() {
return FROM_BUILDER;
}
public EntryPointBuilder getEntryPointBuilder() {
return ENTRY_POINT_BUILDER;
}
public PredicateBuilder getPredicateBuilder() {
return PREDICATE_BUILDER;
}
public PredicateBuilder getExpressionPredicateBuilder() {
return PREDICATE_BUILDER;
}
public SalienceBuilder getSalienceBuilder() {
return SALIENCE_BUILDER;
}
public EnabledBuilder getEnabledBuilder() {
return ENABLED_BUILDER;
}
public List<KnowledgeBuilderResult> getResults() {
return results;
}
public void clearResults() {
this.results.clear();
}
public ReturnValueBuilder getReturnValueBuilder() {
return RETURN_VALUE_BUILDER;
}
public RuleClassBuilder getRuleClassBuilder() {
throw new UnsupportedOperationException( "MVELDialect.getRuleClassBuilder is not supported" );
}
public TypeResolver getTypeResolver() {
return this.packageRegistry.getTypeResolver();
}
public Map getInterceptors() {
return this.interceptors;
}
public String getId() {
return this.id;
}
public PackageRegistry getPackageRegistry() {
return this.packageRegistry;
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.maddyhome.idea.copyright.psi;
import com.intellij.lang.Commenter;
import com.intellij.lang.LanguageCommenters;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.IncorrectOperationException;
import com.maddyhome.idea.copyright.CopyrightManager;
import com.maddyhome.idea.copyright.CopyrightProfile;
import com.maddyhome.idea.copyright.options.LanguageOptions;
import com.maddyhome.idea.copyright.util.FileTypeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public abstract class UpdatePsiFileCopyright extends AbstractUpdateCopyright {
private static final Logger LOG = Logger.getInstance("#" + UpdatePsiFileCopyright.class.getName());
private final CopyrightProfile myOptions;
protected UpdatePsiFileCopyright(Project project, Module module, VirtualFile root, CopyrightProfile options) {
super(project, module, root, options);
myOptions = options;
PsiManager manager = PsiManager.getInstance(project);
file = manager.findFile(root);
FileType type = FileTypeUtil.getInstance().getFileTypeByFile(root);
langOpts = CopyrightManager.getInstance(project).getOptions().getMergedOptions(type.getName());
}
@Override
public void prepare() {
if (file == null) {
logger.info("No file for root: " + getRoot());
return;
}
if (accept()) {
scanFile();
}
}
@Override
public void complete() throws Exception {
complete(true);
}
public void complete(boolean allowReplacement) throws Exception {
if (file == null) {
logger.info("No file for root: " + getRoot());
return;
}
if (accept()) {
processActions(allowReplacement);
}
}
protected boolean accept() {
return !(file instanceof PsiPlainTextFile);
}
protected abstract void scanFile();
protected void checkComments(PsiElement first, PsiElement last, boolean commentHere) {
List<PsiComment> comments = new ArrayList<>();
collectComments(first, last, comments);
checkComments(last, commentHere, comments);
}
protected void collectComments(PsiElement first, PsiElement last, List<PsiComment> comments) {
if (first == last && first instanceof PsiComment) {
comments.add((PsiComment)first);
return;
}
PsiElement elem = first;
while (elem != last && elem != null) {
if (elem instanceof PsiComment) {
comments.add((PsiComment)elem);
logger.debug("found comment");
}
elem = getNextSibling(elem);
}
}
protected void checkComments(PsiElement last, boolean commentHere, List<PsiComment> comments) {
try {
final String keyword = myOptions.getKeyword();
final LinkedHashSet<CommentRange> found = new LinkedHashSet<>();
Document doc = null;
if (!StringUtil.isEmpty(keyword)) {
Pattern pattern = Pattern.compile(StringUtil.escapeToRegexp(keyword), Pattern.CASE_INSENSITIVE);
doc = FileDocumentManager.getInstance().getDocument(getFile().getVirtualFile());
for (int i = 0; i < comments.size(); i++) {
PsiComment comment = comments.get(i);
String text = comment.getText();
Matcher match = pattern.matcher(text);
if (match.find()) {
found.add(getLineCopyrightComments(comments, doc, i, comment));
}
}
}
// Default insertion point to just before user chosen marker (package, import, class)
PsiElement point = last;
if (commentHere && !comments.isEmpty() && langOpts.isRelativeBefore()) {
// Insert before first comment within this section of code.
point = comments.get(0);
}
if (commentHere && found.size() == 1) {
CommentRange range = found.iterator().next();
// Is the comment in the right place?
if (langOpts.isRelativeBefore() && range.getFirst() == comments.get(0) ||
!langOpts.isRelativeBefore() && range.getLast() == comments.get(comments.size() - 1)) {
// Check to see if current copyright comment matches new one.
String newComment = getCommentText("", "");
resetCommentText();
String oldComment = doc.getCharsSequence()
.subSequence(range.getFirst().getTextRange().getStartOffset(), range.getLast().getTextRange().getEndOffset()).toString().trim();
if (!StringUtil.isEmptyOrSpaces(myOptions.getAllowReplaceKeyword()) &&
!oldComment.contains(myOptions.getAllowReplaceKeyword())) {
return;
}
if (newComment.trim().equals(oldComment)) {
if (!getLanguageOptions().isAddBlankAfter()) {
// TODO - do we need option to remove blank line after?
return; // Nothing to do since the comment is the same
}
PsiElement next = getNextSibling(range.getLast());
if (next != null) {
final String text = next.getText();
if (StringUtil.isEmptyOrSpaces(text) && countNewline(text) > 1) {
return;
}
}
point = range.getFirst();
}
else if (!newComment.isEmpty()) {
int start = range.getFirst().getTextRange().getStartOffset();
int end = range.getLast().getTextRange().getEndOffset();
addAction(new CommentAction(CommentAction.ACTION_REPLACE, start, end));
return;
}
}
}
for (CommentRange range : found) {
// Remove the old copyright
int start = range.getFirst().getTextRange().getStartOffset();
int end = range.getLast().getTextRange().getEndOffset();
// If this is the only comment then remove the whitespace after unless there is none before
if (range.getFirst() == comments.get(0) && range.getLast() == comments.get(comments.size() - 1)) {
int startLen = 0;
if (getPreviousSibling(range.getFirst()) instanceof PsiWhiteSpace) {
startLen = countNewline(getPreviousSibling(range.getFirst()).getText());
}
int endLen = 0;
if (getNextSibling(range.getLast()) instanceof PsiWhiteSpace) {
endLen = countNewline(getNextSibling(range.getLast()).getText());
}
if (startLen == 1 && getPreviousSibling(range.getFirst()).getTextRange().getStartOffset() > 0) {
start = getPreviousSibling(range.getFirst()).getTextRange().getStartOffset();
}
else if (endLen > 0) {
end = getNextSibling(range.getLast()).getTextRange().getEndOffset();
}
}
// If this is the last comment then remove the whitespace before the comment
else if (range.getLast() == comments.get(comments.size() - 1)) {
if (getPreviousSibling(range.getFirst()) instanceof PsiWhiteSpace &&
countNewline(getPreviousSibling(range.getFirst()).getText()) > 1) {
start = getPreviousSibling(range.getFirst()).getTextRange().getStartOffset();
}
}
// If this is the first or middle comment then remove the whitespace after the comment
else if (getNextSibling(range.getLast()) instanceof PsiWhiteSpace) {
end = getNextSibling(range.getLast()).getTextRange().getEndOffset();
}
addAction(new CommentAction(CommentAction.ACTION_DELETE, start, end));
}
// Finally add the comment if user chose this section.
if (commentHere) {
String suffix = "\n";
if (point != last && getPreviousSibling(point) != null && getPreviousSibling(point) instanceof PsiWhiteSpace) {
suffix = getPreviousSibling(point).getText();
if (countNewline(suffix) == 1) {
suffix = '\n' + suffix;
}
}
if (point != last && getPreviousSibling(point) == null) {
suffix = "\n\n";
}
if (getLanguageOptions().isAddBlankAfter() && countNewline(suffix) == 1) {
suffix += "\n";
}
String prefix = "";
if (getPreviousSibling(point) != null) {
if (getPreviousSibling(point) instanceof PsiComment) {
prefix = "\n\n";
}
if (getPreviousSibling(point) instanceof PsiWhiteSpace &&
getPreviousSibling(getPreviousSibling(point)) != null &&
getPreviousSibling(getPreviousSibling(point)) instanceof PsiComment) {
String ws = getPreviousSibling(point).getText();
int cnt = countNewline(ws);
if (cnt == 1) {
prefix = "\n";
}
}
}
int pos = 0;
if (point != null) {
final TextRange textRange = point.getTextRange();
if (textRange != null) {
pos = textRange.getStartOffset();
}
}
addAction(new CommentAction(pos, prefix, suffix));
}
}
catch (PatternSyntaxException ignore) {
}
catch (Exception e) {
logger.error(e);
}
}
private static CommentRange getLineCopyrightComments(List<PsiComment> comments, Document doc, int i, PsiComment comment) {
PsiElement firstComment = comment;
PsiElement lastComment = comment;
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(PsiUtilCore.findLanguageFromElement(comment));
if (isLineComment(commenter, comment, doc)) {
int sline = doc.getLineNumber(comment.getTextRange().getStartOffset());
int eline = doc.getLineNumber(comment.getTextRange().getEndOffset());
for (int j = i - 1; j >= 0; j--) {
PsiComment cmt = comments.get(j);
if (isLineComment(commenter, cmt, doc) && doc.getLineNumber(cmt.getTextRange().getEndOffset()) == sline - 1) {
firstComment = cmt;
sline = doc.getLineNumber(cmt.getTextRange().getStartOffset());
}
else {
break;
}
}
for (int j = i + 1; j < comments.size(); j++) {
PsiComment cmt = comments.get(j);
if (isLineComment(commenter, cmt, doc) && doc.getLineNumber(cmt.getTextRange().getStartOffset()) == eline + 1) {
lastComment = cmt;
eline = doc.getLineNumber(cmt.getTextRange().getEndOffset());
}
else {
break;
}
}
}
return new CommentRange(firstComment, lastComment);
}
private static boolean isLineComment(Commenter commenter, PsiComment comment, Document doc) {
final String lineCommentPrefix = commenter.getLineCommentPrefix();
if (lineCommentPrefix != null) {
return comment.getText().startsWith(lineCommentPrefix);
}
final TextRange textRange = comment.getTextRange();
return doc.getLineNumber(textRange.getStartOffset()) == doc.getLineNumber(textRange.getEndOffset());
}
protected PsiFile getFile() {
return file;
}
protected LanguageOptions getLanguageOptions() {
return langOpts;
}
protected void addAction(CommentAction action) {
actions.add(action);
}
protected PsiElement getPreviousSibling(PsiElement element) {
return element == null ? null : element.getPrevSibling();
}
protected PsiElement getNextSibling(PsiElement element) {
return element == null ? null : element.getNextSibling();
}
protected void processActions(final boolean allowReplacement) throws IncorrectOperationException {
new WriteCommandAction.Simple(file.getProject(), "Update copyright") {
@Override
protected void run() throws Throwable {
Document doc = FileDocumentManager.getInstance().getDocument(getRoot());
if (doc != null) {
PsiDocumentManager.getInstance(file.getProject()).doPostponedOperationsAndUnblockDocument(doc);
for (CommentAction action : actions) {
int start = action.getStart();
int end = action.getEnd();
switch (action.getType()) {
case CommentAction.ACTION_INSERT:
String comment = getCommentText(action.getPrefix(), action.getSuffix());
if (!comment.isEmpty()) {
doc.insertString(start, comment);
}
break;
case CommentAction.ACTION_REPLACE:
if (allowReplacement) doc.replaceString(start, end, getCommentText("", ""));
break;
case CommentAction.ACTION_DELETE:
if (allowReplacement) doc.deleteString(start, end);
break;
}
}
PsiDocumentManager.getInstance(getProject()).commitDocument(doc);
}
}
}.execute();
}
public boolean hasUpdates() {
return !actions.isEmpty();
}
private static class CommentRange {
public CommentRange(@NotNull PsiElement first, @NotNull PsiElement last) {
this.first = first;
this.last = last;
LOG.assertTrue(first.getContainingFile() == last.getContainingFile());
}
public PsiElement getFirst() {
return first;
}
public PsiElement getLast() {
return last;
}
private final PsiElement first;
private final PsiElement last;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CommentRange that = (CommentRange)o;
if (first != null ? !first.equals(that.first) : that.first != null) return false;
if (last != null ? !last.equals(that.last) : that.last != null) return false;
return true;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (last != null ? last.hashCode() : 0);
return result;
}
}
protected static class CommentAction implements Comparable<CommentAction> {
public static final int ACTION_INSERT = 1;
public static final int ACTION_REPLACE = 2;
public static final int ACTION_DELETE = 3;
public CommentAction(int pos, String prefix, String suffix) {
type = ACTION_INSERT;
start = pos;
end = pos;
this.prefix = prefix;
this.suffix = suffix;
}
public CommentAction(int type, int start, int end) {
this.type = type;
this.start = start;
this.end = end;
}
public int getType() {
return type;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
@Override
public int compareTo(@NotNull CommentAction object) {
int s = object.getStart();
int diff = s - start;
if (diff == 0) {
diff = type == ACTION_INSERT ? 1 : -1;
}
return diff;
}
private final int type;
private final int start;
private final int end;
private String prefix = null;
private String suffix = null;
}
private final PsiFile file;
private final LanguageOptions langOpts;
private final TreeSet<CommentAction> actions = new TreeSet<>();
private static final Logger logger = Logger.getInstance(UpdatePsiFileCopyright.class.getName());
}
| |
/*
* Created by JFormDesigner on Thu Aug 07 20:43:23 CEST 2014
*/
package drusy.ui.panels;
import aurelienribon.ui.css.Style;
import aurelienribon.utils.HttpUtils;
import aurelienribon.utils.Res;
import drusy.utils.Config;
import drusy.utils.Log;
import drusy.utils.Updater;
import org.json.JSONArray;
import org.json.JSONObject;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TimerTask;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
* @author Kevin Renella
*/
public class SwitchStatePanel extends JPanel {
private java.util.List<JPanel> users = new ArrayList<JPanel>();
private java.util.Timer timer;
private WifiStatePanel wifiStatePanel;
private Updater.FakeUpdater fakeUpdater = new Updater.FakeUpdater();
public SwitchStatePanel(WifiStatePanel wifiStatePanel) {
initComponents();
setVisible(false);
this.wifiStatePanel = wifiStatePanel;
Style.registerCssClasses(headerPanel, ".header");
}
public void updatePeriodically() {
long delay = 1000 * 2;
timer = new java.util.Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
update(fakeUpdater);
}
}, 1000, delay);
}
public void update(final Updater updater) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output, "Getting Switch status", false);
task.addListener(new HttpUtils.DownloadListener() {
@Override public void onComplete() {
String json = output.toString();
JSONObject obj = new JSONObject(json);
boolean success = obj.getBoolean("success");
clearUsers();
if (success == true) {
JSONArray switchStatusArray = obj.getJSONArray("result");
for (int i = 0; i < switchStatusArray.length(); ++i) {
JSONObject switchStatus = switchStatusArray.getJSONObject(i);
String status = switchStatus.getString("link");
int id = switchStatus.getInt("id");
if (status.equals("up")) {
JSONArray switchMacArray = switchStatus.getJSONArray("mac_list");
JSONObject switchMac = switchMacArray.getJSONObject(i);
String hostname = switchMac.getString("hostname");
addUsersForSwitchIdAndHostname(id, hostname);
}
}
} else {
String msg = obj.getString("msg");
Log.Debug("Freebox Switch status", msg);
}
if (updater != null) {
updater.updated();
}
}
});
task.addListener(new HttpUtils.DownloadListener() {
@Override
public void onError(IOException ex) {
Log.Debug("Freebox Switch status", ex.getMessage());
if (updater != null) {
updater.updated();
}
}
});
}
public void addUsersForSwitchIdAndHostname(int id, final String hostname) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
String statement = Config.FREEBOX_API_SWITCH_ID.replace("{id}", String.valueOf(id));
HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting Switch information", false);
task.addListener(new HttpUtils.DownloadListener() {
@Override public void onComplete() {
String json = output.toString();
JSONObject obj = new JSONObject(json);
boolean success = obj.getBoolean("success");
if (success == true) {
JSONObject result = obj.getJSONObject("result");
long txBytes = result.getLong("tx_bytes_rate");
long rxBytes = result.getLong("rx_bytes_rate");
addUser("", hostname, txBytes, rxBytes);
} else {
String msg = obj.getString("msg");
Log.Debug("Freebox Switch information", msg);
}
setVisible(true);
}
});
task.addListener(new HttpUtils.DownloadListener() {
@Override
public void onError(IOException ex) {
Log.Debug("Freebox Switch information", ex.getMessage());
}
});
}
private void addUser(String hostName, String information, long txBytes, long rxBytes) {
JPanel panel = new JPanel();
JLabel informationLabel = new JLabel();
ImageIcon imageIcon;
//======== panel1 ========
{
panel.setLayout(new BorderLayout());
panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//---- label2 ----
if (hostName.equals("smartphone")) {
imageIcon = Res.getImage("img/iphone-56.png");
} else {
imageIcon = Res.getImage("img/mac-56.png");
}
informationLabel.setIcon(imageIcon);
informationLabel.setText("<html><b>" + information + "</b><br />Download: " + txBytes / 1000.0 + " ko/s <br />Upload: " + rxBytes / 1000.0 + " ko/s</html>");
informationLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(informationLabel, BorderLayout.CENTER);
}
mainPanel.add(panel);
adaptPanelSize();
users.add(panel);
}
private void adaptPanelSize() {
setSize(getWidth(), (int) getPreferredSize().getHeight());
setLocation(getX(), wifiStatePanel.getY() + wifiStatePanel.getHeight() + Config.GAP);
validate();
repaint();
}
private void clearUsers() {
for (JPanel user : users) {
mainPanel.remove(user);
}
users.clear();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Kevin Renella
headerPanel = new JPanel();
label1 = new JLabel();
mainPanel = new JPanel();
//======== this ========
setLayout(new BorderLayout());
//======== headerPanel ========
{
headerPanel.setLayout(new BorderLayout());
//---- label1 ----
label1.setText("This panel shows you the users connected on the Switch");
label1.setHorizontalAlignment(SwingConstants.CENTER);
headerPanel.add(label1, BorderLayout.CENTER);
}
add(headerPanel, BorderLayout.NORTH);
//======== mainPanel ========
{
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
}
add(mainPanel, BorderLayout.CENTER);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Kevin Renella
private JPanel headerPanel;
private JLabel label1;
private JPanel mainPanel;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.16 at 12:56:53 PM IST
//
package org.akomantoso.schema.v3.csd12;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><type xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD12" xmlns:xsd="http://www.w3.org/2001/XMLSchema">Complex</type>
* </pre>
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><name xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD12" xmlns:xsd="http://www.w3.org/2001/XMLSchema">markeropt</name>
* </pre>
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><comment xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD12" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* the complex type markeropt defines the content model and attributes shared by all marker elements. Here the eId attribute is optional</comment>
* </pre>
*
*
* <p>Java class for markeropt complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="markeropt">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD12}coreopt"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "markeropt")
@XmlSeeAlso({
EolType.class,
Img.class,
NoteRef.class
})
public class Markeropt {
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "space", namespace = "http://www.w3.org/XML/1998/namespace")
protected String space;
@XmlAttribute(name = "eId")
protected String eId;
@XmlAttribute(name = "wId")
protected String wId;
@XmlAttribute(name = "GUID")
protected String guid;
@XmlAttribute(name = "refersTo")
protected List<String> refersTo;
@XmlAttribute(name = "class")
protected String clazz;
@XmlAttribute(name = "style")
protected String style;
@XmlAttribute(name = "title")
protected String titleAttr;
@XmlAttribute(name = "status")
protected StatusType status;
@XmlAttribute(name = "period")
@XmlSchemaType(name = "anyURI")
protected String period;
@XmlAttribute(name = "alternativeTo")
@XmlSchemaType(name = "anyURI")
protected String alternativeTo;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the space property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpace() {
return space;
}
/**
* Sets the value of the space property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpace(String value) {
this.space = value;
}
/**
* Gets the value of the eId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEId() {
return eId;
}
/**
* Sets the value of the eId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEId(String value) {
this.eId = value;
}
/**
* Gets the value of the wId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWId() {
return wId;
}
/**
* Sets the value of the wId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWId(String value) {
this.wId = value;
}
/**
* Gets the value of the guid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGUID() {
return guid;
}
/**
* Sets the value of the guid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGUID(String value) {
this.guid = value;
}
/**
* Gets the value of the refersTo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the refersTo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRefersTo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRefersTo() {
if (refersTo == null) {
refersTo = new ArrayList<String>();
}
return this.refersTo;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the titleAttr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitleAttr() {
return titleAttr;
}
/**
* Sets the value of the titleAttr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitleAttr(String value) {
this.titleAttr = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusType }
*
*/
public StatusType getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusType }
*
*/
public void setStatus(StatusType value) {
this.status = value;
}
/**
* Gets the value of the period property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPeriod() {
return period;
}
/**
* Sets the value of the period property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPeriod(String value) {
this.period = value;
}
/**
* Gets the value of the alternativeTo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlternativeTo() {
return alternativeTo;
}
/**
* Sets the value of the alternativeTo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlternativeTo(String value) {
this.alternativeTo = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| |
/* Author: Bernd Mehnert (Github username: bhmehnert)
*
* class App:
* Contains the main entry point.
*
* Description:
*
* From the MySQL-table MY_TABLE (within the database MY_DB), which by our assumption contains
* in each row a 'time frame', i.e. the table has two columns with the names T1 and T2 containing
* integers t1 < t2, we read out those frames, store them in a certain List object
* and hand this to our Scheduler class. This computes us a minimal number of workers
* 1,2,3, .... which are placed at these frames (i.e. for every primary key in MY_TABLE,
* we have a worker id (which may occur more than once)) such that for no two overlapping frames,
* we have placed the same worker there. The results, i.e. the schedule for our workers,
* are stored in RESULT_TABLE. (If MY_TABLE/ MY_DB do not exist, we will create them automatically.)
*/
package java_mysql_scheduling_demo;
import java.io.*;
import java.util.*;
import java.sql.*;
class App {
// JDBC driver name and database URL
static final String DB_URL = "jdbc:mysql://localhost:3306";
// The Database
static final String USER = "username";
static final String PASS = "password";
static final String MY_DB = "myDB"; // Will be created if it does
// not exist.
// Data concerning the table where read read out the time intervals
// in which our tasks have to be done.
static final String MY_TABLE = "myTable";
static final String PRIMARY_ID = "id";
static final String T1 = "t1";
static final String T2 = "t2";
// If in our MY_DB the table MY_TABLE does not exist,
// it will be created, where T1,T2 above are between
// TMIN and TMAX and we will create NR_ROWS many rows.
static final int TMIN = 0;
static final int TMAX = 10000;
static int NR_ROWS = 10000; // Note that this is no constant.
// If MY_TABLE exists, NR_ROWS
// will be determined and changed
// accordingly.
// Name of the table where the scheduling results will be stored.
static final String RESULT_TABLE = "resultTable";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
DatabaseMetaData metadata = null;
ResultSet result = null;
try {
// Open a connection. The JDBC driver is automatically loaded
// in our setting .
System.out.println("Connecting to MySQL-server ...");
connection = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Done.");
// Connect to the database MY_DB if it exists, otherwise create it
// beforehand.
System.out.println("Creating database "+MY_DB+
" if it does not exist and using it as default/current database ...");
statement = connection.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS "+MY_DB;
statement.executeUpdate(sql);
sql = "USE "+MY_DB;
statement.executeUpdate(sql);
System.out.println("Done.");
// If it not exists, create a table with the name MY_TABLE.
// This table will have NR_ROWS many tuples, each
// tuple consisting of a random pair of integers t1,t2 of integers
// with TMIN <= t1 < t2 <= TMAX.
metadata = connection.getMetaData();
result = metadata.getTables(MY_DB, null, MY_TABLE, null);
boolean createTable = !result.next();
if (createTable) {
System.out.print("A table with the name "+MY_TABLE+" is not present. ");
System.out.print("We will create one with "+NR_ROWS+" tuples, each tuple containing a pair t1,t_2 ");
System.out.print("of integers with "+TMIN+" <= "+"t1"+" < "+"t2"+" <= "+TMAX+", press ENTER to continue ...");
System.in.read();
System.out.println("Creating table "+MY_TABLE+" ...");
sql = "CREATE TABLE "+MY_TABLE+
"("+PRIMARY_ID+" INT NOT NULL, " +
" "+T1+" INT NOT NULL, " +
" "+T2+" INT NOT NULL, " +
" PRIMARY KEY ( "+PRIMARY_ID+" ))";
statement.executeUpdate(sql);
System.out.println("Done.");
System.out.println("Inserting the tuples ...");
Random randGenerator = new Random();
int t1 = 0;
int t2 = 0;
// Since we have lots of data to write, we create a large string
// and write the data in our table using only one statement.
// This is much faster than writing one row at a time.
sql = "INSERT INTO "+ MY_TABLE + " (" +
PRIMARY_ID+","+T1+","+T2+") VALUES";
for (int i = 0; i < NR_ROWS; i++) {
t1 = randGenerator.nextInt(TMAX-TMIN) + TMIN;
t2 = randGenerator.nextInt(TMAX-t1) + t1 + 1;
sql = sql +
"(" + Integer.toString(i) + " ," +
Integer.toString(t1) + " ," +
Integer.toString(t2) + ")";
if (i < NR_ROWS - 1) {
sql = sql + ",";
}
}
statement.executeUpdate(sql);
System.out.println("Done.");
}
else {
System.out.println("The table "+MY_TABLE+" already exists. Finding out the number of rows ... ");
// The number of rows.
sql = "SELECT COUNT(*) FROM "+MY_TABLE;
result = statement.executeQuery(sql);
if (result.next()) {
NR_ROWS = result.getInt("COUNT(*)");
System.out.println("The number is "+ Integer.toString(NR_ROWS)+".");
}
}
// Now we read the time data out of our MY_TABLE and use
// our scheduler. We compute a schedule and store it in the table
// RESULT_TABLE. Let us first count how many rows our table has:
System.out.println("Reading out the time frames t1,t2 from our table "
+ MY_TABLE +
" and prepareing the data for further computations with our scheduler ...");
// In the following list, we store what we read out.
List<TimeFrameBound> tFKS = new ArrayList<TimeFrameBound>();
// Let us read out the data.
sql = "SELECT "+PRIMARY_ID+","+T1+","+T2+" FROM "+MY_TABLE;
result = statement.executeQuery(sql);
while (result.next()){
int primary = result.getInt(PRIMARY_ID);
tFKS.add(new TimeFrameBound(primary, result.getInt(T1),1));
tFKS.add(new TimeFrameBound(primary, result.getInt(T2),-1));
}
System.out.println("Done.");
// Now we apply our own scheduler and store the results.
System.out.println("Computing a schedule ...");
Scheduler myScheduler = new Scheduler();
myScheduler.settFKS(tFKS);
int[] computation = myScheduler.computeSchedule();
System.out.println("Done.");
System.out.println("Creating table "+RESULT_TABLE+","+
" dropping the old version of it if it exists,"+
" and storing scheduling results ...");
sql = "DROP TABLE IF EXISTS "+RESULT_TABLE;
statement.executeUpdate(sql);
sql = "CREATE TABLE "+RESULT_TABLE+
"(resultId INT NOT NULL, " +
" workerId INT NOT NULL, " +
" PRIMARY KEY ( resultId ))";
statement.executeUpdate(sql);
sql = "INSERT INTO "+ RESULT_TABLE + " (" +
"resultId, workerId) VALUES";
for (int i = 0; i < NR_ROWS; i++) {
sql = sql +
"(" + Integer.toString(i) + " ," +
Integer.toString(computation[i]) + ")";
if (i < NR_ROWS - 1) {
sql = sql + ",";
}
}
statement.executeUpdate(sql);
System.out.println("Done.");
// As a final demonstration: We compute how many workers were necessary
// and for a particular time frame the worker we plan should work at
// at that frame:
System.out.print("We have tasks distributed over "+
Integer.toString(NR_ROWS)+
" time frames. Computing the number of workers we need for those ... ");
sql = "SELECT MAX(workerId) AS workerId FROM "+ RESULT_TABLE;
result = statement.executeQuery(sql);
if (result.next()) {
System.out.println("The number is "+
Integer.toString(result.getInt("workerId"))+".");
}
// End of of our demo.
}
catch(SQLException se){
// Deal with errors from the JDBC.
se.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
finally{
//close resources.
try{
if(statement != null)
connection.close();
}
catch(SQLException se){
}// do nothing
try{
if(connection != null)
connection.close();
}
catch(SQLException se){
se.printStackTrace();
} //end finally try
}
}
}
| |
/*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.doctor;
import com.facebook.buck.doctor.config.BuildLogEntry;
import com.facebook.buck.doctor.config.DoctorConfig;
import com.facebook.buck.doctor.config.SourceControlInfo;
import com.facebook.buck.doctor.config.UserLocalConfiguration;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.LogConfigPaths;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.Optionals;
import com.facebook.buck.util.RichStream;
import com.facebook.buck.util.config.Configs;
import com.facebook.buck.util.environment.BuildEnvironmentDescription;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.facebook.buck.util.versioncontrol.FullVersionControlStats;
import com.facebook.buck.util.versioncontrol.VersionControlStatsGenerator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.immutables.value.Value;
/** Base class for gathering logs and other interesting information from buck. */
public abstract class AbstractReport {
private static final Logger LOG = Logger.get(AbstractReport.class);
private final ProjectFilesystem filesystem;
private final DefectReporter defectReporter;
private final BuildEnvironmentDescription buildEnvironmentDescription;
private final VersionControlStatsGenerator versionControlStatsGenerator;
private final Console output;
private final DoctorConfig doctorConfig;
private final ExtraInfoCollector extraInfoCollector;
private final Optional<WatchmanDiagReportCollector> watchmanDiagReportCollector;
public AbstractReport(
ProjectFilesystem filesystem,
DefectReporter defectReporter,
BuildEnvironmentDescription buildEnvironmentDescription,
VersionControlStatsGenerator versionControlStatsGenerator,
Console output,
DoctorConfig doctorBuckConfig,
ExtraInfoCollector extraInfoCollector,
Optional<WatchmanDiagReportCollector> watchmanDiagReportCollector) {
this.filesystem = filesystem;
this.defectReporter = defectReporter;
this.buildEnvironmentDescription = buildEnvironmentDescription;
this.versionControlStatsGenerator = versionControlStatsGenerator;
this.output = output;
this.doctorConfig = doctorBuckConfig;
this.extraInfoCollector = extraInfoCollector;
this.watchmanDiagReportCollector = watchmanDiagReportCollector;
}
protected abstract ImmutableSet<BuildLogEntry> promptForBuildSelection();
protected Optional<SourceControlInfo> getSourceControlInfo() throws InterruptedException {
Optional<FullVersionControlStats> versionControlStatsOptional =
versionControlStatsGenerator.generateStats(VersionControlStatsGenerator.Mode.FULL);
if (!versionControlStatsOptional.isPresent()) {
return Optional.empty();
}
FullVersionControlStats versionControlStats = versionControlStatsOptional.get();
return Optional.of(
SourceControlInfo.of(
versionControlStats.getCurrentRevisionId(),
versionControlStats.getBaseBookmarks(),
Optional.of(versionControlStats.getBranchedFromMasterRevisionId()),
Optional.of(versionControlStats.getBranchedFromMasterTS()),
versionControlStats.getDiff(),
versionControlStats.getPathsChangedInWorkingDirectory()));
}
protected abstract Optional<UserReport> getUserReport();
protected abstract Optional<FileChangesIgnoredReport> getFileChangesIgnoredReport()
throws IOException, InterruptedException;
public final Optional<DefectSubmitResult> collectAndSubmitResult()
throws IOException, InterruptedException {
ImmutableSet<BuildLogEntry> selectedBuilds = promptForBuildSelection();
if (selectedBuilds.isEmpty()) {
return Optional.empty();
}
Optional<UserReport> userReport = getUserReport();
Optional<SourceControlInfo> sourceControlInfo = getSourceControlInfo();
ImmutableSet<Path> extraInfoPaths = ImmutableSet.of();
Optional<String> extraInfo = Optional.empty();
try {
Optional<ExtraInfoResult> extraInfoResultOptional = extraInfoCollector.run();
if (extraInfoResultOptional.isPresent()) {
extraInfoPaths = extraInfoResultOptional.get().getExtraFiles();
extraInfo = Optional.of(extraInfoResultOptional.get().getOutput());
}
} catch (ExtraInfoCollector.ExtraInfoExecutionException e) {
output.printErrorText(
"There was a problem gathering additional information: %s. "
+ "The results will not be attached to the report.",
e.getMessage());
}
Optional<FileChangesIgnoredReport> fileChangesIgnoredReport = getFileChangesIgnoredReport();
UserLocalConfiguration userLocalConfiguration =
UserLocalConfiguration.of(isNoBuckCheckPresent(), getLocalConfigs());
ImmutableSet<Path> includedPaths =
FluentIterable.from(selectedBuilds)
.transformAndConcat(
new Function<BuildLogEntry, Iterable<Path>>() {
@Override
public Iterable<Path> apply(BuildLogEntry input) {
ImmutableSet.Builder<Path> result = ImmutableSet.builder();
Optionals.addIfPresent(input.getRuleKeyLoggerLogFile(), result);
Optionals.addIfPresent(input.getMachineReadableLogFile(), result);
Optionals.addIfPresent(input.getRuleKeyDiagKeysFile(), result);
Optionals.addIfPresent(input.getRuleKeyDiagGraphFile(), result);
result.add(input.getRelativePath());
return result.build();
}
})
.append(extraInfoPaths)
.append(userLocalConfiguration.getLocalConfigsContents().keySet())
.append(getTracePathsOfBuilds(selectedBuilds))
.append(
fileChangesIgnoredReport
.flatMap(r -> r.getWatchmanDiagReport())
.map(ImmutableList::of)
.orElse(ImmutableList.of()))
.toSet();
DefectReport defectReport =
DefectReport.builder()
.setUserReport(userReport)
.setHighlightedBuildIds(
RichStream.from(selectedBuilds)
.map(BuildLogEntry::getBuildId)
.flatMap(Optionals::toStream)
.toOnceIterable())
.setBuildEnvironmentDescription(buildEnvironmentDescription)
.setSourceControlInfo(sourceControlInfo)
.setIncludedPaths(includedPaths)
.setExtraInfo(extraInfo)
.setFileChangesIgnoredReport(fileChangesIgnoredReport)
.setUserLocalConfiguration(userLocalConfiguration)
.build();
output.getStdOut().println("Writing report, please wait..\n");
return Optional.of(defectReporter.submitReport(defectReport));
}
@Value.Immutable
@BuckStyleImmutable
interface AbstractUserReport {
@Value.Parameter
String getUserIssueDescription();
@Value.Parameter
String getIssueCategory();
}
private ImmutableMap<Path, String> getLocalConfigs() {
Path rootPath = filesystem.getRootPath();
ImmutableSet<Path> knownUserLocalConfigs =
ImmutableSet.of(
Paths.get(Configs.DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME),
LogConfigPaths.LOCAL_PATH,
Paths.get(".watchman.local"),
Paths.get(".buckjavaargs.local"),
Paths.get(".bucklogging.local.properties"));
ImmutableMap.Builder<Path, String> localConfigs = ImmutableMap.builder();
for (Path localConfig : knownUserLocalConfigs) {
try {
localConfigs.put(
localConfig,
new String(Files.readAllBytes(rootPath.resolve(localConfig)), StandardCharsets.UTF_8));
} catch (FileNotFoundException e) {
LOG.debug("%s was not found.", localConfig);
} catch (IOException e) {
LOG.warn("Failed to read contents of %s.", rootPath.resolve(localConfig).toString());
}
}
return localConfigs.build();
}
/**
* It returns a list of trace files that corresponds to builds while respecting the maximum size
* of the final zip file.
*
* @param entries the highlighted builds
* @return a set of paths that points to the corresponding traces.
*/
private ImmutableSet<Path> getTracePathsOfBuilds(ImmutableSet<BuildLogEntry> entries) {
ImmutableSet.Builder<Path> tracePaths = new ImmutableSet.Builder<>();
long reportSizeBytes = 0;
for (BuildLogEntry entry : entries) {
reportSizeBytes += entry.getSize();
if (entry.getTraceFile().isPresent()) {
try {
Path traceFile = filesystem.getPathForRelativeExistingPath(entry.getTraceFile().get());
long traceFileSizeBytes = Files.size(traceFile);
if (doctorConfig.getReportMaxSizeBytes().isPresent()) {
if (reportSizeBytes + traceFileSizeBytes < doctorConfig.getReportMaxSizeBytes().get()) {
tracePaths.add(entry.getTraceFile().get());
reportSizeBytes += traceFileSizeBytes;
}
} else {
tracePaths.add(entry.getTraceFile().get());
reportSizeBytes += traceFileSizeBytes;
}
} catch (IOException e) {
LOG.info("Trace path %s wasn't valid, skipping it.", entry.getTraceFile().get());
}
}
}
return tracePaths.build();
}
private boolean isNoBuckCheckPresent() {
return Files.exists(filesystem.getRootPath().resolve(".nobuckcheck"));
}
@VisibleForTesting
Optional<FileChangesIgnoredReport> runWatchmanDiagReportCollector(UserInput input)
throws IOException, InterruptedException {
if (!watchmanDiagReportCollector.isPresent()
|| !input.confirm(
"Is buck not picking up changes to files? "
+ "(saying 'yes' will run extra consistency checks)")) {
return Optional.empty();
}
Optional<Path> watchmanDiagReport = Optional.empty();
try {
watchmanDiagReport = Optional.of(watchmanDiagReportCollector.get().run());
} catch (ExtraInfoCollector.ExtraInfoExecutionException e) {
output.printErrorText(
"There was a problem getting the watchman-diag report: %s. "
+ "The information will be omitted from the report.",
e);
}
return Optional.of(
FileChangesIgnoredReport.builder().setWatchmanDiagReport(watchmanDiagReport).build());
}
}
| |
/*
* 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.graph.test.operations;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.core.fs.FileInputSplit;
import org.apache.flink.core.fs.Path;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.Triplet;
import org.apache.flink.test.util.MultipleProgramsTestBase;
import org.apache.flink.types.NullValue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;
@RunWith(Parameterized.class)
public class GraphCreationWithCsvITCase extends MultipleProgramsTestBase {
public GraphCreationWithCsvITCase(TestExecutionMode mode) {
super(mode);
}
private String expectedResult;
@Test
public void testCreateWithCsvFile() throws Exception {
/*
* Test with two Csv files one with Vertex Data and one with Edges data
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
final String fileContent = "1,1\n"+
"2,2\n"+
"3,3\n";
final FileInputSplit split = createTempFile(fileContent);
final String fileContent2 = "1,2,ot\n"+
"3,2,tt\n"+
"3,1,to\n";
final FileInputSplit split2 = createTempFile(fileContent2);
Graph<Long, Long, String> graph = Graph.fromCsvReader(split.getPath().toString(), split2.getPath().toString(), env)
.types(Long.class, Long.class, String.class);
List<Triplet<Long, Long, String>> result = graph.getTriplets().collect();
expectedResult = "1,2,1,2,ot\n" +
"3,2,3,2,tt\n" +
"3,1,3,1,to\n";
compareResultAsTuples(result, expectedResult);
}
@Test
public void testCsvWithNullEdge() throws Exception {
/*
Test fromCsvReader with edge and vertex path and nullvalue for edge
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
final String vertexFileContent = "1,one\n"+
"2,two\n"+
"3,three\n";
final String edgeFileContent = "1,2\n"+
"3,2\n"+
"3,1\n";
final FileInputSplit split = createTempFile(vertexFileContent);
final FileInputSplit edgeSplit = createTempFile(edgeFileContent);
Graph<Long, String, NullValue> graph = Graph.fromCsvReader(split.getPath().toString(), edgeSplit.getPath().toString(),
env).vertexTypes(Long.class, String.class);
List<Triplet<Long, String, NullValue>> result = graph.getTriplets().collect();
expectedResult = "1,2,one,two,(null)\n"+
"3,2,three,two,(null)\n"+
"3,1,three,one,(null)\n";
compareResultAsTuples(result, expectedResult);
}
@Test
public void testCsvWithConstantValueMapper() throws Exception {
/*
*Test fromCsvReader with edge path and a mapper that assigns a Double constant as value
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
final String fileContent = "1,2,ot\n"+
"3,2,tt\n"+
"3,1,to\n";
final FileInputSplit split = createTempFile(fileContent);
Graph<Long, Double, String> graph = Graph.fromCsvReader(split.getPath().toString(),
new AssignDoubleValueMapper(), env).types(Long.class, Double.class, String.class);
List<Triplet<Long, Double, String>> result = graph.getTriplets().collect();
//graph.getTriplets().writeAsCsv(resultPath);
expectedResult = "1,2,0.1,0.1,ot\n" + "3,1,0.1,0.1,to\n" + "3,2,0.1,0.1,tt\n";
compareResultAsTuples(result, expectedResult);
}
@Test
public void testCreateWithOnlyEdgesCsvFile() throws Exception {
/*
* Test with one Csv file one with Edges data. Also tests the configuration method ignoreFistLineEdges()
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
final String fileContent2 = "header\n1,2,ot\n"+
"3,2,tt\n"+
"3,1,to\n";
final FileInputSplit split2 = createTempFile(fileContent2);
Graph<Long, NullValue, String> graph= Graph.fromCsvReader(split2.getPath().toString(), env)
.ignoreFirstLineEdges()
.ignoreCommentsVertices("hi")
.edgeTypes(Long.class, String.class);
List<Triplet<Long, NullValue, String>> result = graph.getTriplets().collect();
expectedResult = "1,2,(null),(null),ot\n" +
"3,2,(null),(null),tt\n" +
"3,1,(null),(null),to\n";
compareResultAsTuples(result, expectedResult);
}
@Test
public void testCreateCsvFileDelimiterConfiguration() throws Exception {
/*
* Test with an Edge and Vertex csv file. Tests the configuration methods FieldDelimiterEdges and
* FieldDelimiterVertices
* Also tests the configuration methods LineDelimiterEdges and LineDelimiterVertices
*/
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
final String fileContent = "header\n1;1\n"+
"2;2\n"+
"3;3\n";
final FileInputSplit split = createTempFile(fileContent);
final String fileContent2 = "header|1:2:ot|"+
"3:2:tt|"+
"3:1:to|";
final FileInputSplit split2 = createTempFile(fileContent2);
Graph<Long, Long, String> graph= Graph.fromCsvReader(split.getPath().toString(), split2.getPath().toString(), env).
ignoreFirstLineEdges().ignoreFirstLineVertices().
fieldDelimiterEdges(":").fieldDelimiterVertices(";").
lineDelimiterEdges("|").
types(Long.class, Long.class, String.class);
List<Triplet<Long, Long, String>> result = graph.getTriplets().collect();
expectedResult = "1,2,1,2,ot\n" +
"3,2,3,2,tt\n" +
"3,1,3,1,to\n";
compareResultAsTuples(result, expectedResult);
}
/*----------------------------------------------------------------------------------------------------------------*/
@SuppressWarnings("serial")
private static final class AssignDoubleValueMapper implements MapFunction<Long, Double> {
public Double map(Long value) {
return 0.1d;
}
}
private FileInputSplit createTempFile(String content) throws IOException {
File tempFile = File.createTempFile("test_contents", "tmp");
tempFile.deleteOnExit();
OutputStreamWriter wrt = new OutputStreamWriter(
new FileOutputStream(tempFile), Charset.forName("UTF-8")
);
wrt.write(content);
wrt.close();
return new FileInputSplit(0, new Path(tempFile.toURI().toString()), 0,
tempFile.length(), new String[] {"localhost"});
}
}
| |
/**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.jdbc;
import com.impossibl.postgres.api.jdbc.PGSQLOutput;
import com.impossibl.postgres.types.CompositeType;
import com.impossibl.postgres.types.CompositeType.Attribute;
import com.impossibl.postgres.utils.guava.ByteStreams;
import com.impossibl.postgres.utils.guava.CharStreams;
import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED;
import static com.impossibl.postgres.jdbc.Exceptions.NOT_SUPPORTED;
import static com.impossibl.postgres.jdbc.SQLTypeUtils.coerce;
import static com.impossibl.postgres.jdbc.SQLTypeUtils.mapSetType;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.RowId;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Collections;
public class PGSQLOutputImpl implements PGSQLOutput {
private PGConnectionImpl connection;
private CompositeType type;
private int currentAttributeIdx;
private Object[] attributeValues;
public PGSQLOutputImpl(PGConnectionImpl connection, CompositeType type) {
this.connection = connection;
this.type = type;
this.attributeValues = new Object[type.getAttributes().size()];
}
public Object[] getAttributeValues() {
return attributeValues;
}
void writeNextAttributeValue(Object val) throws SQLException {
Attribute attr = type.getAttribute(currentAttributeIdx + 1);
if (attr == null) {
throw new SQLException("invalid attribute access");
}
Class<?> targetType = mapSetType(attr.getType());
attributeValues[currentAttributeIdx++] = coerce(val, attr.getType(), targetType, Collections.<String, Class<?>>emptyMap(), connection);
}
@Override
public void writeString(String x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeBoolean(boolean x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeByte(byte x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeShort(short x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeInt(int x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeLong(long x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeFloat(float x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeDouble(double x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeBigDecimal(BigDecimal x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeBytes(byte[] x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeDate(Date x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeTime(Time x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeTimestamp(Timestamp x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeCharacterStream(Reader x) throws SQLException {
try {
writeNextAttributeValue(CharStreams.toString(x));
}
catch (IOException e) {
throw new SQLException(e);
}
}
@Override
public void writeAsciiStream(InputStream x) throws SQLException {
try {
writeNextAttributeValue(new String(ByteStreams.toByteArray(x), StandardCharsets.US_ASCII));
}
catch (IOException e) {
throw new SQLException(e);
}
}
@Override
public void writeBinaryStream(InputStream x) throws SQLException {
try {
writeNextAttributeValue(ByteStreams.toByteArray(x));
}
catch (IOException e) {
throw new SQLException(e);
}
}
@Override
public void writeArray(Array x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeURL(URL x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeObject(SQLData x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeObject(Object x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeBlob(Blob x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeClob(Clob x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeStruct(Struct x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeSQLXML(SQLXML x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeRowId(RowId x) throws SQLException {
writeNextAttributeValue(x);
}
@Override
public void writeRef(Ref x) throws SQLException {
throw NOT_IMPLEMENTED;
}
@Override
public void writeNString(String x) throws SQLException {
throw NOT_SUPPORTED;
}
@Override
public void writeNClob(NClob x) throws SQLException {
throw NOT_SUPPORTED;
}
}
| |
package edu.purdue.safewalk.Fragments;
import java.util.ArrayList;
import org.w3c.dom.Document;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import edu.purdue.safewalk.R;
import edu.purdue.safewalk.SafeWalk;
import edu.purdue.safewalk.MapItems.CustomMapFragment;
import edu.purdue.safewalk.MapItems.GMapV2Direction;
import edu.purdue.safewalk.MapItems.MapOverlayHandler;
import edu.purdue.safewalk.Widgets.TouchableWrapper;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WalkRequestFragment extends Fragment {
public static enum BubbleState {
START, END, CONFIRM;
};
public BubbleState mBubbleState = BubbleState.START;
GoogleMap mMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.map, null);
LinearLayout lin = (LinearLayout) v
.findViewById(R.id.mapPopUpLinLayout);
lin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onPopUpBubbleClick(v);
}
});
int shortAnimDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
((TouchableWrapper) v.findViewById(R.id.touchWrapper))
.setOverlayHandler(new MapOverlayHandler(getActivity(),
shortAnimDuration));
initMap();
return v;
// mOriginalContentView = super.onCreateView(inflater, parent,
// savedInstanceState);
// int shortAnimDuration = getResources().getInteger(
// android.R.integer.config_shortAnimTime);
// mTouchView = new TouchableWrapper(new
// MapOverlayHandler(getActivity(),
// shortAnimDuration));
// mTouchView.addView(mOriginalContentView);
//
// TODO: Make onPopupBubbleClick the onClick for mapPopUpLinLayout
// return mTouchView;
}
private void initMap() {
mMap = ((CustomMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
((SafeWalk) getActivity()).mMap = mMap;
if (mMap != null) {
mMap.setMyLocationEnabled(true);
UiSettings mapSettings = mMap.getUiSettings();
mapSettings.setTiltGesturesEnabled(false);
mapSettings.setRotateGesturesEnabled(false);
} else {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(
getActivity());
alertBuilder.setTitle("Error!");
alertBuilder.setMessage(this.getResources().getText(
R.string.error_no_maps));
alertBuilder.setPositiveButton("Close "
+ this.getResources().getText(R.string.app_name),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
alertBuilder.show();
}
}
/*
* Function used when a request to be picked up is map, send information to
* server
*/
public void onPopUpBubbleClick(View v) {
LatLng latlng;
if (mBubbleState == BubbleState.START) {
latlng = ((CustomMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).dropPinAtCenter(getActivity(),
"Start", BitmapDescriptorFactory.HUE_GREEN);
SharedPreferences bubbleState = getActivity().getSharedPreferences(
"bubbleState", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = bubbleState.edit();
edit.putString("start_lat", "" + latlng.latitude);
edit.putString("start_long", "" + latlng.longitude);
edit.commit();
mBubbleState = BubbleState.END;
updateBubbleText();
} else if (mBubbleState == BubbleState.END) {
latlng = ((CustomMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).dropPinAtCenter(getActivity(),
"End", BitmapDescriptorFactory.HUE_RED);
SharedPreferences bubbleState = getActivity().getSharedPreferences(
"bubbleState", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = bubbleState.edit();
edit.putString("end_lat", "" + latlng.latitude);
edit.putString("end_long", "" + latlng.longitude);
edit.commit();
LatLng start = new LatLng(Double.parseDouble(bubbleState.getString(
"start_lat", "0")), Double.parseDouble(bubbleState
.getString("start_long", "0")));
AsyncTask<LatLng, Void, ArrayList<LatLng>> directionsTask = new AsyncTask<LatLng, Void, ArrayList<LatLng>>() {
@Override
protected ArrayList<LatLng> doInBackground(LatLng... locations) {
GMapV2Direction md = new GMapV2Direction();
mMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
Document doc = md.getDocument(locations[0], locations[1],
GMapV2Direction.MODE_WALKING);
return md.getDirection(doc);
}
@Override
protected void onPostExecute(ArrayList<LatLng> directionPoint) {
PolylineOptions rectLine = new PolylineOptions().width(3)
.color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);
}
};
// TODO: Add loading bar under actionbar
directionsTask.execute(start, latlng);
mBubbleState = BubbleState.CONFIRM;
updateBubbleText();
} else if (mBubbleState == BubbleState.CONFIRM) {
// open request activity...
((SafeWalk) getActivity()).openRequestActivity();
mBubbleState = BubbleState.START;
updateBubbleText();
}
}
public void updateBubbleText() {
TextView bubble = (TextView) getView().findViewById(R.id.bubbleText);
switch (mBubbleState) {
case START:
bubble.setText("Request Pickup Location");
break;
case END:
bubble.setText("Set Dropoff Location");
break;
case CONFIRM:
bubble.setText("Confirm Route");
break;
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.verifier.event;
import com.facebook.airlift.event.client.EventField;
import com.facebook.airlift.event.client.EventType;
import com.facebook.presto.jdbc.QueryStats;
import com.facebook.presto.verifier.prestoaction.QueryActionStats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.units.Duration;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
@Immutable
@EventType("QueryInfo")
public class QueryInfo
{
private final String catalog;
private final String schema;
private final String originalQuery;
private final Map<String, String> sessionProperties;
private final String queryId;
private final List<String> setupQueryIds;
private final List<String> teardownQueryIds;
private final String checksumQueryId;
private final String query;
private final List<String> setupQueries;
private final List<String> teardownQueries;
private final String checksumQuery;
private final String jsonPlan;
private final String outputTableName;
private final Double cpuTimeSecs;
private final Double wallTimeSecs;
private final Long peakTotalMemoryBytes;
private final Long peakTaskTotalMemoryBytes;
private final String extraStats;
public QueryInfo(
String catalog,
String schema,
String originalQuery,
Map<String, String> sessionProperties,
List<String> setupQueryIds,
List<String> teardownQueryIds,
Optional<String> checksumQueryId,
Optional<String> query,
Optional<List<String>> setupQueries,
Optional<List<String>> teardownQueries,
Optional<String> checksumQuery,
Optional<String> jsonPlan,
Optional<QueryActionStats> queryActionStats,
Optional<String> outputTableName)
{
Optional<QueryStats> stats = queryActionStats.flatMap(QueryActionStats::getQueryStats);
this.catalog = requireNonNull(catalog, "catalog is null");
this.schema = requireNonNull(schema, "schema is null");
this.originalQuery = requireNonNull(originalQuery, "originalQuery is null");
this.sessionProperties = ImmutableMap.copyOf(sessionProperties);
this.queryId = stats.map(QueryStats::getQueryId).orElse(null);
this.setupQueryIds = ImmutableList.copyOf(setupQueryIds);
this.teardownQueryIds = ImmutableList.copyOf(teardownQueryIds);
this.checksumQueryId = checksumQueryId.orElse(null);
this.query = query.orElse(null);
this.setupQueries = setupQueries.orElse(null);
this.teardownQueries = teardownQueries.orElse(null);
this.checksumQuery = checksumQuery.orElse(null);
this.jsonPlan = jsonPlan.orElse(null);
this.cpuTimeSecs = stats.map(QueryStats::getCpuTimeMillis).map(QueryInfo::millisToSeconds).orElse(null);
this.wallTimeSecs = stats.map(QueryStats::getWallTimeMillis).map(QueryInfo::millisToSeconds).orElse(null);
this.peakTotalMemoryBytes = stats.map(QueryStats::getPeakTotalMemoryBytes).orElse(null);
this.peakTaskTotalMemoryBytes = stats.map(QueryStats::getPeakTaskTotalMemoryBytes).orElse(null);
this.extraStats = queryActionStats.flatMap(QueryActionStats::getExtraStats).orElse(null);
this.outputTableName = outputTableName.orElse(null);
}
private static double millisToSeconds(long millis)
{
return new Duration(millis, MILLISECONDS).getValue(SECONDS);
}
@EventField
public String getCatalog()
{
return catalog;
}
@EventField
public String getSchema()
{
return schema;
}
@EventField
public String getOriginalQuery()
{
return originalQuery;
}
@EventField
public Map<String, String> getSessionProperties()
{
return sessionProperties;
}
@EventField
public String getQueryId()
{
return queryId;
}
@EventField
public List<String> getSetupQueryIds()
{
return setupQueryIds;
}
@EventField
public List<String> getTeardownQueryIds()
{
return teardownQueryIds;
}
@EventField
public String getChecksumQueryId()
{
return checksumQueryId;
}
@EventField
public String getQuery()
{
return query;
}
@EventField
public List<String> getSetupQueries()
{
return setupQueries;
}
@EventField
public List<String> getTeardownQueries()
{
return teardownQueries;
}
@EventField
public String getChecksumQuery()
{
return checksumQuery;
}
@EventField
public String getJsonPlan()
{
return jsonPlan;
}
@EventField
public String getOutputTableName()
{
return outputTableName;
}
@EventField
public Double getCpuTimeSecs()
{
return cpuTimeSecs;
}
@EventField
public Double getWallTimeSecs()
{
return wallTimeSecs;
}
@EventField
public Long getPeakTotalMemoryBytes()
{
return peakTotalMemoryBytes;
}
@EventField
public Long getPeakTaskTotalMemoryBytes()
{
return peakTaskTotalMemoryBytes;
}
@EventField
public String getExtraStats()
{
return extraStats;
}
public static Builder builder(
String catalog,
String schema,
String originalQuery,
Map<String, String> sessionProperties)
{
return new Builder(catalog, schema, originalQuery, sessionProperties);
}
public static class Builder
{
private final String catalog;
private final String schema;
private final String originalQuery;
private final Map<String, String> sessionProperties;
private List<String> setupQueryIds = ImmutableList.of();
private List<String> teardownQueryIds = ImmutableList.of();
private Optional<String> checksumQueryId = Optional.empty();
private Optional<String> query = Optional.empty();
private Optional<List<String>> setupQueries = Optional.empty();
private Optional<List<String>> teardownQueries = Optional.empty();
private Optional<String> checksumQuery = Optional.empty();
private Optional<String> jsonPlan = Optional.empty();
private Optional<QueryActionStats> queryActionStats = Optional.empty();
private Optional<String> outputTableName = Optional.empty();
private Builder(
String catalog,
String schema,
String originalQuery,
Map<String, String> sessionProperties)
{
this.catalog = requireNonNull(catalog, "catalog is null");
this.schema = requireNonNull(schema, "schema is null");
this.originalQuery = requireNonNull(originalQuery, "originalQuery is null");
this.sessionProperties = ImmutableMap.copyOf(sessionProperties);
}
public Builder setSetupQueryIds(List<String> setupQueryIds)
{
this.setupQueryIds = ImmutableList.copyOf(setupQueryIds);
return this;
}
public Builder setTeardownQueryIds(List<String> teardownQueryIds)
{
this.teardownQueryIds = ImmutableList.copyOf(teardownQueryIds);
return this;
}
public Builder setChecksumQueryId(Optional<String> checksumQueryId)
{
this.checksumQueryId = requireNonNull(checksumQueryId, "checksumQueryId is null");
return this;
}
public Builder setQuery(Optional<String> query)
{
this.query = requireNonNull(query, "query is null");
return this;
}
public Builder setSetupQueries(Optional<List<String>> setupQueries)
{
this.setupQueries = requireNonNull(setupQueries, "setupQueries is null");
return this;
}
public Builder setTeardownQueries(Optional<List<String>> teardownQueries)
{
this.teardownQueries = requireNonNull(teardownQueries, "teardownQueries is null");
return this;
}
public Builder setChecksumQuery(Optional<String> checksumQuery)
{
this.checksumQuery = requireNonNull(checksumQuery, "checksumQuery is null");
return this;
}
public Builder setJsonPlan(String jsonPlan)
{
this.jsonPlan = Optional.of(jsonPlan);
return this;
}
public Builder setQueryActionStats(Optional<QueryActionStats> queryActionStats)
{
this.queryActionStats = requireNonNull(queryActionStats, "queryActionStats is null");
return this;
}
public Builder setOutputTableName(Optional<String> outputTableName)
{
this.outputTableName = requireNonNull(outputTableName, "outputTableName is null");
return this;
}
public QueryInfo build()
{
return new QueryInfo(
catalog,
schema,
originalQuery,
sessionProperties,
setupQueryIds,
teardownQueryIds,
checksumQueryId,
query,
setupQueries,
teardownQueries,
checksumQuery,
jsonPlan,
queryActionStats,
outputTableName);
}
}
}
| |
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.sql;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.lang.SystemUtil;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
/**
* Class used for reading table data from a database through JDBC, and map
* the data to Java classes.
*
* @see ObjectMapper
*
* @author Harald Kuhr (haraldk@iconmedialab.no)
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-sandbox/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#1 $
*
* @todo Use JDK logging instead of proprietary logging.
*
*/
public class ObjectReader {
/**
* Main method, for testing purposes only.
*/
public final static void main(String[] pArgs) throws SQLException {
/*
System.err.println("Testing only!");
// Get default connection
ObjectReader obr = new ObjectReader(DatabaseConnection.getConnection());
com.twelvemonkeys.usedcars.DBCar car = new com.twelvemonkeys.usedcars.DBCar(new Integer(1));
com.twelvemonkeys.usedcars.DBDealer dealer = new com.twelvemonkeys.usedcars.DBDealer("NO4537");
System.out.println(obr.readObject(dealer));
com.twelvemonkeys.usedcars.Dealer[] dealers = (com.twelvemonkeys.usedcars.Dealer[]) obr.readObjects(dealer);
for (int i = 0; i < dealers.length; i++) {
System.out.println(dealers[i]);
}
System.out.println("------------------------------------------------------------------------------\n"
+ "Total: " + dealers.length + " dealers in database\n");
Hashtable where = new Hashtable();
where.put("zipCode", "0655");
dealers = (com.twelvemonkeys.usedcars.Dealer[]) obr.readObjects(dealer, where);
for (int i = 0; i < dealers.length; i++) {
System.out.println(dealers[i]);
}
System.out.println("------------------------------------------------------------------------------\n"
+ "Total: " + dealers.length + " dealers matching query: "
+ where + "\n");
com.twelvemonkeys.usedcars.Car[] cars = null;
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car);
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
System.out.println("------------------------------------------------------------------------------\n"
+ "Total: " + cars.length + " cars in database\n");
where = new Hashtable();
where.put("year", new Integer(1995));
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car, where);
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
System.out.println("------------------------------------------------------------------------------\n"
+ "Total: " + cars.length + " cars matching query: "
+ where + " \n");
where = new Hashtable();
where.put("publishers", "Bilguiden");
cars = (com.twelvemonkeys.usedcars.Car[]) obr.readObjects(car, where);
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
System.out.println("------------------------------------------------------------------------------\n"
+ "Total: " + cars.length + " cars matching query: "
+ where + "\n");
System.out.println("==============================================================================\n"
+ getStats());
*/
}
protected Log mLog = null;
protected Properties mConfig = null;
/**
* The connection used for all database operations executed by this
* ObjectReader.
*/
Connection mConnection = null;
/**
* The cache for this ObjectReader.
* Probably a source for memory leaks, as it has no size limitations.
*/
private Hashtable mCache = new Hashtable();
/**
* Creates a new ObjectReader, using the given JDBC Connection. The
* Connection will be used for all database reads by this ObjectReader.
*
* @param connection A JDBC Connection
*/
public ObjectReader(Connection pConnection) {
mConnection = pConnection;
try {
mConfig = SystemUtil.loadProperties(getClass());
}
catch (FileNotFoundException fnf) {
// Just go with defaults
}
catch (IOException ioe) {
new Log(this).logError(ioe);
}
mLog = new Log(this, mConfig);
}
/**
* Gets a string containing the stats for this ObjectReader.
*
* @return A string to display the stats.
*/
public static String getStats() {
long total = sCacheHit + sCacheMiss + sCacheUn;
double hit = ((double) sCacheHit / (double) total) * 100.0;
double miss = ((double) sCacheMiss / (double) total) * 100.0;
double un = ((double) sCacheUn / (double) total) * 100.0;
// Default locale
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
return "Total: " + total + " reads. "
+ "Cache hits: " + sCacheHit + " (" + nf.format(hit) + "%), "
+ "Cache misses: " + sCacheMiss + " (" + nf.format(miss) + "%), "
+ "Unattempted: " + sCacheUn + " (" + nf.format(un) + "%) ";
}
/**
* Get an array containing Objects of type objClass, with the
* identity values for the given class set.
*/
private Object[] readIdentities(Class pObjClass, Hashtable pMapping,
Hashtable pWhere, ObjectMapper pOM)
throws SQLException {
sCacheUn++;
// Build SQL query string
if (pWhere == null)
pWhere = new Hashtable();
String[] keys = new String[pWhere.size()];
int i = 0;
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
keys[i] = (String) en.nextElement();
}
// Get SQL for reading identity column
String sql = pOM.buildIdentitySQL(keys)
+ buildWhereClause(keys, pMapping);
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
// Prepare statement and set values
PreparedStatement statement = mConnection.prepareStatement(sql);
for (int j = 0; j < keys.length; j++) {
Object key = pWhere.get(keys[j]);
if (key instanceof Integer)
statement.setInt(j + 1, ((Integer) key).intValue());
else if (key instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) key);
else
statement.setString(j + 1, key.toString());
}
// Execute query
ResultSet rs = null;
try {
rs = statement.executeQuery();
}
catch (SQLException e) {
mLog.logError(sql + " (" + pWhere + ")", e);
throw e;
}
Vector result = new Vector();
// Map query to objects
while (rs.next()) {
Object obj = null;
try {
obj = pObjClass.newInstance();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InstantiationException ie) {
ie.printStackTrace();
}
// Map it
pOM.mapColumnProperty(rs, 1,
pOM.getProperty(pOM.getPrimaryKey()), obj);
result.addElement(obj);
}
// Return array of identifiers
return result.toArray((Object[]) Array.newInstance(pObjClass,
result.size()));
}
/**
* Reads one object implementing the DatabaseReadable interface from the
* database.
*
* @param readable A DatabaseReadable object
* @return The Object read, or null in no object is found
*/
public Object readObject(DatabaseReadable pReadable) throws SQLException {
return readObject(pReadable.getId(), pReadable.getClass(),
pReadable.getMapping());
}
/**
* Reads the object with the given id from the database, using the given
* mapping.
*
* @param id An object uniquely identifying the object to read
* @param objClass The clas
* @return The Object read, or null in no object is found
*/
public Object readObject(Object pId, Class pObjClass, Hashtable pMapping)
throws SQLException {
return readObject(pId, pObjClass, pMapping, null);
}
/**
* Reads all the objects of the given type from the
* database. The object must implement the DatabaseReadable interface.
*
* @return An array of Objects, or an zero-length array if none was found
*/
public Object[] readObjects(DatabaseReadable pReadable)
throws SQLException {
return readObjects(pReadable.getClass(),
pReadable.getMapping(), null);
}
/**
* Sets the property value to an object using reflection
*
* @param obj The object to get a property from
* @param property The name of the property
* @param value The property value
*
*/
private void setPropertyValue(Object pObj, String pProperty,
Object pValue) {
Method m = null;
Class[] cl = {pValue.getClass()};
try {
//Util.setPropertyValue(pObj, pProperty, pValue);
// Find method
m = pObj.getClass().
getMethod("set" + StringUtil.capitalize(pProperty), cl);
// Invoke it
Object[] args = {pValue};
m.invoke(pObj, args);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
}
/**
* Gets the property value from an object using reflection
*
* @param obj The object to get a property from
* @param property The name of the property
*
* @return The property value as an Object
*/
private Object getPropertyValue(Object pObj, String pProperty) {
Method m = null;
Class[] cl = new Class[0];
try {
//return Util.getPropertyValue(pObj, pProperty);
// Find method
m = pObj.getClass().
getMethod("get" + StringUtil.capitalize(pProperty),
new Class[0]);
// Invoke it
Object result = m.invoke(pObj, new Object[0]);
return result;
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
return null;
}
/**
* Reads and sets the child properties of the given parent object.
*
* @param parent The object to set the child obects to.
* @param om The ObjectMapper of the parent object.
*/
private void setChildObjects(Object pParent, ObjectMapper pOM)
throws SQLException {
if (pOM == null) {
throw new NullPointerException("ObjectMapper in readChildObjects "
+ "cannot be null!!");
}
for (Enumeration keys = pOM.mMapTypes.keys(); keys.hasMoreElements();) {
String property = (String) keys.nextElement();
String mapType = (String) pOM.mMapTypes.get(property);
if (property.length() <= 0 || mapType == null) {
continue;
}
// Get the id of the parent
Object id = getPropertyValue(pParent,
pOM.getProperty(pOM.getPrimaryKey()));
if (mapType.equals(ObjectMapper.OBJECTMAP)) {
// OBJECT Mapping
// Get the class for this property
Class objectClass = (Class) pOM.mClasses.get(property);
DatabaseReadable dbr = null;
try {
dbr = (DatabaseReadable) objectClass.newInstance();
}
catch (Exception e) {
mLog.logError(e);
}
/*
Properties mapping = readMapping(objectClass);
*/
// Get property mapping for child object
if (pOM.mJoins.containsKey(property))
// mapping.setProperty(".join", (String) pOM.joins.get(property));
dbr.getMapping().put(".join", pOM.mJoins.get(property));
// Find id and put in where hash
Hashtable where = new Hashtable();
// String foreignKey = mapping.getProperty(".foreignKey");
String foreignKey = (String)
dbr.getMapping().get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
Object[] child = readObjects(dbr, where);
// Object[] child = readObjects(objectClass, mapping, where);
if (child.length < 1)
throw new SQLException("No child object with foreign key "
+ foreignKey + "=" + id);
else if (child.length != 1)
throw new SQLException("More than one object with foreign "
+ "key " + foreignKey + "=" + id);
// Set child object to the parent
setPropertyValue(pParent, property, child[0]);
}
else if (mapType.equals(ObjectMapper.COLLECTIONMAP)) {
// COLLECTION Mapping
// Get property mapping for child object
Hashtable mapping = pOM.getPropertyMapping(property);
// Find id and put in where hash
Hashtable where = new Hashtable();
String foreignKey = (String) mapping.get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
DBObject dbr = new DBObject();
dbr.mapping = mapping; // ugh...
// Read the objects
Object[] objs = readObjects(dbr, where);
// Put the objects in a hash
Hashtable children = new Hashtable();
for (int i = 0; i < objs.length; i++) {
children.put(((DBObject) objs[i]).getId(),
((DBObject) objs[i]).getObject());
}
// Set child properties to parent object
setPropertyValue(pParent, property, children);
}
}
}
/**
* Reads all objects from the database, using the given mapping.
*
* @param objClass The class of the objects to read
* @param mapping The hashtable containing the object mapping
*
* @return An array of Objects, or an zero-length array if none was found
*/
public Object[] readObjects(Class pObjClass, Hashtable pMapping)
throws SQLException {
return readObjects(pObjClass, pMapping, null);
}
/**
* Builds extra SQL WHERE clause
*
* @param keys An array of ID names
* @param mapping The hashtable containing the object mapping
*
* @return A string containing valid SQL
*/
private String buildWhereClause(String[] pKeys, Hashtable pMapping) {
StringBuilder sqlBuf = new StringBuilder();
for (int i = 0; i < pKeys.length; i++) {
String column = (String) pMapping.get(pKeys[i]);
sqlBuf.append(" AND ");
sqlBuf.append(column);
sqlBuf.append(" = ?");
}
return sqlBuf.toString();
}
private String buildIdInClause(Object[] pIds, Hashtable pMapping) {
StringBuilder sqlBuf = new StringBuilder();
if (pIds != null && pIds.length > 0) {
sqlBuf.append(" AND ");
sqlBuf.append(pMapping.get(".primaryKey"));
sqlBuf.append(" IN (");
for (int i = 0; i < pIds.length; i++) {
sqlBuf.append(pIds[i]); // SETTE INN '?' ???
sqlBuf.append(", ");
}
sqlBuf.append(")");
}
return sqlBuf.toString();
}
/**
* Reads all objects from the database, using the given mapping.
*
* @param readable A DatabaseReadable object
* @param mapping The hashtable containing the object mapping
*
* @return An array of Objects, or an zero-length array if none was found
*/
public Object[] readObjects(DatabaseReadable pReadable, Hashtable pWhere)
throws SQLException {
return readObjects(pReadable.getClass(),
pReadable.getMapping(), pWhere);
}
/**
* Reads the object with the given id from the database, using the given
* mapping.
* This is the most general form of readObject().
*
* @param id An object uniquely identifying the object to read
* @param objClass The class of the object to read
* @param mapping The hashtable containing the object mapping
* @param where An hashtable containing extra criteria for the read
*
* @return An array of Objects, or an zero-length array if none was found
*/
public Object readObject(Object pId, Class pObjClass,
Hashtable pMapping, Hashtable pWhere)
throws SQLException {
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
return readObject0(pId, pObjClass, om, pWhere);
}
public Object readObjects(Object[] pIds, Class pObjClass,
Hashtable pMapping, Hashtable pWhere)
throws SQLException {
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
return readObjects0(pIds, pObjClass, om, pWhere);
}
/**
* Reads all objects from the database, using the given mapping.
* This is the most general form of readObjects().
*
* @param objClass The class of the objects to read
* @param mapping The hashtable containing the object mapping
* @param where An hashtable containing extra criteria for the read
*
* @return An array of Objects, or an zero-length array if none was found
*/
public Object[] readObjects(Class pObjClass, Hashtable pMapping,
Hashtable pWhere) throws SQLException {
return readObjects0(pObjClass, pMapping, pWhere);
}
// readObjects implementation
private Object[] readObjects0(Class pObjClass, Hashtable pMapping,
Hashtable pWhere) throws SQLException {
ObjectMapper om = new ObjectMapper(pObjClass, pMapping);
Object[] ids = readIdentities(pObjClass, pMapping, pWhere, om);
Object[] result = readObjects0(ids, pObjClass, om, pWhere);
return result;
}
private Object[] readObjects0(Object[] pIds, Class pObjClass,
ObjectMapper pOM, Hashtable pWhere)
throws SQLException {
Object[] result = new Object[pIds.length];
// Read each object from ID
for (int i = 0; i < pIds.length; i++) {
// TODO: For better cahce efficiency/performance:
// - Read as many objects from cache as possible
// - Read all others in ONE query, and add to cache
/*
sCacheUn++;
// Build SQL query string
if (pWhere == null)
pWhere = new Hashtable();
String[] keys = new String[pWhere.size()];
int i = 0;
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
keys[i] = (String) en.nextElement();
}
// Get SQL for reading identity column
String sql = pOM.buildSelectClause() + pOM.buildFromClause() +
+ buildWhereClause(keys, pMapping) + buildIdInClause(pIds, pMapping);
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
PreparedStatement statement = null;
// Execute query, and map columns/properties
try {
statement = mConnection.prepareStatement(sql);
// Set keys
for (int j = 0; j < keys.length; j++) {
Object value = pWhere.get(keys[j]);
if (value instanceof Integer)
statement.setInt(j + 1, ((Integer) value).intValue());
else if (value instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) value);
else
statement.setString(j + 1, value.toString());
}
// Set ids
for (int j = 0; j < pIds.length; j++) {
Object id = pIds[i];
if (id instanceof Integer)
statement.setInt(j + 1, ((Integer) id).intValue());
else if (id instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) id);
else
statement.setString(j + 1, id.toString());
}
ResultSet rs = statement.executeQuery();
Object[] result = pOM.mapObjects(rs);
// Set child objects and return
for (int i = 0; i < result.length; i++) {
// FOR THIS TO REALLY GET EFFECTIVE, WE NEED TO SET ALL
// CHILDREN IN ONE GO!
setChildObjects(result[i], pOM);
mContent.put(pOM.getPrimaryKey() + "=" + pId, result[0]);
}
// Return result
return result[0];
}
*/
Object id = getPropertyValue(result[i],
pOM.getProperty(pOM.getPrimaryKey()));
result[i] = readObject0(id, pObjClass, pOM, null);
}
return result;
}
// readObject implementation, used for ALL database reads
static long sCacheHit;
static long sCacheMiss;
static long sCacheUn;
private Object readObject0(Object pId, Class pObjClass, ObjectMapper pOM,
Hashtable pWhere) throws SQLException {
if (pId == null && pWhere == null)
throw new IllegalArgumentException("Either id or where argument"
+ "must be non-null!");
// First check if object exists in cache
if (pId != null) {
Object o = mCache.get(pOM.getPrimaryKey() + "=" + pId);
if (o != null) {
sCacheHit++;
return o;
}
sCacheMiss++;
}
else {
sCacheUn++;
}
// Create where hash
if (pWhere == null)
pWhere = new Hashtable();
// Make sure the ID is in the where hash
if (pId != null)
pWhere.put(pOM.getProperty(pOM.getPrimaryKey()), pId);
String[] keys = new String[pWhere.size()];
Enumeration en = pWhere.keys();
for (int i = 0; en.hasMoreElements(); i++) {
keys[i] = (String) en.nextElement();
}
// Get SQL query string
String sql = pOM.buildSQL() + buildWhereClause(keys, pOM.mPropertiesMap);
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
PreparedStatement statement = null;
// Execute query, and map columns/properties
try {
statement = mConnection.prepareStatement(sql);
for (int j = 0; j < keys.length; j++) {
Object value = pWhere.get(keys[j]);
if (value instanceof Integer)
statement.setInt(j + 1, ((Integer) value).intValue());
else if (value instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) value);
else
statement.setString(j + 1, value.toString());
}
ResultSet rs = statement.executeQuery();
Object[] result = pOM.mapObjects(rs);
// Set child objects and return
if (result.length == 1) {
setChildObjects(result[0], pOM);
mCache.put(pOM.getPrimaryKey() + "=" + pId, result[0]);
// Return result
return result[0];
}
// More than 1 is an error...
else if (result.length > 1) {
throw new SQLException("More than one object with primary key "
+ pOM.getPrimaryKey() + "="
+ pWhere.get(pOM.getProperty(pOM.getPrimaryKey())) + "!");
}
}
catch (SQLException e) {
mLog.logError(sql + " (" + pWhere + ")", e);
throw e;
}
finally {
try {
statement.close();
}
catch (SQLException e) {
mLog.logError(e);
}
}
return null;
}
/**
* Utility method for reading a property mapping from a properties-file
*
*/
public static Properties loadMapping(Class pClass) {
try {
return SystemUtil.loadProperties(pClass);
}
catch (FileNotFoundException fnf) {
// System.err... err...
System.err.println("ERROR: " + fnf.getMessage());
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return new Properties();
}
/**
* @deprecated Use loadMapping(Class) instead
* @see #loadMapping(Class)
*/
public static Properties readMapping(Class pClass) {
return loadMapping(pClass);
}
}
/**
* Utility class
*/
class DBObject implements DatabaseReadable {
Object id;
Object o;
static Hashtable mapping; // WHOA, STATIC!?!?
public DBObject() {
}
public void setId(Object id) {
this.id = id;
}
public Object getId() {
return id;
}
public void setObject(Object o) {
this.o = o;
}
public Object getObject() {
return o;
}
public Hashtable getMapping() {
return mapping;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.scalar;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.function.Description;
import com.facebook.presto.spi.function.LiteralParameters;
import com.facebook.presto.spi.function.OperatorType;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.ScalarOperator;
import com.facebook.presto.spi.function.SqlNullable;
import com.facebook.presto.spi.function.SqlType;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.type.CodePointsType;
import com.facebook.presto.type.Constraint;
import com.facebook.presto.type.LiteralParameter;
import com.google.common.primitives.Ints;
import io.airlift.slice.InvalidCodePointException;
import io.airlift.slice.InvalidUtf8Exception;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceUtf8;
import io.airlift.slice.Slices;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Map;
import java.util.OptionalInt;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static com.facebook.presto.spi.type.Chars.padSpaces;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.util.Failures.checkCondition;
import static io.airlift.slice.SliceUtf8.countCodePoints;
import static io.airlift.slice.SliceUtf8.getCodePointAt;
import static io.airlift.slice.SliceUtf8.lengthOfCodePoint;
import static io.airlift.slice.SliceUtf8.lengthOfCodePointSafe;
import static io.airlift.slice.SliceUtf8.offsetOfCodePoint;
import static io.airlift.slice.SliceUtf8.toLowerCase;
import static io.airlift.slice.SliceUtf8.toUpperCase;
import static io.airlift.slice.SliceUtf8.tryGetCodePointAt;
import static io.airlift.slice.Slices.utf8Slice;
import static java.lang.Character.MAX_CODE_POINT;
import static java.lang.Character.SURROGATE;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;
/**
* Current implementation is based on code points from Unicode and does ignore grapheme cluster boundaries.
* Therefore only some methods work correctly with grapheme cluster boundaries.
*/
public final class StringFunctions
{
private StringFunctions() {}
@Description("convert Unicode code point to a string")
@ScalarFunction
@SqlType("varchar(1)")
public static Slice chr(@SqlType(StandardTypes.BIGINT) long codepoint)
{
try {
return SliceUtf8.codePointToUtf8(Ints.saturatedCast(codepoint));
}
catch (InvalidCodePointException e) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Not a valid Unicode code point: " + codepoint, e);
}
}
@Description("count of code points of the given string")
@ScalarFunction
@LiteralParameters("x")
@SqlType(StandardTypes.BIGINT)
public static long length(@SqlType("varchar(x)") Slice slice)
{
return countCodePoints(slice);
}
@Description("greedily removes occurrences of a pattern in a string")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("varchar(x)")
public static Slice replace(@SqlType("varchar(x)") Slice str, @SqlType("varchar(y)") Slice search)
{
return replace(str, search, Slices.EMPTY_SLICE);
}
@Description("greedily replaces occurrences of a pattern with a string")
@ScalarFunction
@LiteralParameters({"x", "y", "z", "u"})
@Constraint(variable = "u", expression = "min(2147483647, x + z * (x + 1))")
@SqlType("varchar(u)")
public static Slice replace(@SqlType("varchar(x)") Slice str, @SqlType("varchar(y)") Slice search, @SqlType("varchar(z)") Slice replace)
{
// Empty search?
if (search.length() == 0) {
// With empty `search` we insert `replace` in front of every character and and the end
Slice buffer = Slices.allocate((countCodePoints(str) + 1) * replace.length() + str.length());
// Always start with replace
buffer.setBytes(0, replace);
int indexBuffer = replace.length();
// After every code point insert `replace`
int index = 0;
while (index < str.length()) {
int codePointLength = lengthOfCodePointSafe(str, index);
// Append current code point
buffer.setBytes(indexBuffer, str, index, codePointLength);
indexBuffer += codePointLength;
// Append `replace`
buffer.setBytes(indexBuffer, replace);
indexBuffer += replace.length();
// Advance pointer to current code point
index += codePointLength;
}
return buffer;
}
// Allocate a reasonable buffer
Slice buffer = Slices.allocate(str.length());
int index = 0;
int indexBuffer = 0;
while (index < str.length()) {
int matchIndex = str.indexOf(search, index);
// Found a match?
if (matchIndex < 0) {
// No match found so copy the rest of string
int bytesToCopy = str.length() - index;
buffer = Slices.ensureSize(buffer, indexBuffer + bytesToCopy);
buffer.setBytes(indexBuffer, str, index, bytesToCopy);
indexBuffer += bytesToCopy;
break;
}
int bytesToCopy = matchIndex - index;
buffer = Slices.ensureSize(buffer, indexBuffer + bytesToCopy + replace.length());
// Non empty match?
if (bytesToCopy > 0) {
buffer.setBytes(indexBuffer, str, index, bytesToCopy);
indexBuffer += bytesToCopy;
}
// Non empty replace?
if (replace.length() > 0) {
buffer.setBytes(indexBuffer, replace);
indexBuffer += replace.length();
}
// Continue searching after match
index = matchIndex + search.length();
}
return buffer.slice(0, indexBuffer);
}
@Description("reverse all code points in a given string")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice reverse(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.reverse(slice);
}
@Description("returns index of first occurrence of a substring (or 0 if not found)")
@ScalarFunction("strpos")
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.BIGINT)
public static long stringPosition(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice substring)
{
if (substring.length() == 0) {
return 1;
}
int index = string.indexOf(substring);
if (index < 0) {
return 0;
}
return countCodePoints(string, 0, index) + 1;
}
@Description("suffix starting at given index")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice substr(@SqlType("varchar(x)") Slice utf8, @SqlType(StandardTypes.BIGINT) long start)
{
if ((start == 0) || utf8.length() == 0) {
return Slices.EMPTY_SLICE;
}
int startCodePoint = Ints.saturatedCast(start);
if (startCodePoint > 0) {
int indexStart = offsetOfCodePoint(utf8, startCodePoint - 1);
if (indexStart < 0) {
// before beginning of string
return Slices.EMPTY_SLICE;
}
int indexEnd = utf8.length();
return utf8.slice(indexStart, indexEnd - indexStart);
}
// negative start is relative to end of string
int codePoints = countCodePoints(utf8);
startCodePoint += codePoints;
// before beginning of string
if (startCodePoint < 0) {
return Slices.EMPTY_SLICE;
}
int indexStart = offsetOfCodePoint(utf8, startCodePoint);
int indexEnd = utf8.length();
return utf8.slice(indexStart, indexEnd - indexStart);
}
@Description("substring of given length starting at an index")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice substr(@SqlType("varchar(x)") Slice utf8, @SqlType(StandardTypes.BIGINT) long start, @SqlType(StandardTypes.BIGINT) long length)
{
if (start == 0 || (length <= 0) || (utf8.length() == 0)) {
return Slices.EMPTY_SLICE;
}
int startCodePoint = Ints.saturatedCast(start);
int lengthCodePoints = Ints.saturatedCast(length);
if (startCodePoint > 0) {
int indexStart = offsetOfCodePoint(utf8, startCodePoint - 1);
if (indexStart < 0) {
// before beginning of string
return Slices.EMPTY_SLICE;
}
int indexEnd = offsetOfCodePoint(utf8, indexStart, lengthCodePoints);
if (indexEnd < 0) {
// after end of string
indexEnd = utf8.length();
}
return utf8.slice(indexStart, indexEnd - indexStart);
}
// negative start is relative to end of string
int codePoints = countCodePoints(utf8);
startCodePoint += codePoints;
// before beginning of string
if (startCodePoint < 0) {
return Slices.EMPTY_SLICE;
}
int indexStart = offsetOfCodePoint(utf8, startCodePoint);
int indexEnd;
if (startCodePoint + lengthCodePoints < codePoints) {
indexEnd = offsetOfCodePoint(utf8, indexStart, lengthCodePoints);
}
else {
indexEnd = utf8.length();
}
return utf8.slice(indexStart, indexEnd - indexStart);
}
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("array(varchar(x))")
public static Block split(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice delimiter)
{
return split(string, delimiter, string.length() + 1);
}
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("array(varchar(x))")
public static Block split(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice delimiter, @SqlType(StandardTypes.BIGINT) long limit)
{
checkCondition(limit > 0, INVALID_FUNCTION_ARGUMENT, "Limit must be positive");
checkCondition(limit <= Integer.MAX_VALUE, INVALID_FUNCTION_ARGUMENT, "Limit is too large");
checkCondition(delimiter.length() > 0, INVALID_FUNCTION_ARGUMENT, "The delimiter may not be the empty string");
BlockBuilder parts = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1, string.length());
// If limit is one, the last and only element is the complete string
if (limit == 1) {
VARCHAR.writeSlice(parts, string);
return parts.build();
}
int index = 0;
while (index < string.length()) {
int splitIndex = string.indexOf(delimiter, index);
// Found split?
if (splitIndex < 0) {
break;
}
// Add the part from current index to found split
VARCHAR.writeSlice(parts, string, index, splitIndex - index);
// Continue searching after delimiter
index = splitIndex + delimiter.length();
// Reached limit-1 parts so we can stop
if (parts.getPositionCount() == limit - 1) {
break;
}
}
// Rest of string
VARCHAR.writeSlice(parts, string, index, string.length() - index);
return parts.build();
}
@SqlNullable
@Description("splits a string by a delimiter and returns the specified field (counting from one)")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("varchar(x)")
public static Slice splitPart(@SqlType("varchar(x)") Slice string, @SqlType("varchar(y)") Slice delimiter, @SqlType(StandardTypes.BIGINT) long index)
{
checkCondition(index > 0, INVALID_FUNCTION_ARGUMENT, "Index must be greater than zero");
// Empty delimiter? Then every character will be a split
if (delimiter.length() == 0) {
int startCodePoint = toIntExact(index);
int indexStart = offsetOfCodePoint(string, startCodePoint - 1);
if (indexStart < 0) {
// index too big
return null;
}
int length = lengthOfCodePoint(string, indexStart);
if (indexStart + length > string.length()) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid UTF-8 encoding");
}
return string.slice(indexStart, length);
}
int matchCount = 0;
int previousIndex = 0;
while (previousIndex < string.length()) {
int matchIndex = string.indexOf(delimiter, previousIndex);
// No match
if (matchIndex < 0) {
break;
}
// Reached the requested part?
if (++matchCount == index) {
return string.slice(previousIndex, matchIndex - previousIndex);
}
// Continue searching after the delimiter
previousIndex = matchIndex + delimiter.length();
}
if (matchCount == index - 1) {
// returns last section of the split
return string.slice(previousIndex, string.length() - previousIndex);
}
// index is too big, null is returned
return null;
}
@Description("creates a map using entryDelimiter and keyValueDelimiter")
@ScalarFunction
@SqlType("map<varchar,varchar>")
public static Block splitToMap(@SqlType(StandardTypes.VARCHAR) Slice string, @SqlType(StandardTypes.VARCHAR) Slice entryDelimiter, @SqlType(StandardTypes.VARCHAR) Slice keyValueDelimiter)
{
checkCondition(entryDelimiter.length() > 0, INVALID_FUNCTION_ARGUMENT, "entryDelimiter is empty");
checkCondition(keyValueDelimiter.length() > 0, INVALID_FUNCTION_ARGUMENT, "keyValueDelimiter is empty");
checkCondition(!entryDelimiter.equals(keyValueDelimiter), INVALID_FUNCTION_ARGUMENT, "entryDelimiter and keyValueDelimiter must not be the same");
Map<Slice, Slice> map = new HashMap<>();
int entryStart = 0;
while (entryStart < string.length()) {
// Extract key-value pair based on current index
// then add the pair if it can be split by keyValueDelimiter
Slice keyValuePair;
int entryEnd = string.indexOf(entryDelimiter, entryStart);
if (entryEnd >= 0) {
keyValuePair = string.slice(entryStart, entryEnd - entryStart);
}
else {
// The rest of the string is the last possible pair.
keyValuePair = string.slice(entryStart, string.length() - entryStart);
}
int keyEnd = keyValuePair.indexOf(keyValueDelimiter);
if (keyEnd >= 0) {
int valueStart = keyEnd + keyValueDelimiter.length();
Slice key = keyValuePair.slice(0, keyEnd);
Slice value = keyValuePair.slice(valueStart, keyValuePair.length() - valueStart);
if (value.indexOf(keyValueDelimiter) >= 0) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Key-value delimiter must appear exactly once in each entry. Bad input: '" + keyValuePair.toStringUtf8() + "'");
}
if (map.containsKey(key)) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Duplicate keys (%s) are not allowed", key.toStringUtf8()));
}
map.put(key, value);
}
else {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Key-value delimiter must appear exactly once in each entry. Bad input: '" + keyValuePair.toStringUtf8() + "'");
}
if (entryEnd < 0) {
// No more pairs to add
break;
}
// Next possible pair is placed next to the current entryDelimiter
entryStart = entryEnd + entryDelimiter.length();
}
BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), map.size());
for (Map.Entry<Slice, Slice> entry : map.entrySet()) {
VARCHAR.writeSlice(builder, entry.getKey());
VARCHAR.writeSlice(builder, entry.getValue());
}
return builder.build();
}
@Description("removes whitespace from the beginning of a string")
@ScalarFunction("ltrim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice leftTrim(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.leftTrim(slice);
}
@Description("removes whitespace from the end of a string")
@ScalarFunction("rtrim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice rightTrim(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.rightTrim(slice);
}
@Description("removes whitespace from the beginning and end of a string")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice trim(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.trim(slice);
}
@Description("remove the longest string containing only given characters from the beginning of a string")
@ScalarFunction("ltrim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice leftTrim(@SqlType("varchar(x)") Slice slice, @SqlType(CodePointsType.NAME) int[] codePointsToTrim)
{
return SliceUtf8.leftTrim(slice, codePointsToTrim);
}
@Description("remove the longest string containing only given characters from the end of a string")
@ScalarFunction("rtrim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice rightTrim(@SqlType("varchar(x)") Slice slice, @SqlType(CodePointsType.NAME) int[] codePointsToTrim)
{
return SliceUtf8.rightTrim(slice, codePointsToTrim);
}
@Description("remove the longest string containing only given characters from the beginning and end of a string")
@ScalarFunction("trim")
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice trim(@SqlType("varchar(x)") Slice slice, @SqlType(CodePointsType.NAME) int[] codePointsToTrim)
{
return SliceUtf8.trim(slice, codePointsToTrim);
}
@ScalarOperator(OperatorType.CAST)
@LiteralParameters("x")
@SqlType(CodePointsType.NAME)
public static int[] castVarcharToCodePoints(@SqlType("varchar(x)") Slice slice)
{
return castToCodePoints(slice);
}
@ScalarOperator(OperatorType.CAST)
@SqlType(CodePointsType.NAME)
@LiteralParameters("x")
public static int[] castCharToCodePoints(@LiteralParameter("x") Long charLength, @SqlType("char(x)") Slice slice)
{
return castToCodePoints(padSpaces(slice, charLength.intValue()));
}
private static int[] castToCodePoints(Slice slice)
{
int[] codePoints = new int[safeCountCodePoints(slice)];
int position = 0;
for (int index = 0; index < codePoints.length; index++) {
codePoints[index] = getCodePointAt(slice, position);
position += lengthOfCodePoint(slice, position);
}
return codePoints;
}
private static int safeCountCodePoints(Slice slice)
{
int codePoints = 0;
for (int position = 0; position < slice.length(); ) {
int codePoint = tryGetCodePointAt(slice, position);
if (codePoint < 0) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid UTF-8 encoding in characters: " + slice.toStringUtf8());
}
position += lengthOfCodePoint(codePoint);
codePoints++;
}
return codePoints;
}
@Description("converts the string to lower case")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice lower(@SqlType("varchar(x)") Slice slice)
{
return toLowerCase(slice);
}
@Description("converts the string to upper case")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice upper(@SqlType("varchar(x)") Slice slice)
{
return toUpperCase(slice);
}
private static Slice pad(Slice text, long targetLength, Slice padString, int paddingOffset)
{
checkCondition(
0 <= targetLength && targetLength <= Integer.MAX_VALUE,
INVALID_FUNCTION_ARGUMENT,
"Target length must be in the range [0.." + Integer.MAX_VALUE + "]"
);
checkCondition(padString.length() > 0, INVALID_FUNCTION_ARGUMENT, "Padding string must not be empty");
int textLength = countCodePoints(text);
int resultLength = (int) targetLength;
// if our target length is the same as our string then return our string
if (textLength == resultLength) {
return text;
}
// if our string is bigger than requested then truncate
if (textLength > resultLength) {
return SliceUtf8.substring(text, 0, resultLength);
}
// number of bytes in each code point
int padStringLength = countCodePoints(padString);
int[] padStringCounts = new int[padStringLength];
for (int i = 0; i < padStringLength; ++i) {
padStringCounts[i] = lengthOfCodePointSafe(padString, offsetOfCodePoint(padString, i));
}
// preallocate the result
int bufferSize = text.length();
for (int i = 0; i < resultLength - textLength; ++i) {
bufferSize += padStringCounts[i % padStringLength];
}
Slice buffer = Slices.allocate(bufferSize);
// fill in the existing string
int countBytes = bufferSize - text.length();
int startPointOfExistingText = (paddingOffset + countBytes) % bufferSize;
buffer.setBytes(startPointOfExistingText, text);
// assign the pad string while there's enough space for it
int byteIndex = paddingOffset;
for (int i = 0; i < countBytes / padString.length(); ++i) {
buffer.setBytes(byteIndex, padString);
byteIndex += padString.length();
}
// handle the tail: at most we assign padStringLength - 1 code points
buffer.setBytes(byteIndex, padString.getBytes(0, paddingOffset + countBytes - byteIndex));
return buffer;
}
@Description("pads a string on the left")
@ScalarFunction("lpad")
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.VARCHAR)
public static Slice leftPad(@SqlType("varchar(x)") Slice text, @SqlType(StandardTypes.BIGINT) long targetLength, @SqlType("varchar(y)") Slice padString)
{
return pad(text, targetLength, padString, 0);
}
@Description("pads a string on the right")
@ScalarFunction("rpad")
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.VARCHAR)
public static Slice rightPad(@SqlType("varchar(x)") Slice text, @SqlType(StandardTypes.BIGINT) long targetLength, @SqlType("varchar(y)") Slice padString)
{
return pad(text, targetLength, padString, text.length());
}
@Description("computes Levenshtein distance between two strings")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.BIGINT)
public static long levenshteinDistance(@SqlType("varchar(x)") Slice left, @SqlType("varchar(y)") Slice right)
{
int[] leftCodePoints = castToCodePoints(left);
int[] rightCodePoints = castToCodePoints(right);
if (leftCodePoints.length < rightCodePoints.length) {
int[] tempCodePoints = leftCodePoints;
leftCodePoints = rightCodePoints;
rightCodePoints = tempCodePoints;
}
if (rightCodePoints.length == 0) {
return leftCodePoints.length;
}
int[] distances = new int[rightCodePoints.length];
for (int i = 0; i < rightCodePoints.length; i++) {
distances[i] = i + 1;
}
for (int i = 0; i < leftCodePoints.length; i++) {
int leftUpDistance = distances[0];
if (leftCodePoints[i] == rightCodePoints[0]) {
distances[0] = i;
}
else {
distances[0] = Math.min(i, distances[0]) + 1;
}
for (int j = 1; j < rightCodePoints.length; j++) {
int leftUpDistanceNext = distances[j];
if (leftCodePoints[i] == rightCodePoints[j]) {
distances[j] = leftUpDistance;
}
else {
distances[j] = Math.min(distances[j - 1], Math.min(leftUpDistance, distances[j])) + 1;
}
leftUpDistance = leftUpDistanceNext;
}
}
return distances[rightCodePoints.length - 1];
}
@Description("transforms the string to normalized form")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType(StandardTypes.VARCHAR)
public static Slice normalize(@SqlType("varchar(x)") Slice slice, @SqlType("varchar(y)") Slice form)
{
Normalizer.Form targetForm;
try {
targetForm = Normalizer.Form.valueOf(form.toStringUtf8());
}
catch (IllegalArgumentException e) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Normalization form must be one of [NFD, NFC, NFKD, NFKC]");
}
return utf8Slice(Normalizer.normalize(slice.toStringUtf8(), targetForm));
}
@Description("decodes the UTF-8 encoded string")
@ScalarFunction
@SqlType(StandardTypes.VARCHAR)
public static Slice fromUtf8(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
return SliceUtf8.fixInvalidUtf8(slice);
}
@Description("decodes the UTF-8 encoded string")
@ScalarFunction
@LiteralParameters("x")
@SqlType(StandardTypes.VARCHAR)
public static Slice fromUtf8(@SqlType(StandardTypes.VARBINARY) Slice slice, @SqlType("varchar(x)") Slice replacementCharacter)
{
int count = countCodePoints(replacementCharacter);
if (count > 1) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Replacement character string must empty or a single character");
}
OptionalInt replacementCodePoint;
if (count == 1) {
try {
replacementCodePoint = OptionalInt.of(getCodePointAt(replacementCharacter, 0));
}
catch (InvalidUtf8Exception e) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid replacement character");
}
}
else {
replacementCodePoint = OptionalInt.empty();
}
return SliceUtf8.fixInvalidUtf8(slice, replacementCodePoint);
}
@Description("decodes the UTF-8 encoded string")
@ScalarFunction
@SqlType(StandardTypes.VARCHAR)
public static Slice fromUtf8(@SqlType(StandardTypes.VARBINARY) Slice slice, @SqlType(StandardTypes.BIGINT) long replacementCodePoint)
{
if (replacementCodePoint > MAX_CODE_POINT || Character.getType((int) replacementCodePoint) == SURROGATE) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid replacement character");
}
return SliceUtf8.fixInvalidUtf8(slice, OptionalInt.of((int) replacementCodePoint));
}
@Description("encodes the string to UTF-8")
@ScalarFunction
@LiteralParameters("x")
@SqlType(StandardTypes.VARBINARY)
public static Slice toUtf8(@SqlType("varchar(x)") Slice slice)
{
return slice;
}
}
| |
/*
* Copyright 2000-2014 Vaadin 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.vaadin.ui;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import com.vaadin.event.ActionManager;
import com.vaadin.event.ConnectorActionManager;
import com.vaadin.event.ShortcutListener;
import com.vaadin.server.AbstractClientConnector;
import com.vaadin.server.AbstractErrorMessage.ContentMode;
import com.vaadin.server.ComponentSizeValidator;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.ErrorMessage.ErrorLevel;
import com.vaadin.server.Extension;
import com.vaadin.server.Resource;
import com.vaadin.server.Responsive;
import com.vaadin.server.SizeWithUnit;
import com.vaadin.server.Sizeable;
import com.vaadin.server.UserError;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.AbstractComponentState;
import com.vaadin.shared.ComponentConstants;
import com.vaadin.shared.ui.ComponentStateUtil;
import com.vaadin.shared.util.SharedUtil;
import com.vaadin.ui.Field.ValueChangeEvent;
import com.vaadin.ui.declarative.DesignAttributeHandler;
import com.vaadin.ui.declarative.DesignContext;
import com.vaadin.util.ReflectTools;
/**
* An abstract class that defines default implementation for the
* {@link Component} interface. Basic UI components that are not derived from an
* external component can inherit this class to easily qualify as Vaadin
* components. Most components in Vaadin do just that.
*
* @author Vaadin Ltd.
* @since 3.0
*/
@SuppressWarnings("serial")
public abstract class AbstractComponent extends AbstractClientConnector
implements Component {
/* Private members */
/**
* Application specific data object. The component does not use or modify
* this.
*/
private Object applicationData;
/**
* The internal error message of the component.
*/
private ErrorMessage componentError = null;
/**
* Locale of this component.
*/
private Locale locale;
/**
* The component should receive focus (if {@link Focusable}) when attached.
*/
private boolean delayedFocus;
/* Sizeable fields */
private float width = SIZE_UNDEFINED;
private float height = SIZE_UNDEFINED;
private Unit widthUnit = Unit.PIXELS;
private Unit heightUnit = Unit.PIXELS;
/**
* Keeps track of the Actions added to this component; the actual
* handling/notifying is delegated, usually to the containing window.
*/
private ConnectorActionManager actionManager;
private boolean visible = true;
private HasComponents parent;
private Boolean explicitImmediateValue;
protected static final String DESIGN_ATTR_PLAIN_TEXT = "plain-text";
/* Constructor */
/**
* Constructs a new Component.
*/
public AbstractComponent() {
// ComponentSizeValidator.setCreationLocation(this);
}
/* Get/Set component properties */
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#setId(java.lang.String)
*/
@Override
public void setId(String id) {
getState().id = id;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#getId()
*/
@Override
public String getId() {
return getState(false).id;
}
/**
* @deprecated As of 7.0. Use {@link #setId(String)}
*/
@Deprecated
public void setDebugId(String id) {
setId(id);
}
/**
* @deprecated As of 7.0. Use {@link #getId()}
*/
@Deprecated
public String getDebugId() {
return getId();
}
/*
* Gets the component's style. Don't add a JavaDoc comment here, we use the
* default documentation from implemented interface.
*/
@Override
public String getStyleName() {
String s = "";
if (ComponentStateUtil.hasStyles(getState(false))) {
for (final Iterator<String> it = getState(false).styles.iterator(); it
.hasNext();) {
s += it.next();
if (it.hasNext()) {
s += " ";
}
}
}
return s;
}
/*
* Sets the component's style. Don't add a JavaDoc comment here, we use the
* default documentation from implemented interface.
*/
@Override
public void setStyleName(String style) {
if (style == null || "".equals(style)) {
getState().styles = null;
return;
}
if (getState().styles == null) {
getState().styles = new ArrayList<String>();
}
List<String> styles = getState().styles;
styles.clear();
StringTokenizer tokenizer = new StringTokenizer(style, " ");
while (tokenizer.hasMoreTokens()) {
styles.add(tokenizer.nextToken());
}
}
@Override
public void setPrimaryStyleName(String style) {
getState().primaryStyleName = style;
}
@Override
public String getPrimaryStyleName() {
return getState(false).primaryStyleName;
}
@Override
public void addStyleName(String style) {
if (style == null || "".equals(style)) {
return;
}
if (style.contains(" ")) {
// Split space separated style names and add them one by one.
StringTokenizer tokenizer = new StringTokenizer(style, " ");
while (tokenizer.hasMoreTokens()) {
addStyleName(tokenizer.nextToken());
}
return;
}
if (getState().styles == null) {
getState().styles = new ArrayList<String>();
}
List<String> styles = getState().styles;
if (!styles.contains(style)) {
styles.add(style);
}
}
@Override
public void removeStyleName(String style) {
if (ComponentStateUtil.hasStyles(getState())) {
StringTokenizer tokenizer = new StringTokenizer(style, " ");
while (tokenizer.hasMoreTokens()) {
getState().styles.remove(tokenizer.nextToken());
}
}
}
/**
* Adds or removes a style name. Multiple styles can be specified as a
* space-separated list of style names.
*
* If the {@code add} parameter is true, the style name is added to the
* component. If the {@code add} parameter is false, the style name is
* removed from the component.
* <p>
* Functionally this is equivalent to using {@link #addStyleName(String)} or
* {@link #removeStyleName(String)}
*
* @since
* @param style
* the style name to be added or removed
* @param add
* <code>true</code> to add the given style, <code>false</code>
* to remove it
* @see #addStyleName(String)
* @see #removeStyleName(String)
*/
public void setStyleName(String style, boolean add) {
if (add) {
addStyleName(style);
} else {
removeStyleName(style);
}
}
/*
* Get's the component's caption. Don't add a JavaDoc comment here, we use
* the default documentation from implemented interface.
*/
@Override
public String getCaption() {
return getState(false).caption;
}
/**
* Sets the component's caption <code>String</code>. Caption is the visible
* name of the component. This method will trigger a
* {@link RepaintRequestEvent}.
*
* @param caption
* the new caption <code>String</code> for the component.
*/
@Override
public void setCaption(String caption) {
getState().caption = caption;
}
/**
* Sets whether the caption is rendered as HTML.
* <p>
* If set to true, the captions are rendered in the browser as HTML and the
* developer is responsible for ensuring no harmful HTML is used. If set to
* false, the caption is rendered in the browser as plain text.
* <p>
* The default is false, i.e. to render that caption as plain text.
*
* @param captionAsHtml
* true if the captions are rendered as HTML, false if rendered
* as plain text
*/
public void setCaptionAsHtml(boolean captionAsHtml) {
getState().captionAsHtml = captionAsHtml;
}
/**
* Checks whether captions are rendered as HTML
* <p>
* The default is false, i.e. to render that caption as plain text.
*
* @return true if the captions are rendered as HTML, false if rendered as
* plain text
*/
public boolean isCaptionAsHtml() {
return getState(false).captionAsHtml;
}
/*
* Don't add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
@Override
public Locale getLocale() {
if (locale != null) {
return locale;
}
HasComponents parent = getParent();
if (parent != null) {
return parent.getLocale();
}
final VaadinSession session = getSession();
if (session != null) {
return session.getLocale();
}
return null;
}
/**
* Sets the locale of this component.
*
* <pre>
* // Component for which the locale is meaningful
* InlineDateField date = new InlineDateField("Datum");
*
* // German language specified with ISO 639-1 language
* // code and ISO 3166-1 alpha-2 country code.
* date.setLocale(new Locale("de", "DE"));
*
* date.setResolution(DateField.RESOLUTION_DAY);
* layout.addComponent(date);
* </pre>
*
*
* @param locale
* the locale to become this component's locale.
*/
public void setLocale(Locale locale) {
this.locale = locale;
if (locale != null && isAttached()) {
getUI().getLocaleService().addLocale(locale);
}
markAsDirty();
}
/*
* Gets the component's icon resource. Don't add a JavaDoc comment here, we
* use the default documentation from implemented interface.
*/
@Override
public Resource getIcon() {
return getResource(ComponentConstants.ICON_RESOURCE);
}
/**
* Sets the component's icon. This method will trigger a
* {@link RepaintRequestEvent}.
*
* @param icon
* the icon to be shown with the component's caption.
*/
@Override
public void setIcon(Resource icon) {
setResource(ComponentConstants.ICON_RESOURCE, icon);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#isEnabled()
*/
@Override
public boolean isEnabled() {
return getState(false).enabled;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#setEnabled(boolean)
*/
@Override
public void setEnabled(boolean enabled) {
getState().enabled = enabled;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.client.Connector#isConnectorEnabled()
*/
@Override
public boolean isConnectorEnabled() {
if (!isVisible()) {
return false;
} else if (!isEnabled()) {
return false;
} else if (!super.isConnectorEnabled()) {
return false;
} else if ((getParent() instanceof SelectiveRenderer)
&& !((SelectiveRenderer) getParent()).isRendered(this)) {
return false;
} else {
return true;
}
}
/**
* Returns the explicitly set immediate value.
*
* @return the explicitly set immediate value or null if
* {@link #setImmediate(boolean)} has not been explicitly invoked
*/
protected Boolean getExplicitImmediateValue() {
return explicitImmediateValue;
}
/**
* Returns the immediate mode of the component.
* <p>
* Certain operations such as adding a value change listener will set the
* component into immediate mode if {@link #setImmediate(boolean)} has not
* been explicitly called with false.
*
* @return true if the component is in immediate mode (explicitly or
* implicitly set), false if the component if not in immediate mode
*/
public boolean isImmediate() {
if (explicitImmediateValue != null) {
return explicitImmediateValue;
} else if (hasListeners(ValueChangeEvent.class)) {
/*
* Automatic immediate for fields that developers are interested
* about.
*/
return true;
} else {
return false;
}
}
/**
* Sets the component's immediate mode to the specified status.
*
* @param immediate
* the boolean value specifying if the component should be in the
* immediate mode after the call.
*/
public void setImmediate(boolean immediate) {
explicitImmediateValue = immediate;
getState().immediate = immediate;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#isVisible()
*/
@Override
public boolean isVisible() {
return visible;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() == visible) {
return;
}
this.visible = visible;
if (visible) {
/*
* If the visibility state is toggled from invisible to visible it
* affects all children (the whole hierarchy) in addition to this
* component.
*/
markAsDirtyRecursive();
}
if (getParent() != null) {
// Must always repaint the parent (at least the hierarchy) when
// visibility of a child component changes.
getParent().markAsDirty();
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#getDescription()
*/
@Override
public String getDescription() {
return getState(false).description;
}
/**
* Sets the component's description. See {@link #getDescription()} for more
* information on what the description is. This method will trigger a
* {@link RepaintRequestEvent}.
*
* The description is displayed as HTML in tooltips or directly in certain
* components so care should be taken to avoid creating the possibility for
* HTML injection and possibly XSS vulnerabilities.
*
* @param description
* the new description string for the component.
*/
public void setDescription(String description) {
getState().description = description;
}
/*
* Gets the component's parent component. Don't add a JavaDoc comment here,
* we use the default documentation from implemented interface.
*/
@Override
public HasComponents getParent() {
return parent;
}
@Override
public void setParent(HasComponents parent) {
// If the parent is not changed, don't do anything
if (parent == null ? this.parent == null : parent.equals(this.parent)) {
return;
}
if (parent != null && this.parent != null) {
throw new IllegalStateException(getClass().getName()
+ " already has a parent.");
}
// Send a detach event if the component is currently attached
if (isAttached()) {
detach();
}
// Connect to new parent
this.parent = parent;
// Send attach event if the component is now attached
if (isAttached()) {
attach();
}
}
/**
* Returns the closest ancestor with the given type.
* <p>
* To find the Window that contains the component, use {@code Window w =
* getParent(Window.class);}
* </p>
*
* @param <T>
* The type of the ancestor
* @param parentType
* The ancestor class we are looking for
* @return The first ancestor that can be assigned to the given class. Null
* if no ancestor with the correct type could be found.
*/
public <T extends HasComponents> T findAncestor(Class<T> parentType) {
HasComponents p = getParent();
while (p != null) {
if (parentType.isAssignableFrom(p.getClass())) {
return parentType.cast(p);
}
p = p.getParent();
}
return null;
}
/**
* Gets the error message for this component.
*
* @return ErrorMessage containing the description of the error state of the
* component or null, if the component contains no errors. Extending
* classes should override this method if they support other error
* message types such as validation errors or buffering errors. The
* returned error message contains information about all the errors.
*/
public ErrorMessage getErrorMessage() {
return componentError;
}
/**
* Gets the component's error message.
*
* @link Terminal.ErrorMessage#ErrorMessage(String, int)
*
* @return the component's error message.
*/
public ErrorMessage getComponentError() {
return componentError;
}
/**
* Sets the component's error message. The message may contain certain XML
* tags, for more information see
*
* @link Component.ErrorMessage#ErrorMessage(String, int)
*
* @param componentError
* the new <code>ErrorMessage</code> of the component.
*/
public void setComponentError(ErrorMessage componentError) {
this.componentError = componentError;
fireComponentErrorEvent();
markAsDirty();
}
/*
* Tests if the component is in read-only mode. Don't add a JavaDoc comment
* here, we use the default documentation from implemented interface.
*/
@Override
public boolean isReadOnly() {
return getState(false).readOnly;
}
/*
* Sets the component's read-only mode. Don't add a JavaDoc comment here, we
* use the default documentation from implemented interface.
*/
@Override
public void setReadOnly(boolean readOnly) {
getState().readOnly = readOnly;
}
/*
* Notify the component that it's attached to a window. Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
@Override
public void attach() {
super.attach();
if (delayedFocus) {
focus();
}
setActionManagerViewer();
if (locale != null) {
getUI().getLocaleService().addLocale(locale);
}
}
/*
* Detach the component from application. Don't add a JavaDoc comment here,
* we use the default documentation from implemented interface.
*/
@Override
public void detach() {
super.detach();
if (actionManager != null) {
// Remove any existing viewer. UI cast is just to make the
// compiler happy
actionManager.setViewer((UI) null);
}
}
/**
* Sets the focus for this component if the component is {@link Focusable}.
*/
protected void focus() {
if (this instanceof Focusable) {
final VaadinSession session = getSession();
if (session != null) {
getUI().setFocusedComponent((Focusable) this);
delayedFocus = false;
} else {
delayedFocus = true;
}
}
}
/**
* Build CSS compatible string representation of height.
*
* @return CSS height
*/
private String getCSSHeight() {
return getHeight() + getHeightUnits().getSymbol();
}
/**
* Build CSS compatible string representation of width.
*
* @return CSS width
*/
private String getCSSWidth() {
return getWidth() + getWidthUnits().getSymbol();
}
/**
* Returns the shared state bean with information to be sent from the server
* to the client.
*
* Subclasses should override this method and set any relevant fields of the
* state returned by super.getState().
*
* @since 7.0
*
* @return updated component shared state
*/
@Override
protected AbstractComponentState getState() {
return (AbstractComponentState) super.getState();
}
@Override
protected AbstractComponentState getState(boolean markAsDirty) {
return (AbstractComponentState) super.getState(markAsDirty);
}
@Override
public void beforeClientResponse(boolean initial) {
super.beforeClientResponse(initial);
// TODO This logic should be on the client side and the state should
// simply be a data object with "width" and "height".
if (getHeight() >= 0
&& (getHeightUnits() != Unit.PERCENTAGE || ComponentSizeValidator
.parentCanDefineHeight(this))) {
getState().height = "" + getCSSHeight();
} else {
getState().height = "";
}
if (getWidth() >= 0
&& (getWidthUnits() != Unit.PERCENTAGE || ComponentSizeValidator
.parentCanDefineWidth(this))) {
getState().width = "" + getCSSWidth();
} else {
getState().width = "";
}
ErrorMessage error = getErrorMessage();
if (null != error) {
getState().errorMessage = error.getFormattedHtmlMessage();
} else {
getState().errorMessage = null;
}
getState().immediate = isImmediate();
}
/* General event framework */
private static final Method COMPONENT_EVENT_METHOD = ReflectTools
.findMethod(Component.Listener.class, "componentEvent",
Component.Event.class);
/* Component event framework */
/*
* Registers a new listener to listen events generated by this component.
* Don't add a JavaDoc comment here, we use the default documentation from
* implemented interface.
*/
@Override
public void addListener(Component.Listener listener) {
addListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD);
}
/*
* Removes a previously registered listener from this component. Don't add a
* JavaDoc comment here, we use the default documentation from implemented
* interface.
*/
@Override
public void removeListener(Component.Listener listener) {
removeListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD);
}
/**
* Emits the component event. It is transmitted to all registered listeners
* interested in such events.
*/
protected void fireComponentEvent() {
fireEvent(new Component.Event(this));
}
/**
* Emits the component error event. It is transmitted to all registered
* listeners interested in such events.
*/
protected void fireComponentErrorEvent() {
fireEvent(new Component.ErrorEvent(getComponentError(), this));
}
/**
* Sets the data object, that can be used for any application specific data.
* The component does not use or modify this data.
*
* @param data
* the Application specific data.
* @since 3.1
*/
public void setData(Object data) {
applicationData = data;
}
/**
* Gets the application specific data. See {@link #setData(Object)}.
*
* @return the Application specific data set with setData function.
* @since 3.1
*/
public Object getData() {
return applicationData;
}
/* Sizeable and other size related methods */
/*
* (non-Javadoc)
*
* @see com.vaadin.Sizeable#getHeight()
*/
@Override
public float getHeight() {
return height;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#getHeightUnits()
*/
@Override
public Unit getHeightUnits() {
return heightUnit;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#getWidth()
*/
@Override
public float getWidth() {
return width;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#getWidthUnits()
*/
@Override
public Unit getWidthUnits() {
return widthUnit;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setHeight(float, Unit)
*/
@Override
public void setHeight(float height, Unit unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit can not be null");
}
this.height = height;
heightUnit = unit;
markAsDirty();
// ComponentSizeValidator.setHeightLocation(this);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setSizeFull()
*/
@Override
public void setSizeFull() {
setWidth(100, Unit.PERCENTAGE);
setHeight(100, Unit.PERCENTAGE);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setSizeUndefined()
*/
@Override
public void setSizeUndefined() {
setWidthUndefined();
setHeightUndefined();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setWidthUndefined()
*/
@Override
public void setWidthUndefined() {
setWidth(-1, Unit.PIXELS);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setHeightUndefined()
*/
@Override
public void setHeightUndefined() {
setHeight(-1, Unit.PIXELS);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setWidth(float, Unit)
*/
@Override
public void setWidth(float width, Unit unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit can not be null");
}
this.width = width;
widthUnit = unit;
markAsDirty();
// ComponentSizeValidator.setWidthLocation(this);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setWidth(java.lang.String)
*/
@Override
public void setWidth(String width) {
SizeWithUnit size = SizeWithUnit.parseStringSize(width);
if (size != null) {
setWidth(size.getSize(), size.getUnit());
} else {
setWidth(-1, Unit.PIXELS);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.server.Sizeable#setHeight(java.lang.String)
*/
@Override
public void setHeight(String height) {
SizeWithUnit size = SizeWithUnit.parseStringSize(height);
if (size != null) {
setHeight(size.getSize(), size.getUnit());
} else {
setHeight(-1, Unit.PIXELS);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#readDesign(org.jsoup.nodes.Element,
* com.vaadin.ui.declarative.DesignContext)
*/
@Override
public void readDesign(Element design, DesignContext designContext) {
Attributes attr = design.attributes();
// handle default attributes
for (String attribute : getDefaultAttributes()) {
if (design.hasAttr(attribute)) {
DesignAttributeHandler.assignValue(this, attribute,
design.attr(attribute));
}
}
// handle immediate
if (attr.hasKey("immediate")) {
setImmediate(DesignAttributeHandler.getFormatter().parse(
attr.get("immediate"), Boolean.class));
}
// handle locale
if (attr.hasKey("locale")) {
setLocale(getLocaleFromString(attr.get("locale")));
}
// handle width and height
readSize(attr);
// handle component error
if (attr.hasKey("error")) {
UserError error = new UserError(attr.get("error"),
ContentMode.HTML, ErrorLevel.ERROR);
setComponentError(error);
}
// Tab index when applicable
if (design.hasAttr("tabindex") && this instanceof Focusable) {
((Focusable) this).setTabIndex(DesignAttributeHandler
.readAttribute("tabindex", design.attributes(),
Integer.class));
}
// check for unsupported attributes
Set<String> supported = new HashSet<String>();
supported.addAll(getDefaultAttributes());
supported.addAll(getCustomAttributes());
for (Attribute a : attr) {
if (!a.getKey().startsWith(":") && !supported.contains(a.getKey())) {
getLogger().info(
"Unsupported attribute found when reading from design : "
+ a.getKey());
}
}
}
/**
* Constructs a Locale corresponding to the given string. The string should
* consist of one, two or three parts with '_' between the different parts
* if there is more than one part. The first part specifies the language,
* the second part the country and the third part the variant of the locale.
*
* @param localeString
* the locale specified as a string
* @return the Locale object corresponding to localeString
*/
private Locale getLocaleFromString(String localeString) {
if (localeString == null) {
return null;
}
String[] parts = localeString.split("_");
if (parts.length > 3) {
throw new RuntimeException("Cannot parse the locale string: "
+ localeString);
}
switch (parts.length) {
case 1:
return new Locale(parts[0]);
case 2:
return new Locale(parts[0], parts[1]);
default:
return new Locale(parts[0], parts[1], parts[2]);
}
}
/**
* Toggles responsiveness of this component.
*
* @since 7.5.0
* @param responsive
* boolean enables responsiveness, false disables
*/
public void setResponsive(boolean responsive) {
if (responsive) {
// make responsive if necessary
if (!isResponsive()) {
Responsive.makeResponsive(this);
}
} else {
// remove responsive extensions
List<Extension> extensions = new ArrayList<Extension>(
getExtensions());
for (Extension e : extensions) {
if (e instanceof Responsive) {
removeExtension(e);
}
}
}
}
/**
* Returns true if the component is responsive
*
* @since 7.5.0
* @return true if the component is responsive
*/
public boolean isResponsive() {
for (Extension e : getExtensions()) {
if (e instanceof Responsive) {
return true;
}
}
return false;
}
/**
* Reads the size of this component from the given design attributes. If the
* attributes do not contain relevant size information, defaults is
* consulted.
*
* @param attributes
* the design attributes
* @param defaultInstance
* instance of the class that has default sizing.
*/
private void readSize(Attributes attributes) {
// read width
if (attributes.hasKey("width-auto") || attributes.hasKey("size-auto")) {
this.setWidth(null);
} else if (attributes.hasKey("width-full")
|| attributes.hasKey("size-full")) {
this.setWidth("100%");
} else if (attributes.hasKey("width")) {
this.setWidth(attributes.get("width"));
}
// read height
if (attributes.hasKey("height-auto") || attributes.hasKey("size-auto")) {
this.setHeight(null);
} else if (attributes.hasKey("height-full")
|| attributes.hasKey("size-full")) {
this.setHeight("100%");
} else if (attributes.hasKey("height")) {
this.setHeight(attributes.get("height"));
}
}
/**
* Writes the size related attributes for the component if they differ from
* the defaults
*
* @param component
* the component
* @param attributes
* the attribute map where the attribute are written
* @param defaultInstance
* the default instance of the class for fetching the default
* values
*/
private void writeSize(Attributes attributes, Component defaultInstance) {
if (hasEqualSize(defaultInstance)) {
// we have default values -> ignore
return;
}
boolean widthFull = getWidth() == 100f
&& getWidthUnits().equals(Sizeable.Unit.PERCENTAGE);
boolean heightFull = getHeight() == 100f
&& getHeightUnits().equals(Sizeable.Unit.PERCENTAGE);
boolean widthAuto = getWidth() == -1;
boolean heightAuto = getHeight() == -1;
// first try the full shorthands
if (widthFull && heightFull) {
attributes.put("size-full", "true");
} else if (widthAuto && heightAuto) {
attributes.put("size-auto", "true");
} else {
// handle width
if (!hasEqualWidth(defaultInstance)) {
if (widthFull) {
attributes.put("width-full", "true");
} else if (widthAuto) {
attributes.put("width-auto", "true");
} else {
String widthString = DesignAttributeHandler.getFormatter()
.format(getWidth()) + getWidthUnits().getSymbol();
attributes.put("width", widthString);
}
}
if (!hasEqualHeight(defaultInstance)) {
// handle height
if (heightFull) {
attributes.put("height-full", "true");
} else if (heightAuto) {
attributes.put("height-auto", "true");
} else {
String heightString = DesignAttributeHandler.getFormatter()
.format(getHeight()) + getHeightUnits().getSymbol();
attributes.put("height", heightString);
}
}
}
}
/**
* Test if the given component has equal width with this instance
*
* @param component
* the component for the width comparison
* @return true if the widths are equal
*/
private boolean hasEqualWidth(Component component) {
return getWidth() == component.getWidth()
&& getWidthUnits().equals(component.getWidthUnits());
}
/**
* Test if the given component has equal height with this instance
*
* @param component
* the component for the height comparison
* @return true if the heights are equal
*/
private boolean hasEqualHeight(Component component) {
return getHeight() == component.getHeight()
&& getHeightUnits().equals(component.getHeightUnits());
}
/**
* Test if the given components has equal size with this instance
*
* @param component
* the component for the size comparison
* @return true if the sizes are equal
*/
private boolean hasEqualSize(Component component) {
return hasEqualWidth(component) && hasEqualHeight(component);
}
/**
* Returns a collection of attributes that do not require custom handling
* when reading or writing design. These are typically attributes of some
* primitive type. The default implementation searches setters with
* primitive values
*
* @return a collection of attributes that can be read and written using the
* default approach.
*/
private Collection<String> getDefaultAttributes() {
Collection<String> attributes = DesignAttributeHandler
.getSupportedAttributes(this.getClass());
attributes.removeAll(getCustomAttributes());
return attributes;
}
/**
* Returns a collection of attributes that should not be handled by the
* basic implementation of the {@link readDesign} and {@link writeDesign}
* methods. Typically these are handled in a custom way in the overridden
* versions of the above methods
*
* @since 7.4
*
* @return the collection of attributes that are not handled by the basic
* implementation
*/
protected Collection<String> getCustomAttributes() {
ArrayList<String> l = new ArrayList<String>(
Arrays.asList(customAttributes));
if (this instanceof Focusable) {
l.add("tab-index");
l.add("tabindex");
}
return l;
}
private static final String[] customAttributes = new String[] { "width",
"height", "debug-id", "error", "width-auto", "height-auto",
"width-full", "height-full", "size-auto", "size-full", "immediate",
"locale", "read-only", "_id" };
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.Component#writeDesign(org.jsoup.nodes.Element,
* com.vaadin.ui.declarative.DesignContext)
*/
@Override
public void writeDesign(Element design, DesignContext designContext) {
AbstractComponent def = designContext.getDefaultInstance(this);
Attributes attr = design.attributes();
// handle default attributes
for (String attribute : getDefaultAttributes()) {
DesignAttributeHandler.writeAttribute(this, attribute, attr, def);
}
// handle immediate
if (explicitImmediateValue != null) {
DesignAttributeHandler.writeAttribute("immediate", attr,
explicitImmediateValue, def.isImmediate(), Boolean.class);
}
// handle locale
if (getLocale() != null
&& (getParent() == null || !getLocale().equals(
getParent().getLocale()))) {
design.attr("locale", getLocale().toString());
}
// handle size
writeSize(attr, def);
// handle component error
String errorMsg = getComponentError() != null ? getComponentError()
.getFormattedHtmlMessage() : null;
String defErrorMsg = def.getComponentError() != null ? def
.getComponentError().getFormattedHtmlMessage() : null;
if (!SharedUtil.equals(errorMsg, defErrorMsg)) {
attr.put("error", errorMsg);
}
// handle tab index
if (this instanceof Focusable) {
DesignAttributeHandler.writeAttribute("tabindex", attr,
((Focusable) this).getTabIndex(),
((Focusable) def).getTabIndex(), Integer.class);
}
}
/*
* Actions
*/
/**
* Gets the {@link ActionManager} used to manage the
* {@link ShortcutListener}s added to this {@link Field}.
*
* @return the ActionManager in use
*/
protected ActionManager getActionManager() {
if (actionManager == null) {
actionManager = new ConnectorActionManager(this);
setActionManagerViewer();
}
return actionManager;
}
/**
* Set a viewer for the action manager to be the parent sub window (if the
* component is in a window) or the UI (otherwise). This is still a
* simplification of the real case as this should be handled by the parent
* VOverlay (on the client side) if the component is inside an VOverlay
* component.
*/
private void setActionManagerViewer() {
if (actionManager != null && getUI() != null) {
// Attached and has action manager
Window w = findAncestor(Window.class);
if (w != null) {
actionManager.setViewer(w);
} else {
actionManager.setViewer(getUI());
}
}
}
public void addShortcutListener(ShortcutListener shortcut) {
getActionManager().addAction(shortcut);
}
public void removeShortcutListener(ShortcutListener shortcut) {
if (actionManager != null) {
actionManager.removeAction(shortcut);
}
}
/**
* Determine whether a <code>content</code> component is equal to, or the
* ancestor of this component.
*
* @param content
* the potential ancestor element
* @return <code>true</code> if the relationship holds
*/
protected boolean isOrHasAncestor(Component content) {
if (content instanceof HasComponents) {
for (Component parent = this; parent != null; parent = parent
.getParent()) {
if (parent.equals(content)) {
return true;
}
}
}
return false;
}
private static final Logger getLogger() {
return Logger.getLogger(AbstractComponent.class.getName());
}
}
| |
/*
* Copyright (c) 2005-2010 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.framework.util.helpers;
import static org.mifos.framework.TestUtils.EURO;
import static org.mifos.framework.TestUtils.RUPEE;
import java.math.BigDecimal;
import java.math.RoundingMode;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.config.AccountingRulesConstants;
import org.mifos.config.ConfigurationManager;
import org.mifos.core.CurrencyMismatchException;
import org.mifos.framework.TestUtils;
import org.testng.annotations.Test;
@Test(groups={"unit", "fastTestsSuite"}, dependsOnGroups={"productMixTestSuite"})
public class MoneyTest extends TestCase {
public void testAdd() {
Money money = new Money(RUPEE, "100.0");
Money addendend = new Money(RUPEE, "200.0");
Assert.assertEquals("testing Add, should succeed", new Money(RUPEE, "300.0"), money.add(addendend));
}
public void testAddMultipleDecimalAmounts() {
Money money = new Money(RUPEE, "0.1");
Money money1 = money.add(new Money(RUPEE, "0.1"));
Money money2 = money1.add(new Money(RUPEE, "0.1"));
Money money3 = money2.add(new Money(RUPEE, "0.1"));
Money money4 = money3.add(new Money(RUPEE, "0.1"));
Assert.assertEquals("testing addMultipleDecimalAmounts, should succeed", new Money(RUPEE, "0.5"), money4);
}
public void testAddWithDiffCurrencies() {
Money money = new Money(RUPEE, "100.0");
try {
Money addendendWithDiffCurrecny = new Money(EURO, "200");
money.add(addendendWithDiffCurrecny);
Assert.fail("testing Add with different currencies should throw an exception.");
} catch (CurrencyMismatchException e) {
}
}
public void testSubtract() {
Money subtrahend = new Money(RUPEE, "100.0");
Money money = new Money(RUPEE, "200.0");
Assert.assertEquals("testing subtract, should succeed", new Money(RUPEE, "100.0"), money.subtract(subtrahend));
}
public void testSubtractWithDiffCurrencies() {
Money money = new Money(RUPEE, "100.0");
try {
Money subtrahendWithDiffCurrecny = new Money(EURO, "100");
money.subtract(subtrahendWithDiffCurrecny);
Assert.fail("testing subtract with different currencies should throw an exception.");
} catch (CurrencyMismatchException e) {
}
}
public void testMultiply() {
BigDecimal multiplicand = new BigDecimal("10.0");
Money money = new Money(RUPEE, "20.0");
Assert.assertEquals("testing multiply, should succeed", new Money(RUPEE, "200.0"), money.multiply(multiplicand));
}
public void testFactorMultiply() {
Money money = new Money(RUPEE, "100.0");
Double factor = new Double(1.24);
Assert.assertEquals("testing multiply with a factor, should succeed", new Money(RUPEE, "124.0"), money
.multiply(factor));
}
public void testMultiplyBigDecimal() {
Money money = new Money(RUPEE, "100.0");
BigDecimal factor = new BigDecimal(1.24);
Assert.assertEquals("testing multiply with a factor, should succeed", new Money(RUPEE, "124.0"), money
.multiply(factor));
}
public void testDivideByMoney() {
Money dividend = new Money(RUPEE, new BigDecimal(10.0));
Money money = new Money(RUPEE, "20.0");
Assert.assertEquals("testing divide, should succeed", new BigDecimal("2.0000000000000"), money.divide(dividend));
}
public void testDivideByBigDecimal() {
BigDecimal dividend = new BigDecimal(10.0);
Money money = new Money(RUPEE, "20.0");
Assert.assertEquals("testing divide, should succeed", new Money(RUPEE, "2.0"), money.divide(dividend));
}
public void testDivideByShort() {
Short dividend = new Short("4");
Money money = new Money(RUPEE, "20.0");
Assert.assertEquals("testing divide, should succeed", new Money(RUPEE, "5.00000000000000"), money.divide(dividend));
}
public void testDivideByInteger() {
Integer dividend = new Integer("3");
Money money = new Money(RUPEE, "20.0");
Money expected = new Money(RUPEE, "6.6666666666667");
Money result = money.divide(dividend);
Assert.assertEquals("testing divide, should succeed", expected, result);
}
public void testDivideRepeating() {
BigDecimal dividend = new BigDecimal("3.0");
Money money = new Money(RUPEE, "10.0");
Assert.assertEquals("testing divide, should succeed", new Money(RUPEE, "3.3333333333333"), money.divide(dividend));
money = new Money(RUPEE, "20.0");
Assert.assertEquals("testing divide, should succeed", new Money(RUPEE, "6.6666666666667"), money.divide(dividend));
}
public void testDivideWithDiffCurrencies() {
Money money = new Money(RUPEE, "20.0");
try {
Money dividendWithDiffCurrecny = new Money(EURO, "10");
money.divide(dividendWithDiffCurrecny);
Assert.fail("testing divide with different currencies should throw an exception.");
} catch (CurrencyMismatchException e) {
}
}
public void testNegate() {
Money money = new Money(RUPEE, "20.0");
Assert.assertEquals(new Money(RUPEE, "-20.0"), money.negate());
}
public void testRoundUp() {
Money money = new Money(RUPEE, "142.34");
Assert.assertEquals(new Money(RUPEE, "143.00"), Money.round(money, money.getCurrency().getRoundingAmount(), RoundingMode.CEILING));
}
public void testRoundDown() {
Money money = new Money(EURO, "142.34");
Assert.assertEquals(new Money(EURO, "142.00"), Money.round(money, money.getCurrency().getRoundingAmount(), RoundingMode.FLOOR));
}
public void testRoundRepeating() {
MifosCurrency currency = new MifosCurrency((short) 1, "test", BigDecimal.valueOf(3.0), "USD");
Money money = new Money(currency, "1");
Assert.assertEquals(new Money(currency, "3"), Money.round(money, currency.getRoundingAmount(), RoundingMode.CEILING));
}
public void testRoundWhenRoundingOffMultipleIsHundred() {
BigDecimal roundingOffMultiple = BigDecimal.valueOf(100);
Money roundedMoney = Money.round(new Money(EURO, "1100"), roundingOffMultiple, RoundingMode.CEILING);
Assert.assertEquals(new Money(EURO, "1100"), roundedMoney);
roundedMoney = Money.round(new Money(EURO, "1101"), roundingOffMultiple, RoundingMode.CEILING);
Assert.assertEquals(new Money(EURO, "1200"), roundedMoney);
roundedMoney = Money.round(new Money(EURO, "1149"), roundingOffMultiple, RoundingMode.HALF_UP);
Assert.assertEquals(new Money(EURO, "1100"), roundedMoney);
roundedMoney = Money.round(new Money(EURO, "1150"), roundingOffMultiple, RoundingMode.HALF_UP);
Assert.assertEquals(new Money(EURO, "1200"), roundedMoney);
roundedMoney = Money.round(new Money(EURO, "1199"), roundingOffMultiple, RoundingMode.FLOOR);
Assert.assertEquals(new Money(EURO, "1100"), roundedMoney);
roundedMoney = Money.round(new Money(EURO, "1199"), roundingOffMultiple, RoundingMode.FLOOR);
Assert.assertEquals(new Money(EURO, "1100"), roundedMoney);
}
public void testRoundingExceptionWhenRoundingOffMultipleIsZero() {
BigDecimal roundingOffMultiple = BigDecimal.valueOf(0);
try {
Money.round(new Money(EURO, "1100"), roundingOffMultiple, RoundingMode.CEILING);
} catch (ArithmeticException e) {}
}
public void testIsRoundedAmount() {
String currencyCodeSuffix = "." + TestUtils.EURO.getCurrencyCode();
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.DIGITS_AFTER_DECIMAL+currencyCodeSuffix, "1");
configMgr.setProperty(AccountingRulesConstants.INITIAL_ROUND_OFF_MULTIPLE+currencyCodeSuffix, "1");
configMgr.setProperty(AccountingRulesConstants.FINAL_ROUND_OFF_MULTIPLE+currencyCodeSuffix, "1");
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
try {
Assert.assertTrue(MoneyUtils.isRoundedAmount(new Money(EURO, "1")));
Assert.assertFalse(MoneyUtils.isRoundedAmount(new Money(EURO, "1.1")));
Money.setDefaultCurrency(RUPEE);
Assert.assertFalse(MoneyUtils.isRoundedAmount(1.1));
} finally {
configMgr.clearProperty(AccountingRulesConstants.DIGITS_AFTER_DECIMAL+currencyCodeSuffix);
configMgr.clearProperty(AccountingRulesConstants.INITIAL_ROUND_OFF_MULTIPLE+currencyCodeSuffix);
configMgr.clearProperty(AccountingRulesConstants.FINAL_ROUND_OFF_MULTIPLE+currencyCodeSuffix);
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
}
public void testDivideMoneyRepeating() {
Money dividend = new Money(RUPEE, "3.0");
Money money = new Money(RUPEE, "10.0");
Assert.assertEquals("testing divide, should succeed", new BigDecimal("3.3333333333333"), money.divide(dividend));
}
public void testHashCode() {
Money money = new Money(RUPEE, "142.34");
BigDecimal amnt = new BigDecimal(142.34);
Assert.assertEquals((money.getCurrency().getCurrencyId() * 100 + amnt.intValue()), money.hashCode());
}
public void testHashCodeForNullCurrency() {
try {
Money money = new Money(null, "0");
Assert.assertEquals(0, money.hashCode());
}catch (NullPointerException e) {
Assert.assertEquals(e.getLocalizedMessage(), ExceptionConstants.CURRENCY_MUST_NOT_BE_NULL);
}
}
public void testToString() {
Money money = new Money(RUPEE, "4456456456.6");
Assert.assertEquals("The toString of money returns : ", "4456456456.6", money.toString());
}
public void testIsGreaterThan() {
Money large = new Money(RUPEE, "10.0");
Money small = new Money(RUPEE, "1.0");
Money same = new Money(RUPEE, "10.0");
Assert.assertTrue("large should be greater than small", large.isGreaterThan(small));
Assert.assertFalse("large should not be greater than itself", large.isGreaterThan(large));
Assert.assertFalse("small should not be greater than large", small.isGreaterThan(large));
Assert.assertFalse("large should not be equal to same", large.isGreaterThan(same));
}
public void testIsGreaterThanOrEqual() {
Money large = new Money(RUPEE, "10.0");
Money small = new Money(RUPEE, "1.0");
Assert.assertTrue(large.isGreaterThanOrEqual(small));
Assert.assertTrue(large.isGreaterThanOrEqual(large));
Assert.assertFalse(small.isGreaterThanOrEqual(large));
}
public void testIsGreaterThanZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE, "0.0");
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertTrue(nonZero.isGreaterThanZero());
Assert.assertFalse(lessThanZero.isGreaterThanZero());
Assert.assertFalse(zero.isGreaterThanZero());
}
public void testIsGreaterThanOrEqualZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE, "0.0");
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertTrue(nonZero.isGreaterThanZero());
Assert.assertFalse(lessThanZero.isGreaterThanOrEqualZero());
Assert.assertTrue(zero.isGreaterThanOrEqualZero());
}
public void testIsLessThan() {
Money large = new Money(EURO, "10.0");
Money small = new Money(EURO, "1.0");
Assert.assertTrue("small should be less than large", small.isLessThan(large));
Assert.assertFalse("small should not be less than itself", small.isLessThan(small));
Assert.assertFalse("large should not be less than small", large.isLessThan(small));
}
public void testIsLessThanOrEqual() {
Money large = new Money(RUPEE, "10.0");
Money small = new Money(RUPEE, "1.0");
Money same = new Money(RUPEE, "10.0");
Assert.assertFalse(large.isLessThanOrEqual(small));
Assert.assertTrue(small.isLessThanOrEqual(large));
Assert.assertTrue(small.isLessThanOrEqual(large));
Assert.assertTrue(large.isLessThanOrEqual(same));
}
public void testIsLessThanZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE);
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertFalse(nonZero.isLessThanZero());
Assert.assertTrue(lessThanZero.isLessThanZero());
Assert.assertFalse(zero.isLessThanZero());
}
public void testIsLessThanOrEqualZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE);
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertFalse(nonZero.isLessThanOrEqualZero());
Assert.assertTrue(lessThanZero.isLessThanOrEqualZero());
Assert.assertTrue(zero.isLessThanOrEqualZero());
}
public void testIsZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE);
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertFalse(nonZero.isZero());
Assert.assertFalse(lessThanZero.isZero());
Assert.assertTrue(zero.isZero());
}
public void testIsNonZero() {
Money nonZero = new Money(RUPEE, "10.0");
Money zero = new Money(RUPEE);
Money lessThanZero = new Money(RUPEE, "-2.0");
Assert.assertTrue(nonZero.isNonZero());
Assert.assertTrue(lessThanZero.isNonZero());
Assert.assertFalse(zero.isNonZero());
}
public void testIsLessThanForDifferentCurrencies() {
Money large = new Money(RUPEE, "10.0");
Money small = new Money(EURO, "1.0");
try {
Assert.assertFalse("large should not be less than small", large.isLessThan(small));
Assert.fail("Comparing two different currencies should throw and exceeption");
} catch (RuntimeException e) {
}
}
public void testIsGreaterThanForDifferentCurrencies() {
Money large = new Money(RUPEE, "10.0");
Money small = new Money(EURO, "1.0");
try {
Assert.assertFalse("large should not be less than small", large.isGreaterThan(small));
Assert.fail("Comparing two different currencies should throw and exceeption");
} catch (RuntimeException e) {
}
}
}
| |
package replicant;
import arez.component.Linkable;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import replicant.messages.ChangeSetMessage;
import replicant.messages.ChannelChange;
import replicant.messages.EntityChange;
import replicant.messages.EntityChangeDataImpl;
import replicant.spy.DataLoadStatus;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
public class MessageResponseTest
extends AbstractReplicantTest
{
@Test
public void construct()
{
final MessageResponse action =
new MessageResponse( 1, ChangeSetMessage.create( null, null, null, null, null ), null );
assertFalse( action.areEntityLinksPending() );
assertFalse( action.areEntityChangesPending() );
assertFalse( action.hasWorldBeenValidated() );
assertEquals( action.getChannelAddCount(), 0 );
assertEquals( action.getChannelUpdateCount(), 0 );
assertEquals( action.getChannelRemoveCount(), 0 );
assertEquals( action.getEntityUpdateCount(), 0 );
assertEquals( action.getEntityRemoveCount(), 0 );
assertEquals( action.getEntityLinkCount(), 0 );
}
@Test
public void toStatus()
{
final ChangeSetMessage changeSet =
ChangeSetMessage.create( null, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] );
final MessageResponse action = new MessageResponse( 1, changeSet, null );
action.incChannelAddCount();
action.incChannelAddCount();
action.incChannelRemoveCount();
action.incChannelRemoveCount();
action.incChannelRemoveCount();
action.incChannelUpdateCount();
action.incEntityUpdateCount();
action.incEntityRemoveCount();
action.incEntityRemoveCount();
action.incEntityLinkCount();
final DataLoadStatus status = action.toStatus();
assertEquals( status.getRequestId(), null );
assertEquals( status.getChannelAddCount(), 2 );
assertEquals( status.getChannelUpdateCount(), 1 );
assertEquals( status.getChannelRemoveCount(), 3 );
assertEquals( status.getEntityUpdateCount(), 1 );
assertEquals( status.getEntityRemoveCount(), 2 );
assertEquals( status.getEntityLinkCount(), 1 );
}
@Test
public void incIgnoredUnlessSpyEnabled()
{
ReplicantTestUtil.disableSpies();
final MessageResponse action = new MessageResponse( 1, new ChangeSetMessage(), null );
assertEquals( action.getChannelAddCount(), 0 );
assertEquals( action.getChannelUpdateCount(), 0 );
assertEquals( action.getChannelRemoveCount(), 0 );
assertEquals( action.getEntityUpdateCount(), 0 );
assertEquals( action.getEntityRemoveCount(), 0 );
assertEquals( action.getEntityLinkCount(), 0 );
// We enforce this to make it easier for DCE
action.incChannelAddCount();
action.incChannelRemoveCount();
action.incChannelUpdateCount();
action.incEntityUpdateCount();
action.incEntityRemoveCount();
action.incEntityLinkCount();
assertEquals( action.getChannelAddCount(), 0 );
assertEquals( action.getChannelUpdateCount(), 0 );
assertEquals( action.getChannelRemoveCount(), 0 );
assertEquals( action.getEntityUpdateCount(), 0 );
assertEquals( action.getEntityRemoveCount(), 0 );
assertEquals( action.getEntityLinkCount(), 0 );
}
@Test
public void testToString()
{
final ChangeSetMessage changeSet =
ChangeSetMessage.create( null, null, null, new ChannelChange[ 0 ], new EntityChange[ 0 ] );
final MessageResponse action = new MessageResponse( 1, changeSet, null );
assertEquals( action.toString(),
"MessageResponse[Type=update,RequestId=null,ChangeIndex=0,CompletionAction.null?=true,UpdatedEntities.size=0]" );
// Null out Entities
action.nextEntityToLink();
assertEquals( action.toString(),
"MessageResponse[Type=update,RequestId=null,ChangeIndex=0,CompletionAction.null?=true,UpdatedEntities.size=0]" );
ReplicantTestUtil.disableNames();
assertEquals( action.toString(),
"replicant.MessageResponse@" + Integer.toHexString( System.identityHashCode( action ) ) );
}
@Test
public void lifeCycleWithNormallyCompletedRequest()
{
// ChangeSet details
final int requestId = ValueUtil.randomInt();
// Channel updates
final ChannelChange[] channelChanges = new ChannelChange[ 0 ];
// Entity Updates
final int channelId = 22;
// Entity update
final EntityChange change1 =
EntityChange.create( 100, 50,
new String[]{ String.valueOf( channelId ) },
new EntityChangeDataImpl() );
// Entity Remove
final EntityChange change2 =
EntityChange.create( 100, 51,
new String[]{ String.valueOf( channelId ) } );
// Entity update - non linkable
final EntityChange change3 =
EntityChange.create( 100, 52,
new String[]{ String.valueOf( channelId ) },
new EntityChangeDataImpl() );
final EntityChange[] entityChanges = new EntityChange[]{ change1, change2, change3 };
final Object[] entities = new Object[]{ mock( Linkable.class ), new Object(), new Object() };
final ChangeSetMessage changeSet =
ChangeSetMessage.create( requestId, null, null, channelChanges, entityChanges );
final String requestKey = ValueUtil.randomString();
final RequestEntry request = new RequestEntry( requestId, requestKey, false );
final SafeProcedure completionAction = mock( SafeProcedure.class );
final MessageResponse action = new MessageResponse( 1, changeSet, request );
assertNull( action.getCompletionAction() );
request.setCompletionAction( completionAction );
request.setNormalCompletion( true );
assertEquals( action.getCompletionAction(), completionAction );
assertEquals( request.getCompletionAction(), completionAction );
assertEquals( action.getMessage(), changeSet );
assertEquals( action.getRequest(), request );
assertFalse( action.needsChannelChangesProcessed() );
assertTrue( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertFalse( action.hasWorldBeenValidated() );
// Process entity changes
{
assertEquals( action.nextEntityChange(), entityChanges[ 0 ] );
action.changeProcessed( entities[ 0 ] );
action.incEntityUpdateCount();
assertTrue( action.areEntityChangesPending() );
assertEquals( action.nextEntityChange(), entityChanges[ 1 ] );
action.incEntityRemoveCount();
assertTrue( action.areEntityChangesPending() );
assertEquals( action.nextEntityChange(), entityChanges[ 2 ] );
action.incEntityUpdateCount();
action.changeProcessed( entities[ 2 ] );
assertFalse( action.areEntityChangesPending() );
assertNull( action.nextEntityChange() );
assertFalse( action.areEntityChangesPending() );
assertEquals( action.getEntityUpdateCount(), 2 );
assertEquals( action.getEntityRemoveCount(), 1 );
}
assertFalse( action.needsChannelChangesProcessed() );
assertFalse( action.areEntityChangesPending() );
assertTrue( action.areEntityLinksPending() );
assertFalse( action.hasWorldBeenValidated() );
// process links
{
assertEquals( action.nextEntityToLink(), entities[ 0 ] );
action.incEntityLinkCount();
assertNull( action.nextEntityToLink() );
assertEquals( action.getEntityLinkCount(), 1 );
}
assertFalse( action.areEntityLinksPending() );
assertFalse( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertFalse( action.hasWorldBeenValidated() );
action.markWorldAsValidated();
assertFalse( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertTrue( action.hasWorldBeenValidated() );
}
@Test
public void lifeCycleWithChannelUpdates()
{
// ChangeSet details
final int requestId = ValueUtil.randomInt();
// Channel updates
final String filter1 = ValueUtil.randomString();
final String filter2 = ValueUtil.randomString();
final ChannelChange channelChange1 = ChannelChange.create( "+42", filter1 );
final ChannelChange channelChange2 = ChannelChange.create( "=43.1", filter2 );
final ChannelChange[] channelChanges = new ChannelChange[]{ channelChange1, channelChange2 };
final EntityChange[] entityChanges = new EntityChange[ 0 ];
final ChangeSetMessage changeSet =
ChangeSetMessage.create( requestId, null, new String[]{ "-43.2" }, channelChanges, entityChanges );
final String requestKey = ValueUtil.randomString();
final RequestEntry request = new RequestEntry( requestId, requestKey, false );
final MessageResponse action = new MessageResponse( 1, changeSet, request );
assertEquals( action.getMessage(), changeSet );
assertEquals( action.getRequest(), request );
assertTrue( action.needsChannelChangesProcessed() );
assertFalse( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertFalse( action.hasWorldBeenValidated() );
// processed as single block in caller
action.markChannelActionsProcessed();
assertFalse( action.needsChannelChangesProcessed() );
assertFalse( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertFalse( action.hasWorldBeenValidated() );
action.markWorldAsValidated();
assertFalse( action.needsChannelChangesProcessed() );
assertFalse( action.areEntityChangesPending() );
assertFalse( action.areEntityLinksPending() );
assertTrue( action.hasWorldBeenValidated() );
}
@Test
public void setChangeSet_mismatchedRequestId()
{
final ChangeSetMessage changeSet =
ChangeSetMessage.create( 1234, null, null, null, null );
final RequestEntry request = new RequestEntry( 5678, ValueUtil.randomString(), false );
final IllegalStateException exception =
expectThrows( IllegalStateException.class, () -> new MessageResponse( 1, changeSet, request ) );
assertEquals( exception.getMessage(),
"Replicant-0011: Response message specified requestId '1234' but request specified requestId '5678'." );
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.internal.cache.tier.sockets;
import com.gemstone.gemfire.cache.EntryDestroyedException;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.client.ServerConnectivityException;
import dunit.DistributedTestCase;
import dunit.VM;
@SuppressWarnings({"rawtypes", "serial"})
public class HAInterestPart2DUnitTest extends HAInterestBaseTest {
public HAInterestPart2DUnitTest(String name) {
super(name);
}
/**
* Tests if Primary fails during interest un registration should initiate
* failover should pick new primary
*/
public void testPrimaryFailureInUNregisterInterest() throws Exception {
createClientPoolCache(this.getName(), getServerHostName(server1.getHost()));
createEntriesK1andK2();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server3.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
registerK1AndK2();
VM oldPrimary = getPrimaryVM();
stopPrimaryAndUnregisterRegisterK1();
verifyDeadAndLiveServers(1, 2);
VM newPrimary = getPrimaryVM(oldPrimary);
newPrimary.invoke(HAInterestBaseTest.class, "verifyDispatcherIsAlive");
// primary
newPrimary.invoke(HAInterestBaseTest.class, "verifyInterestUNRegistration");
// secondary
getBackupVM().invoke(HAInterestBaseTest.class, "verifyInterestUNRegistration");
}
/**
* Tests if Secondary fails during interest un registration should add to dead
* Ep list
*/
public void testSecondaryFailureInUNRegisterInterest() throws Exception {
createClientPoolCache(this.getName(), getServerHostName(server1.getHost()));
createEntriesK1andK2();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server3.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
registerK1AndK2();
VM stoppedBackup = stopSecondaryAndUNregisterK1();
verifyDeadAndLiveServers(1, 2);
// still primary
getPrimaryVM().invoke(HAInterestBaseTest.class, "verifyDispatcherIsAlive");
// primary
getPrimaryVM().invoke(HAInterestBaseTest.class, "verifyInterestUNRegistration");
// secondary
getBackupVM(stoppedBackup).invoke(HAInterestBaseTest.class, "verifyInterestUNRegistration");
}
/**
* Tests a scenario in which Dead Server Monitor detects Server Live Just
* before interest registration then interest should be registered on the newly
* detected live server as well
*/
public void testDSMDetectsServerLiveJustBeforeInterestRegistration() throws Exception {
createClientPoolCache(this.getName(), getServerHostName(server1.getHost()));
createEntriesK1andK2();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server3.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
VM backup = getBackupVM();
backup.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(1, 2);
setClientServerObserverForBeforeRegistration(backup);
try {
registerK1AndK2();
waitForBeforeRegistrationCallback();
} finally {
unSetClientServerObserverForRegistrationCallback();
}
server1.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
server2.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
server3.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
}
/**
* Tests a scenario in which Dead Server Monitor detects Server Live Just
* After interest registration then interest should be registered on the newly
* detected live server as well
*/
public void testDSMDetectsServerLiveJustAfterInterestRegistration() throws Exception {
createClientPoolCache(this.getName(), getServerHostName(server1.getHost()));
createEntriesK1andK2();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server3.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
VM backup = getBackupVM();
backup.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(1, 2);
setClientServerObserverForAfterRegistration(backup);
try {
registerK1AndK2();
waitForAfterRegistrationCallback();
} finally {
unSetClientServerObserverForRegistrationCallback();
}
server1.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
server2.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
server3.invoke(HAInterestBaseTest.class, "verifyInterestRegistration");
}
/**
* Tests a Scenario: Only one server, register interest on the server stop
* server , and update the registered entries on the server start the server ,
* DSM will recover interest list on this live server and verify that as a
* part of recovery it refreshes registered entries from the server, because it
* is primary
*/
public void testRefreshEntriesFromPrimaryWhenDSMDetectsServerLive() throws Exception {
addExpectedException(ServerConnectivityException.class.getName());
PORT1 = ((Integer) server1.invoke(HAInterestBaseTest.class, "createServerCache")).intValue();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
createClientPoolCacheConnectionToSingleServer(this.getName(), getServerHostName(server1.getHost()));
registerK1AndK2();
verifyRefreshedEntriesFromServer();
server1.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(1, 0);
server1.invoke(HAInterestBaseTest.class, "putK1andK2");
server1.invoke(HAInterestBaseTest.class, "startServer");
verifyDeadAndLiveServers(0, 1);
final Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
assertNotNull(r1);
WaitCriterion wc = new WaitCriterion() {
private String excuse;
@Override
public boolean done() {
Region.Entry e1;
Region.Entry e2;
try {
e1 = r1.getEntry(k1);
if (e1 == null) {
excuse = "Entry for k1 is null";
return false;
}
} catch (EntryDestroyedException e) {
excuse = "Entry destroyed";
return false;
}
if (!server_k1.equals(e1.getValue())) {
excuse = "e1 value is not server_k1";
return false;
}
try {
e2 = r1.getEntry(k2);
if (e2 == null) {
excuse = "Entry for k2 is null";
return false;
}
} catch (EntryDestroyedException e) {
excuse = "Entry destroyed";
return false;
}
if (!server_k2.equals(e2.getValue())) {
excuse = "e2 value is not server_k2";
return false;
}
return true;
}
@Override
public String description() {
return excuse;
}
};
DistributedTestCase.waitForCriterion(wc, TIMEOUT_MILLIS, INTERVAL_MILLIS, true);
}
/**
* Tests a Scenario: stop a secondary server and update the registered entries
* on the stopped server start the server , DSM will recover interest list on
* this live server and verify that as a part of recovery it does not
* refreshes registered entries from the server, because it is secondary
*/
public void testGIIFromSecondaryWhenDSMDetectsServerLive() throws Exception {
server1.invoke(HAInterestBaseTest.class, "closeCache");
server2.invoke(HAInterestBaseTest.class, "closeCache");
server3.invoke(HAInterestBaseTest.class, "closeCache");
PORT1 = ((Integer) server1.invoke(HAInterestBaseTest.class, "createServerCacheWithLocalRegion")).intValue();
PORT2 = ((Integer) server2.invoke(HAInterestBaseTest.class, "createServerCacheWithLocalRegion")).intValue();
PORT3 = ((Integer) server3.invoke(HAInterestBaseTest.class, "createServerCacheWithLocalRegion")).intValue();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
server3.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
createClientPoolCache(this.getName(), getServerHostName(server1.getHost()));
VM backup1 = getBackupVM();
VM backup2 = getBackupVM(backup1);
backup1.invoke(HAInterestBaseTest.class, "stopServer");
backup2.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(2, 1);
registerK1AndK2();
verifyRefreshedEntriesFromServer();
backup1.invoke(HAInterestBaseTest.class, "putK1andK2");
backup1.invoke(HAInterestBaseTest.class, "startServer");
verifyDeadAndLiveServers(1, 2);
verifyRefreshedEntriesFromServer();
}
/**
* Bug Test for Bug # 35945 A java level Deadlock between acquireConnection
* and RegionEntry during processRecoveredEndpoint by Dead Server Monitor
* Thread.
*
* @throws Exception
*/
public void testBug35945() throws Exception {
PORT1 = ((Integer) server1.invoke(HAInterestBaseTest.class, "createServerCache")).intValue();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
createClientPoolCacheConnectionToSingleServer(this.getName(), getServerHostName(server1.getHost()));
registerK1AndK2();
verifyRefreshedEntriesFromServer();
server1.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(1, 0);
// put on stopped server
server1.invoke(HAInterestBaseTest.class, "putK1andK2");
// spawn a thread to put on server , which will acquire a lock on entry
setClientServerObserverForBeforeInterestRecovery();
server1.invoke(HAInterestBaseTest.class, "startServer");
verifyDeadAndLiveServers(0, 1);
waitForBeforeInterestRecoveryCallBack();
// verify updated value of k1 as a refreshEntriesFromServer
final Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
assertNotNull(r1);
WaitCriterion wc = new WaitCriterion() {
private String excuse;
@Override
public boolean done() {
Region.Entry e1 = r1.getEntry(k1);
Region.Entry e2 = r1.getEntry(k2);
if (e1 == null || !server_k1_updated.equals(e1.getValue())) {
excuse = "k1=" + (e1 == null ? "null" : e1.getValue());
return false;
}
if (e2 == null || !server_k2.equals(e2.getValue())) {
excuse = "k2=" + (e2 == null ? "null" : e2.getValue());
return false;
}
return true;
}
@Override
public String description() {
return excuse;
}
};
DistributedTestCase.waitForCriterion(wc, TIMEOUT_MILLIS, INTERVAL_MILLIS, true);
}
/**
* Tests if failure occurred in Interest recovery thread, then it should select
* new endpoint to register interest
*/
public void testInterestRecoveryFailure() throws Exception {
addExpectedException("Server unreachable");
PORT1 = ((Integer) server1.invoke(HAInterestBaseTest.class, "createServerCache")).intValue();
server1.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
PORT2 = ((Integer) server2.invoke(HAInterestBaseTest.class, "createServerCache")).intValue();
server2.invoke(HAInterestBaseTest.class, "createEntriesK1andK2");
createClientPoolCacheWithSmallRetryInterval(this.getName(), getServerHostName(server1.getHost()));
registerK1AndK2();
verifyRefreshedEntriesFromServer();
VM backup = getBackupVM();
VM primary = getPrimaryVM();
backup.invoke(HAInterestBaseTest.class, "stopServer");
primary.invoke(HAInterestBaseTest.class, "stopServer");
verifyDeadAndLiveServers(2, 0);
primary.invoke(HAInterestBaseTest.class, "putK1andK2");
setClientServerObserverForBeforeInterestRecoveryFailure();
primary.invoke(HAInterestBaseTest.class, "startServer");
waitForBeforeInterestRecoveryCallBack();
if (exceptionOccured) {
fail("The DSM could not ensure that server 1 is started & serevr 2 is stopped");
}
final Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
assertNotNull(r1);
WaitCriterion wc = new WaitCriterion() {
private String excuse;
@Override
public boolean done() {
Region.Entry e1 = r1.getEntry(k1);
Region.Entry e2 = r1.getEntry(k2);
if (e1 == null) {
excuse = "Entry for k1 still null";
return false;
}
if (e2 == null) {
excuse = "Entry for k2 still null";
return false;
}
if (!(server_k1.equals(e1.getValue()))) {
excuse = "Value for k1 wrong";
return false;
}
if (!(server_k2.equals(e2.getValue()))) {
excuse = "Value for k2 wrong";
return false;
}
return true;
}
@Override
public String description() {
return excuse;
}
};
DistributedTestCase.waitForCriterion(wc, TIMEOUT_MILLIS, INTERVAL_MILLIS, true);
}
}
| |
/*
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package codetoanalyze.java.infer;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.lang.System;
import java.util.HashMap;
public class NullPointerExceptions {
class A {
int x;
public void method() {
}
}
// npe local with field
public int nullPointerException() {
A a = null;
return a.x;
}
public A canReturnNullObject(boolean ok) {
A a = new A();
if (ok)
return a;
else
return null;
}
public static void expectNotNullObjectParameter(A a) {
a.method();
}
public static void expectNotNullArrayParameter(A[] array) {
array.clone();
}
// npe with branching, interprocedural
public int nullPointerExceptionInterProc() {
A a = canReturnNullObject(false);
return a.x;
}
// npe with exception handling
public int nullPointerExceptionWithExceptionHandling(boolean ok) {
A a = null;
try {
throw new Exception();
} catch (Exception e) {
return a.x;
}
}
class B {
A a;
void test() {
}
}
public static int nullPointerExceptionWithArray() {
A[] array = new A[]{null};
A t = array[0];
return t.x;
}
// npe with a chain of fields
class C {
B b;
}
public int nullPointerExceptionWithAChainOfFields(C c) {
c.b = new B();
return c.b.a.x;
}
// npe with a null object parameter
public static void nullPointerExceptionWithNullObjectParameter() {
expectNotNullObjectParameter(null);
}
// npe with a null array parameter
public static void nullPointerExceptionWithNullArrayParameter() {
expectNotNullArrayParameter(null);
}
public static void nullPointerExceptionFromFaillingResourceConstructor() throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(new File("whatever.txt"));
} catch (IOException e) {
} finally {
fis.close();
}
}
public static void nullPointerExceptionFromFailingFileOutputStreamConstructor()
throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("whatever.txt"));
} catch (IOException e) {
} finally {
fos.close();
}
}
int x;
public void nullPointerExceptionFromNotKnowingThatThisIsNotNull() {
if (this == null) {
}
this.x = 4;
}
public <T> T id_generics(T o) {
o.toString();
return o;
}
public A frame(A x) {
return id_generics(x);
}
public void nullPointerExceptionUnlessFrameFails() {
String s = null;
Object a = frame(new A());
if (a instanceof A) {
s.length();
}
}
class D {
int x;
}
public int preconditionCheckStateTest(D d) {
Preconditions.checkState(d != null);
return d.x;
}
public void genericMethodSomewhereCheckingForNull(String s) {
if (s == null) {
}
}
public void noNullPointerExceptionAfterSkipFunction() {
String t = new String("Hello!");
String s = t.toString();
genericMethodSomewhereCheckingForNull(s);
s.length();
}
String hashmapNPE(HashMap h, Object o) {
return (h.get(o).toString());
}
String NPEhashmapProtectedByContainsKey(HashMap h, Object o) {
if (h.containsKey(o)) {
return (h.get(o).toString());
}
return "aa";
}
int NPEvalueOfFromHashmapBad(HashMap<Integer,Integer> h, int position) {
return h.get(position);
}
Integer NPEvalueOfFromHashmapGood(HashMap<Integer,Integer> h, int position) {
return h.get(position);
}
static void ReturnedValueOfImmutableListOf() {
ImmutableList<Object> l = ImmutableList.of();
if (l == null) {
l.toString();
}
}
void nullPointerExceptionInArrayLengthLoop(Object[] arr) {
for (int i = 0; i < arr.length; i++) {
Object x = null;
x.toString();
}
}
Context mContext;
ContentResolver mContentResolver;
public void cursorFromContentResolverNPE(String customClause) {
String[] projection = {"COUNT(*)"};
String selectionClause = selectionClause = customClause;
Cursor cursor = mContext.getContentResolver().query(
null,
projection,
selectionClause,
null,
null);
cursor.close();
}
public int cursorQueryShouldNotReturnNull(SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(
"events", null, null, null, null, null, null);
try {
return cursor.getCount();
} finally {
cursor.close();
}
}
Object[] arr = new Object[1];
Object arrayReadShouldNotCauseSymexMemoryError(int i) {
arr[i].toString();
return null;
}
void nullPointerExceptionCallArrayReadMethod() {
arr[0] = new Object();
arrayReadShouldNotCauseSymexMemoryError(0).toString();
}
public void sinkWithNeverNullSource() {
NeverNullSource source = new NeverNullSource();
T t = source.get();
t.f();
}
public void otherSinkWithNeverNullSource() {
SomeLibrary source = new SomeLibrary();
T t = source.get();
t.f();
}
private @Nullable Object mFld;
void nullableFieldNPE() {
mFld.toString();
}
void guardedNullableFieldDeref() {
if (mFld != null) mFld.toString();
}
void allocNullableFieldDeref() {
mFld = new Object();
mFld.toString();
}
void nullableParamNPE(@Nullable Object param) {
param.toString();
}
void guardedNullableParamDeref(@Nullable Object param) {
if (param != null) param.toString();
}
void allocNullableParamDeref(@Nullable Object param) {
param = new Object();
param.toString();
}
native boolean test();
Object getObj() {
if (test()) {
return new Object();
} else {
return null;
}
}
Boolean getBool() {
if (test()) {
return new Boolean(true);
} else {
return null;
}
}
void derefGetterAfterCheckShouldNotCauseNPE() {
if (getObj() != null) {
getObj().toString();
}
}
void derefBoxedGetterAfterCheckShouldNotCauseNPE() {
boolean b = getBool() != null && getBool();
}
static void derefNonThisGetterAfterCheckShouldNotCauseNPE() {
NullPointerExceptions c = new NullPointerExceptions();
if (c.getObj() != null) {
c.getObj().toString();
}
}
void badCheckShouldCauseNPE() {
if (getBool() != null) getObj().toString();
}
void nullPointerExceptionArrayLength() {
Object[] arr = null;
int i = arr.length;
}
class $$Class$Name$With$Dollars {
void npeWithDollars() {
String s = null;
int n = s.length();
}
}
void nullableNonNullStringAfterTextUtilsIsEmptyCheckShouldNotCauseNPE(@Nullable String str) {
if (!TextUtils.isEmpty(str)) {
str.length();
}
}
void someNPEAfterResourceLeak() {
T t = CloseableAsResourceExample.sourceOfNullWithResourceLeak();
t.f();
}
private Object mOkObj = new Object();
public void nullableParamReassign1(@Nullable Object o) {
if (o == null) {
o = mOkObj;
}
o.toString();
}
public void nullableParamReassign2(@Nullable Object o, Object okObj) {
if (o == null) {
o = okObj;
}
o.toString();
}
private @Nullable Object mNullableField;
public void nullableFieldReassign1() {
if (mNullableField == null) {
mNullableField = mOkObj;
}
mNullableField.toString();
}
public void nullableFieldReassign2(Object okObj) {
if (mNullableField == null) {
mNullableField = okObj;
}
mNullableField.toString();
}
public void nullableFieldReassign3(Object param) {
mNullableField = param;
mNullableField.toString();
}
public Object nullableGetter() {
return mNullableField;
}
public void derefNullableGetter() {
Object o = nullableGetter();
o.toString();
}
public @Nullable String testSystemGetPropertyArgument() {
String s = System.getProperty(null);
return s;
}
public void testSystemGetPropertyReturn() {
String s = System.getProperty("");
int n = s.length();
}
Object retUndefined() {
return "".toString(); // toString is a skip function
}
Object derefUndefinedCallee() {
// if retUndefined() is handled incorrectly, we get a symexec_memory_error here
retUndefined().toString();
return null;
}
void derefNull() {
// should be NPE, but will not be reported if we handled retUndefined() incorrectly
derefUndefinedCallee().toString();
}
@SuppressWarnings("null") // TODO(#8647398): Add support for @SuppressWarnings with Ant
void shouldNotReportNPE() {
Object o = null;
o.toString();
}
void shouldNotReportOnSkippedSource() {
Object o = SkippedSourceFile.createdBySkippedFile();
o.toString();
}
int nullListFiles(String pathname) {
File dir = new File(pathname);
File[] files = dir.listFiles();
return files.length; // expect possible NullPointerException as files == null is possible
}
native Object unknownFunc();
Object callUnknownFunc() {
return unknownFunc();
}
void dontReportOnNullableDirectReassignmentToUnknown(@Nullable Object o) {
o = unknownFunc();
o.toString();
}
void dontReportOnNullableIndirectReassignmentToUnknown(@Nullable Object o) {
o = callUnknownFunc();
o.toString();
}
String nullTryLock(FileChannel chan) throws IOException {
FileLock lock = chan.tryLock();
return lock.toString(); // expect possible NullPointerException as lock == null is possible
}
String tryLockThrows(FileChannel chan) {
try {
FileLock lock = chan.tryLock();
return (lock != null ? lock.toString() : "");
} catch (IOException e) {
Object o = null;
return o.toString(); // expect NullPointerException as tryLock can throw
}
}
class L {
L next;
}
Object returnsNullAfterLoopOnList(L l) {
while (l != null) {
l = l.next;
}
return null;
}
void dereferenceAfterLoopOnList(L l) {
Object obj = returnsNullAfterLoopOnList(l);
obj.toString();
}
}
| |
package org.jfrog.hudson.util;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import hudson.model.*;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jfrog.build.api.util.NullLog;
import org.jfrog.build.client.ProxyConfiguration;
import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBaseClient;
import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient;
import org.jfrog.hudson.*;
import java.io.IOException;
import java.util.List;
/**
* @author Shay Yaakov
*/
public abstract class RepositoriesUtils {
public static List<String> getReleaseRepositoryKeysFirst(DeployerOverrider deployer, ArtifactoryServer server) throws IOException {
if (server == null) {
return Lists.newArrayList();
}
return server.getReleaseRepositoryKeysFirst(deployer, null);
}
public static List<String> getSnapshotRepositoryKeysFirst(DeployerOverrider deployer, ArtifactoryServer server) throws IOException {
if (server == null) {
return Lists.newArrayList();
}
return server.getSnapshotRepositoryKeysFirst(deployer, null);
}
public static List<VirtualRepository> getVirtualRepositoryKeys(ResolverOverrider resolverOverrider,
DeployerOverrider deployerOverrider,
ArtifactoryServer server) {
if (server == null) {
return Lists.newArrayList();
}
return server.getVirtualRepositoryKeys(resolverOverrider, null);
}
public static List<VirtualRepository> generateVirtualRepos(ArtifactoryBuildInfoClient client) throws IOException {
List<VirtualRepository> virtualRepositories;
List<String> keys = client.getVirtualRepositoryKeys();
virtualRepositories = Lists.newArrayList(Lists.transform(keys, new Function<String, VirtualRepository>() {
public VirtualRepository apply(String from) {
return new VirtualRepository(from, from);
}
}));
return virtualRepositories;
}
public static List<VirtualRepository> getVirtualRepositoryKeys(String url, CredentialsConfig credentialsConfig,
ArtifactoryServer artifactoryServer, Item item)
throws IOException {
List<VirtualRepository> virtualRepositories;
CredentialsConfig preferredResolver = CredentialManager.getPreferredResolver(credentialsConfig, artifactoryServer);
ArtifactoryBuildInfoClient client;
if (StringUtils.isNotBlank(preferredResolver.provideUsername(item))) {
client = new ArtifactoryBuildInfoClient(url, preferredResolver.provideUsername(item),
preferredResolver.providePassword(item), new NullLog());
} else {
client = new ArtifactoryBuildInfoClient(url, new NullLog());
}
try {
client.setConnectionTimeout(artifactoryServer.getTimeout());
setRetryParams(artifactoryServer, client);
if (Jenkins.getInstance().proxy != null && !artifactoryServer.isBypassProxy()) {
client.setProxyConfiguration(createProxyConfiguration(Jenkins.getInstance().proxy));
}
virtualRepositories = RepositoriesUtils.generateVirtualRepos(client);
return virtualRepositories;
} finally {
client.close();
}
}
public static List<String> getLocalRepositories(String url, CredentialsConfig credentialsConfig,
ArtifactoryServer artifactoryServer, Item item) throws IOException {
List<String> localRepository;
CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(credentialsConfig, artifactoryServer);
ArtifactoryBuildInfoClient client;
if (StringUtils.isNotBlank(preferredDeployer.provideUsername(item))) {
client = new ArtifactoryBuildInfoClient(url, preferredDeployer.provideUsername(item),
preferredDeployer.providePassword(item), new NullLog());
} else {
client = new ArtifactoryBuildInfoClient(url, new NullLog());
}
try {
client.setConnectionTimeout(artifactoryServer.getTimeout());
setRetryParams(artifactoryServer, client);
if (Jenkins.getInstance().proxy != null && !artifactoryServer.isBypassProxy()) {
client.setProxyConfiguration(createProxyConfiguration(Jenkins.getInstance().proxy));
}
localRepository = client.getLocalRepositoriesKeys();
return localRepository;
} finally {
client.close();
}
}
public static ProxyConfiguration createProxyConfiguration(hudson.ProxyConfiguration proxy) {
ProxyConfiguration proxyConfiguration = null;
if (proxy != null) {
proxyConfiguration = new ProxyConfiguration();
proxyConfiguration.host = proxy.name;
proxyConfiguration.port = proxy.port;
proxyConfiguration.username = proxy.getUserName();
proxyConfiguration.password = proxy.getPassword();
}
return proxyConfiguration;
}
public static ArtifactoryServer getArtifactoryServer(String artifactoryIdentity, List<ArtifactoryServer> artifactoryServers) {
if (artifactoryServers != null) {
for (ArtifactoryServer server : artifactoryServers) {
if (server.getUrl().equals(artifactoryIdentity) || server.getName().equals(artifactoryIdentity)) {
return server;
}
}
}
return null;
}
/**
* Returns the list of {@link org.jfrog.hudson.ArtifactoryServer} configured.
*
* @return can be empty but never null.
*/
public static List<ArtifactoryServer> getArtifactoryServers() {
ArtifactoryBuilder.DescriptorImpl descriptor = (ArtifactoryBuilder.DescriptorImpl)
Hudson.getInstance().getDescriptor(ArtifactoryBuilder.class);
return descriptor.getArtifactoryServers();
}
public static List<Repository> createRepositoriesList(List<String> repositoriesValueList) {
List<Repository> repositories = Lists.newArrayList();
for (String repositoryKey : repositoriesValueList) {
Repository repository = new Repository(repositoryKey);
repositories.add(repository);
}
return repositories;
}
public static List<VirtualRepository> collectVirtualRepositories(List<VirtualRepository> repositories, String repoKey) {
if (repositories == null) {
repositories = Lists.newArrayList();
}
if (StringUtils.isNotBlank(repoKey)) {
for (VirtualRepository vr : repositories) {
if (repoKey.equals(vr.getDisplayName())) {
return repositories;
}
}
VirtualRepository vr = new VirtualRepository(repoKey, repoKey);
repositories.add(vr);
}
return repositories;
}
public static List<Repository> collectRepositories(String repoKey) {
List<Repository> repositories = Lists.newArrayList();
if (StringUtils.isNotBlank(repoKey)) {
Repository r = new Repository(repoKey);
repositories.add(r);
}
return repositories;
}
public static void validateServerConfig(AbstractBuild build, BuildListener listener,
ArtifactoryServer artifactoryServer, String artifactoryUrl) throws IOException {
if (artifactoryServer == null) {
String error = "No Artifactory server configured for " + artifactoryUrl +
". Please check your configuration.";
listener.getLogger().println(error);
build.setResult(Result.FAILURE);
throw new IOException(error);
}
}
private static void setRetryParams(ArtifactoryServer artifactoryServer, ArtifactoryBuildInfoClient client) {
setRetryParams(artifactoryServer.getConnectionRetry(), client);
}
/**
* Sets the params of the retry mechanism
*
* @param connectionRetry - The max number of retries configured
* @param client - The client to set the values
*/
public static void setRetryParams(int connectionRetry, ArtifactoryBaseClient client) {
client.setConnectionRetries(connectionRetry);
}
}
| |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kms.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
*/
public class CreateKeyRequest extends AmazonWebServiceRequest implements
Serializable, Cloneable {
/**
* <p>
* Policy to attach to the key. This is required and delegates back to the
* account. The key is the root of trust. The policy size limit is 32 KiB
* (32768 bytes).
* </p>
*/
private String policy;
/**
* <p>
* Description of the key. We recommend that you choose a description that
* helps your customer decide whether the key is appropriate for a task.
* </p>
*/
private String description;
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*/
private String keyUsage;
/**
* <p>
* Policy to attach to the key. This is required and delegates back to the
* account. The key is the root of trust. The policy size limit is 32 KiB
* (32768 bytes).
* </p>
*
* @param policy
* Policy to attach to the key. This is required and delegates back
* to the account. The key is the root of trust. The policy size
* limit is 32 KiB (32768 bytes).
*/
public void setPolicy(String policy) {
this.policy = policy;
}
/**
* <p>
* Policy to attach to the key. This is required and delegates back to the
* account. The key is the root of trust. The policy size limit is 32 KiB
* (32768 bytes).
* </p>
*
* @return Policy to attach to the key. This is required and delegates back
* to the account. The key is the root of trust. The policy size
* limit is 32 KiB (32768 bytes).
*/
public String getPolicy() {
return this.policy;
}
/**
* <p>
* Policy to attach to the key. This is required and delegates back to the
* account. The key is the root of trust. The policy size limit is 32 KiB
* (32768 bytes).
* </p>
*
* @param policy
* Policy to attach to the key. This is required and delegates back
* to the account. The key is the root of trust. The policy size
* limit is 32 KiB (32768 bytes).
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateKeyRequest withPolicy(String policy) {
setPolicy(policy);
return this;
}
/**
* <p>
* Description of the key. We recommend that you choose a description that
* helps your customer decide whether the key is appropriate for a task.
* </p>
*
* @param description
* Description of the key. We recommend that you choose a description
* that helps your customer decide whether the key is appropriate for
* a task.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* Description of the key. We recommend that you choose a description that
* helps your customer decide whether the key is appropriate for a task.
* </p>
*
* @return Description of the key. We recommend that you choose a
* description that helps your customer decide whether the key is
* appropriate for a task.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* Description of the key. We recommend that you choose a description that
* helps your customer decide whether the key is appropriate for a task.
* </p>
*
* @param description
* Description of the key. We recommend that you choose a description
* that helps your customer decide whether the key is appropriate for
* a task.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateKeyRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*
* @param keyUsage
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* @see KeyUsageType
*/
public void setKeyUsage(String keyUsage) {
this.keyUsage = keyUsage;
}
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*
* @return Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* @see KeyUsageType
*/
public String getKeyUsage() {
return this.keyUsage;
}
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*
* @param keyUsage
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see KeyUsageType
*/
public CreateKeyRequest withKeyUsage(String keyUsage) {
setKeyUsage(keyUsage);
return this;
}
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*
* @param keyUsage
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see KeyUsageType
*/
public void setKeyUsage(KeyUsageType keyUsage) {
this.keyUsage = keyUsage.toString();
}
/**
* <p>
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* </p>
*
* @param keyUsage
* Specifies the intended use of the key. Currently this defaults to
* ENCRYPT/DECRYPT, and only symmetric encryption and decryption are
* supported.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see KeyUsageType
*/
public CreateKeyRequest withKeyUsage(KeyUsageType keyUsage) {
setKeyUsage(keyUsage);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getPolicy() != null)
sb.append("Policy: " + getPolicy() + ",");
if (getDescription() != null)
sb.append("Description: " + getDescription() + ",");
if (getKeyUsage() != null)
sb.append("KeyUsage: " + getKeyUsage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateKeyRequest == false)
return false;
CreateKeyRequest other = (CreateKeyRequest) obj;
if (other.getPolicy() == null ^ this.getPolicy() == null)
return false;
if (other.getPolicy() != null
&& other.getPolicy().equals(this.getPolicy()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null
&& other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getKeyUsage() == null ^ this.getKeyUsage() == null)
return false;
if (other.getKeyUsage() != null
&& other.getKeyUsage().equals(this.getKeyUsage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getPolicy() == null) ? 0 : getPolicy().hashCode());
hashCode = prime
* hashCode
+ ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode
+ ((getKeyUsage() == null) ? 0 : getKeyUsage().hashCode());
return hashCode;
}
@Override
public CreateKeyRequest clone() {
return (CreateKeyRequest) super.clone();
}
}
| |
// Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.vlib.pages;
import java.rmi.RemoteException;
import java.util.List;
import javax.ejb.FinderException;
import org.apache.tapestry.ApplicationRuntimeException;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.PageRedirectException;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageRenderListener;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.vlib.EntitySelectionModel;
import org.apache.tapestry.vlib.IActivate;
import org.apache.tapestry.vlib.Protected;
import org.apache.tapestry.vlib.VirtualLibraryEngine;
import org.apache.tapestry.vlib.Visit;
import org.apache.tapestry.vlib.ejb.Book;
import org.apache.tapestry.vlib.ejb.IBookQuery;
import org.apache.tapestry.vlib.ejb.IOperations;
import org.apache.tapestry.vlib.ejb.Person;
/**
* Used to manage giving away of books to other users.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 3.0
*
**/
public abstract class GiveAwayBooks extends Protected implements PageRenderListener
{
public abstract IPropertySelectionModel getBooksModel();
public abstract void setBooksModel(IPropertySelectionModel booksModel);
public abstract IPropertySelectionModel getPersonModel();
public abstract void setPersonModel(IPropertySelectionModel personModel);
public abstract List getSelectedBooks();
public abstract Integer getTargetUserId();
public void formSubmit(IRequestCycle cycle)
{
VirtualLibraryEngine vengine = (VirtualLibraryEngine) getEngine();
Integer targetUserId = getTargetUserId();
Person target = vengine.readPerson(targetUserId);
List selectedBooks = getSelectedBooks();
int count = Tapestry.size(selectedBooks);
if (count == 0)
{
setError(format("select-at-least-one-book", target.getNaturalName()));
return;
}
Integer[] bookIds = (Integer[]) selectedBooks.toArray(new Integer[count]);
int i = 0;
while (true)
{
IOperations operations = vengine.getOperations();
try
{
operations.transferBooks(targetUserId, bookIds);
break;
}
catch (FinderException ex)
{
throw new ApplicationRuntimeException(ex);
}
catch (RemoteException ex)
{
vengine.rmiFailure(getMessage("update-failure"), ex, i++);
}
}
MyLibrary myLibrary = (MyLibrary) cycle.getPage("MyLibrary");
myLibrary.setMessage(
format("transfered-books", Integer.toString(count), target.getNaturalName()));
myLibrary.activate(cycle);
}
private IPropertySelectionModel buildPersonModel()
{
VirtualLibraryEngine vengine = (VirtualLibraryEngine) getEngine();
Visit visit = (Visit) vengine.getVisit();
Integer userPK = visit.getUserId();
Person[] persons = null;
int i = 0;
while (true)
{
IOperations operations = vengine.getOperations();
try
{
persons = operations.getPersons();
break;
}
catch (RemoteException ex)
{
vengine.rmiFailure(getMessage("read-users-failure"), ex, i++);
}
}
EntitySelectionModel result = new EntitySelectionModel();
for (i = 0; i < persons.length; i++)
{
Person p = persons[i];
Integer pk = p.getId();
if (pk.equals(userPK))
continue;
result.add(pk, p.getNaturalName());
}
return result;
}
public void pageBeginRender(PageEvent event)
{
IPropertySelectionModel model = getBooksModel();
if (model == null)
{
model = buildBooksModel();
setBooksModel(model);
}
model = getPersonModel();
if (model == null)
{
model = buildPersonModel();
setPersonModel(model);
}
}
private IPropertySelectionModel buildBooksModel()
{
VirtualLibraryEngine vengine = (VirtualLibraryEngine) getEngine();
Visit visit = (Visit) vengine.getVisit();
Integer userPK = visit.getUserId();
Book[] books = null;
int i = 0;
while (true)
{
books = null;
try
{
IBookQuery query = vengine.createNewQuery();
int count = query.ownerQuery(userPK, null);
if (count > 0)
books = query.get(0, count);
break;
}
catch (RemoteException ex)
{
vengine.rmiFailure(getMessage("read-books-failure"), ex, i++);
}
}
EntitySelectionModel result = new EntitySelectionModel();
if (books != null)
for (i = 0; i < books.length; i++)
result.add(books[i].getId(), books[i].getTitle());
return result;
}
public void pageValidate(PageEvent event)
{
super.pageValidate(event);
IPropertySelectionModel model = buildBooksModel();
if (model.getOptionCount() == 0)
{
IRequestCycle cycle = getRequestCycle();
IActivate page = (IActivate) cycle.getPage("MyLibrary");
page.activate(cycle);
throw new PageRedirectException(page);
}
setBooksModel(model);
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.iterative.rule;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import io.prestosql.Session;
import io.prestosql.execution.Lifespan;
import io.prestosql.geospatial.KdbTree;
import io.prestosql.geospatial.KdbTreeUtils;
import io.prestosql.matching.Capture;
import io.prestosql.matching.Captures;
import io.prestosql.matching.Pattern;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.QualifiedObjectName;
import io.prestosql.metadata.Split;
import io.prestosql.metadata.TableHandle;
import io.prestosql.spi.Page;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ConnectorPageSource;
import io.prestosql.spi.type.ArrayType;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.TypeSignature;
import io.prestosql.split.PageSourceManager;
import io.prestosql.split.SplitManager;
import io.prestosql.split.SplitSource;
import io.prestosql.split.SplitSource.SplitBatch;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.TypeAnalyzer;
import io.prestosql.sql.planner.iterative.Rule;
import io.prestosql.sql.planner.iterative.Rule.Context;
import io.prestosql.sql.planner.iterative.Rule.Result;
import io.prestosql.sql.planner.plan.Assignments;
import io.prestosql.sql.planner.plan.FilterNode;
import io.prestosql.sql.planner.plan.JoinNode;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.plan.PlanNodeId;
import io.prestosql.sql.planner.plan.ProjectNode;
import io.prestosql.sql.planner.plan.SpatialJoinNode;
import io.prestosql.sql.planner.plan.UnnestNode;
import io.prestosql.sql.tree.Cast;
import io.prestosql.sql.tree.ComparisonExpression;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.FunctionCall;
import io.prestosql.sql.tree.QualifiedName;
import io.prestosql.sql.tree.StringLiteral;
import io.prestosql.sql.tree.SymbolReference;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
import static io.prestosql.SystemSessionProperties.getSpatialPartitioningTableName;
import static io.prestosql.SystemSessionProperties.isSpatialJoinEnabled;
import static io.prestosql.matching.Capture.newCapture;
import static io.prestosql.spi.StandardErrorCode.INVALID_SPATIAL_PARTITIONING;
import static io.prestosql.spi.connector.ConnectorSplitManager.SplitSchedulingStrategy.UNGROUPED_SCHEDULING;
import static io.prestosql.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.TypeSignature.parseTypeSignature;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.sql.planner.ExpressionNodeInliner.replaceExpression;
import static io.prestosql.sql.planner.SymbolsExtractor.extractUnique;
import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER;
import static io.prestosql.sql.planner.plan.JoinNode.Type.LEFT;
import static io.prestosql.sql.planner.plan.Patterns.filter;
import static io.prestosql.sql.planner.plan.Patterns.join;
import static io.prestosql.sql.planner.plan.Patterns.source;
import static io.prestosql.sql.tree.ComparisonExpression.Operator.LESS_THAN;
import static io.prestosql.sql.tree.ComparisonExpression.Operator.LESS_THAN_OR_EQUAL;
import static io.prestosql.util.SpatialJoinUtils.extractSupportedSpatialComparisons;
import static io.prestosql.util.SpatialJoinUtils.extractSupportedSpatialFunctions;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
/**
* Applies to broadcast spatial joins, inner and left, expressed via ST_Contains,
* ST_Intersects and ST_Distance functions.
* <p>
* For example:
* <ul>
* <li>SELECT ... FROM a, b WHERE ST_Contains(b.geometry, a.geometry)</li>
* <li>SELECT ... FROM a, b WHERE ST_Intersects(b.geometry, a.geometry)</li>
* <li>SELECT ... FROM a, b WHERE ST_Distance(b.geometry, a.geometry) <= 300</li>
* <li>SELECT ... FROM a, b WHERE 15.5 > ST_Distance(b.geometry, a.geometry)</li>
* </ul>
* <p>
* Joins expressed via ST_Contains and ST_Intersects functions must match all of
* the following criteria:
* <p>
* - arguments of the spatial function are non-scalar expressions;
* - one of the arguments uses symbols from left side of the join, the other from right.
* <p>
* Joins expressed via ST_Distance function must use less than or less than or equals operator
* to compare ST_Distance value with a radius and must match all of the following criteria:
* <p>
* - arguments of the spatial function are non-scalar expressions;
* - one of the arguments uses symbols from left side of the join, the other from right;
* - radius is either scalar expression or uses symbols only from the right (build) side of the join.
* <p>
* For inner join, replaces cross join node and a qualifying filter on top with a single
* spatial join node.
* <p>
* For both inner and left joins, pushes non-trivial expressions of the spatial function
* arguments and radius into projections on top of join child nodes.
* <p>
* Examples:
* <pre>
* Point-in-polygon inner join
* ST_Contains(ST_GeometryFromText(a.wkt), ST_Point(b.longitude, b.latitude))
* becomes a spatial join
* ST_Contains(st_geometryfromtext, st_point)
* with st_geometryfromtext -> 'ST_GeometryFromText(a.wkt)' and
* st_point -> 'ST_Point(b.longitude, b.latitude)' projections on top of child nodes.
*
* Distance query
* ST_Distance(ST_Point(a.lon, a.lat), ST_Point(b.lon, b.lat)) <= 10 / (111.321 * cos(radians(b.lat)))
* becomes a spatial join
* ST_Distance(st_point_a, st_point_b) <= radius
* with st_point_a -> 'ST_Point(a.lon, a.lat)', st_point_b -> 'ST_Point(b.lon, b.lat)'
* and radius -> '10 / (111.321 * cos(radians(b.lat)))' projections on top of child nodes.
* </pre>
*/
public class ExtractSpatialJoins
{
private static final TypeSignature GEOMETRY_TYPE_SIGNATURE = parseTypeSignature("Geometry");
private static final TypeSignature SPHERICAL_GEOGRAPHY_TYPE_SIGNATURE = parseTypeSignature("SphericalGeography");
private static final String KDB_TREE_TYPENAME = "KdbTree";
private final Metadata metadata;
private final SplitManager splitManager;
private final PageSourceManager pageSourceManager;
private final TypeAnalyzer typeAnalyzer;
public ExtractSpatialJoins(Metadata metadata, SplitManager splitManager, PageSourceManager pageSourceManager, TypeAnalyzer typeAnalyzer)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.splitManager = requireNonNull(splitManager, "splitManager is null");
this.pageSourceManager = requireNonNull(pageSourceManager, "pageSourceManager is null");
this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null");
}
public Set<Rule<?>> rules()
{
return ImmutableSet.of(
new ExtractSpatialInnerJoin(metadata, splitManager, pageSourceManager, typeAnalyzer),
new ExtractSpatialLeftJoin(metadata, splitManager, pageSourceManager, typeAnalyzer));
}
@VisibleForTesting
public static final class ExtractSpatialInnerJoin
implements Rule<FilterNode>
{
private static final Capture<JoinNode> JOIN = newCapture();
private static final Pattern<FilterNode> PATTERN = filter()
.with(source().matching(join().capturedAs(JOIN).matching(JoinNode::isCrossJoin)));
private final Metadata metadata;
private final SplitManager splitManager;
private final PageSourceManager pageSourceManager;
private final TypeAnalyzer typeAnalyzer;
public ExtractSpatialInnerJoin(Metadata metadata, SplitManager splitManager, PageSourceManager pageSourceManager, TypeAnalyzer typeAnalyzer)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.splitManager = requireNonNull(splitManager, "splitManager is null");
this.pageSourceManager = requireNonNull(pageSourceManager, "pageSourceManager is null");
this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null");
}
@Override
public boolean isEnabled(Session session)
{
return isSpatialJoinEnabled(session);
}
@Override
public Pattern<FilterNode> getPattern()
{
return PATTERN;
}
@Override
public Result apply(FilterNode node, Captures captures, Context context)
{
JoinNode joinNode = captures.get(JOIN);
Expression filter = node.getPredicate();
List<FunctionCall> spatialFunctions = extractSupportedSpatialFunctions(filter);
for (FunctionCall spatialFunction : spatialFunctions) {
Result result = tryCreateSpatialJoin(context, joinNode, filter, node.getId(), node.getOutputSymbols(), spatialFunction, Optional.empty(), metadata, splitManager, pageSourceManager, typeAnalyzer);
if (!result.isEmpty()) {
return result;
}
}
List<ComparisonExpression> spatialComparisons = extractSupportedSpatialComparisons(filter);
for (ComparisonExpression spatialComparison : spatialComparisons) {
Result result = tryCreateSpatialJoin(context, joinNode, filter, node.getId(), node.getOutputSymbols(), spatialComparison, metadata, splitManager, pageSourceManager, typeAnalyzer);
if (!result.isEmpty()) {
return result;
}
}
return Result.empty();
}
}
@VisibleForTesting
public static final class ExtractSpatialLeftJoin
implements Rule<JoinNode>
{
private static final Pattern<JoinNode> PATTERN = join().matching(node -> node.getCriteria().isEmpty() && node.getFilter().isPresent() && node.getType() == LEFT);
private final Metadata metadata;
private final SplitManager splitManager;
private final PageSourceManager pageSourceManager;
private final TypeAnalyzer typeAnalyzer;
public ExtractSpatialLeftJoin(Metadata metadata, SplitManager splitManager, PageSourceManager pageSourceManager, TypeAnalyzer typeAnalyzer)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.splitManager = requireNonNull(splitManager, "splitManager is null");
this.pageSourceManager = requireNonNull(pageSourceManager, "pageSourceManager is null");
this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null");
}
@Override
public boolean isEnabled(Session session)
{
return isSpatialJoinEnabled(session);
}
@Override
public Pattern<JoinNode> getPattern()
{
return PATTERN;
}
@Override
public Result apply(JoinNode joinNode, Captures captures, Context context)
{
Expression filter = joinNode.getFilter().get();
List<FunctionCall> spatialFunctions = extractSupportedSpatialFunctions(filter);
for (FunctionCall spatialFunction : spatialFunctions) {
Result result = tryCreateSpatialJoin(context, joinNode, filter, joinNode.getId(), joinNode.getOutputSymbols(), spatialFunction, Optional.empty(), metadata, splitManager, pageSourceManager, typeAnalyzer);
if (!result.isEmpty()) {
return result;
}
}
List<ComparisonExpression> spatialComparisons = extractSupportedSpatialComparisons(filter);
for (ComparisonExpression spatialComparison : spatialComparisons) {
Result result = tryCreateSpatialJoin(context, joinNode, filter, joinNode.getId(), joinNode.getOutputSymbols(), spatialComparison, metadata, splitManager, pageSourceManager, typeAnalyzer);
if (!result.isEmpty()) {
return result;
}
}
return Result.empty();
}
}
private static Result tryCreateSpatialJoin(
Context context,
JoinNode joinNode,
Expression filter,
PlanNodeId nodeId,
List<Symbol> outputSymbols,
ComparisonExpression spatialComparison,
Metadata metadata,
SplitManager splitManager,
PageSourceManager pageSourceManager,
TypeAnalyzer typeAnalyzer)
{
PlanNode leftNode = joinNode.getLeft();
PlanNode rightNode = joinNode.getRight();
List<Symbol> leftSymbols = leftNode.getOutputSymbols();
List<Symbol> rightSymbols = rightNode.getOutputSymbols();
Expression radius;
Optional<Symbol> newRadiusSymbol;
ComparisonExpression newComparison;
if (spatialComparison.getOperator() == LESS_THAN || spatialComparison.getOperator() == LESS_THAN_OR_EQUAL) {
// ST_Distance(a, b) <= r
radius = spatialComparison.getRight();
Set<Symbol> radiusSymbols = extractUnique(radius);
if (radiusSymbols.isEmpty() || (rightSymbols.containsAll(radiusSymbols) && containsNone(leftSymbols, radiusSymbols))) {
newRadiusSymbol = newRadiusSymbol(context, radius);
newComparison = new ComparisonExpression(spatialComparison.getOperator(), spatialComparison.getLeft(), toExpression(newRadiusSymbol, radius));
}
else {
return Result.empty();
}
}
else {
// r >= ST_Distance(a, b)
radius = spatialComparison.getLeft();
Set<Symbol> radiusSymbols = extractUnique(radius);
if (radiusSymbols.isEmpty() || (rightSymbols.containsAll(radiusSymbols) && containsNone(leftSymbols, radiusSymbols))) {
newRadiusSymbol = newRadiusSymbol(context, radius);
newComparison = new ComparisonExpression(spatialComparison.getOperator().flip(), spatialComparison.getRight(), toExpression(newRadiusSymbol, radius));
}
else {
return Result.empty();
}
}
Expression newFilter = replaceExpression(filter, ImmutableMap.of(spatialComparison, newComparison));
PlanNode newRightNode = newRadiusSymbol.map(symbol -> addProjection(context, rightNode, symbol, radius)).orElse(rightNode);
JoinNode newJoinNode = new JoinNode(
joinNode.getId(),
joinNode.getType(),
leftNode,
newRightNode,
joinNode.getCriteria(),
joinNode.getOutputSymbols(),
Optional.of(newFilter),
joinNode.getLeftHashSymbol(),
joinNode.getRightHashSymbol(),
joinNode.getDistributionType(),
joinNode.isSpillable());
return tryCreateSpatialJoin(context, newJoinNode, newFilter, nodeId, outputSymbols, (FunctionCall) newComparison.getLeft(), Optional.of(newComparison.getRight()), metadata, splitManager, pageSourceManager, typeAnalyzer);
}
private static Result tryCreateSpatialJoin(
Context context,
JoinNode joinNode,
Expression filter,
PlanNodeId nodeId,
List<Symbol> outputSymbols,
FunctionCall spatialFunction,
Optional<Expression> radius,
Metadata metadata,
SplitManager splitManager,
PageSourceManager pageSourceManager,
TypeAnalyzer typeAnalyzer)
{
// TODO Add support for distributed left spatial joins
Optional<String> spatialPartitioningTableName = joinNode.getType() == INNER ? getSpatialPartitioningTableName(context.getSession()) : Optional.empty();
Optional<KdbTree> kdbTree = spatialPartitioningTableName.map(tableName -> loadKdbTree(tableName, context.getSession(), metadata, splitManager, pageSourceManager));
List<Expression> arguments = spatialFunction.getArguments();
verify(arguments.size() == 2);
Expression firstArgument = arguments.get(0);
Expression secondArgument = arguments.get(1);
Type sphericalGeographyType = metadata.getType(SPHERICAL_GEOGRAPHY_TYPE_SIGNATURE);
if (typeAnalyzer.getType(context.getSession(), context.getSymbolAllocator().getTypes(), firstArgument).equals(sphericalGeographyType)
|| typeAnalyzer.getType(context.getSession(), context.getSymbolAllocator().getTypes(), secondArgument).equals(sphericalGeographyType)) {
return Result.empty();
}
Set<Symbol> firstSymbols = extractUnique(firstArgument);
Set<Symbol> secondSymbols = extractUnique(secondArgument);
if (firstSymbols.isEmpty() || secondSymbols.isEmpty()) {
return Result.empty();
}
Optional<Symbol> newFirstSymbol = newGeometrySymbol(context, firstArgument, metadata);
Optional<Symbol> newSecondSymbol = newGeometrySymbol(context, secondArgument, metadata);
PlanNode leftNode = joinNode.getLeft();
PlanNode rightNode = joinNode.getRight();
PlanNode newLeftNode;
PlanNode newRightNode;
// Check if the order of arguments of the spatial function matches the order of join sides
int alignment = checkAlignment(joinNode, firstSymbols, secondSymbols);
if (alignment > 0) {
newLeftNode = newFirstSymbol.map(symbol -> addProjection(context, leftNode, symbol, firstArgument)).orElse(leftNode);
newRightNode = newSecondSymbol.map(symbol -> addProjection(context, rightNode, symbol, secondArgument)).orElse(rightNode);
}
else if (alignment < 0) {
newLeftNode = newSecondSymbol.map(symbol -> addProjection(context, leftNode, symbol, secondArgument)).orElse(leftNode);
newRightNode = newFirstSymbol.map(symbol -> addProjection(context, rightNode, symbol, firstArgument)).orElse(rightNode);
}
else {
return Result.empty();
}
Expression newFirstArgument = toExpression(newFirstSymbol, firstArgument);
Expression newSecondArgument = toExpression(newSecondSymbol, secondArgument);
Optional<Symbol> leftPartitionSymbol = Optional.empty();
Optional<Symbol> rightPartitionSymbol = Optional.empty();
if (kdbTree.isPresent()) {
leftPartitionSymbol = Optional.of(context.getSymbolAllocator().newSymbol("pid", INTEGER));
rightPartitionSymbol = Optional.of(context.getSymbolAllocator().newSymbol("pid", INTEGER));
if (alignment > 0) {
newLeftNode = addPartitioningNodes(context, newLeftNode, leftPartitionSymbol.get(), kdbTree.get(), newFirstArgument, Optional.empty());
newRightNode = addPartitioningNodes(context, newRightNode, rightPartitionSymbol.get(), kdbTree.get(), newSecondArgument, radius);
}
else {
newLeftNode = addPartitioningNodes(context, newLeftNode, leftPartitionSymbol.get(), kdbTree.get(), newSecondArgument, Optional.empty());
newRightNode = addPartitioningNodes(context, newRightNode, rightPartitionSymbol.get(), kdbTree.get(), newFirstArgument, radius);
}
}
Expression newSpatialFunction = new FunctionCall(spatialFunction.getName(), ImmutableList.of(newFirstArgument, newSecondArgument));
Expression newFilter = replaceExpression(filter, ImmutableMap.of(spatialFunction, newSpatialFunction));
return Result.ofPlanNode(new SpatialJoinNode(
nodeId,
SpatialJoinNode.Type.fromJoinNodeType(joinNode.getType()),
newLeftNode,
newRightNode,
outputSymbols,
newFilter,
leftPartitionSymbol,
rightPartitionSymbol,
kdbTree.map(KdbTreeUtils::toJson)));
}
private static KdbTree loadKdbTree(String tableName, Session session, Metadata metadata, SplitManager splitManager, PageSourceManager pageSourceManager)
{
QualifiedObjectName name = toQualifiedObjectName(tableName, session.getCatalog().get(), session.getSchema().get());
TableHandle tableHandle = metadata.getTableHandle(session, name)
.orElseThrow(() -> new PrestoException(INVALID_SPATIAL_PARTITIONING, format("Table not found: %s", name)));
Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle);
List<ColumnHandle> visibleColumnHandles = columnHandles.values().stream()
.filter(handle -> !metadata.getColumnMetadata(session, tableHandle, handle).isHidden())
.collect(toImmutableList());
checkSpatialPartitioningTable(visibleColumnHandles.size() == 1, "Expected single column for table %s, but found %s columns", name, columnHandles.size());
ColumnHandle kdbTreeColumn = Iterables.getOnlyElement(visibleColumnHandles);
Optional<KdbTree> kdbTree = Optional.empty();
try (SplitSource splitSource = splitManager.getSplits(session, tableHandle, UNGROUPED_SCHEDULING)) {
while (!Thread.currentThread().isInterrupted()) {
SplitBatch splitBatch = getFutureValue(splitSource.getNextBatch(NOT_PARTITIONED, Lifespan.taskWide(), 1000));
List<Split> splits = splitBatch.getSplits();
for (Split split : splits) {
try (ConnectorPageSource pageSource = pageSourceManager.createPageSource(session, split, tableHandle, ImmutableList.of(kdbTreeColumn))) {
do {
getFutureValue(pageSource.isBlocked());
Page page = pageSource.getNextPage();
if (page != null && page.getPositionCount() > 0) {
checkSpatialPartitioningTable(!kdbTree.isPresent(), "Expected exactly one row for table %s, but found more", name);
checkSpatialPartitioningTable(page.getPositionCount() == 1, "Expected exactly one row for table %s, but found %s rows", name, page.getPositionCount());
String kdbTreeJson = VARCHAR.getSlice(page.getBlock(0), 0).toStringUtf8();
try {
kdbTree = Optional.of(KdbTreeUtils.fromJson(kdbTreeJson));
}
catch (IllegalArgumentException e) {
checkSpatialPartitioningTable(false, "Invalid JSON string for KDB tree: %s", e.getMessage());
}
}
}
while (!pageSource.isFinished());
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
if (splitBatch.isLastBatch()) {
break;
}
}
}
checkSpatialPartitioningTable(kdbTree.isPresent(), "Expected exactly one row for table %s, but got none", name);
return kdbTree.get();
}
private static void checkSpatialPartitioningTable(boolean condition, String message, Object... arguments)
{
if (!condition) {
throw new PrestoException(INVALID_SPATIAL_PARTITIONING, format(message, arguments));
}
}
private static QualifiedObjectName toQualifiedObjectName(String name, String catalog, String schema)
{
ImmutableList<String> ids = ImmutableList.copyOf(Splitter.on('.').split(name));
if (ids.size() == 3) {
return new QualifiedObjectName(ids.get(0), ids.get(1), ids.get(2));
}
if (ids.size() == 2) {
return new QualifiedObjectName(catalog, ids.get(0), ids.get(1));
}
if (ids.size() == 1) {
return new QualifiedObjectName(catalog, schema, ids.get(0));
}
throw new PrestoException(INVALID_SPATIAL_PARTITIONING, format("Invalid name: %s", name));
}
private static int checkAlignment(JoinNode joinNode, Set<Symbol> maybeLeftSymbols, Set<Symbol> maybeRightSymbols)
{
List<Symbol> leftSymbols = joinNode.getLeft().getOutputSymbols();
List<Symbol> rightSymbols = joinNode.getRight().getOutputSymbols();
if (leftSymbols.containsAll(maybeLeftSymbols)
&& containsNone(leftSymbols, maybeRightSymbols)
&& rightSymbols.containsAll(maybeRightSymbols)
&& containsNone(rightSymbols, maybeLeftSymbols)) {
return 1;
}
if (leftSymbols.containsAll(maybeRightSymbols)
&& containsNone(leftSymbols, maybeLeftSymbols)
&& rightSymbols.containsAll(maybeLeftSymbols)
&& containsNone(rightSymbols, maybeRightSymbols)) {
return -1;
}
return 0;
}
private static Expression toExpression(Optional<Symbol> optionalSymbol, Expression defaultExpression)
{
return optionalSymbol.map(symbol -> (Expression) symbol.toSymbolReference()).orElse(defaultExpression);
}
private static Optional<Symbol> newGeometrySymbol(Context context, Expression expression, Metadata metadata)
{
if (expression instanceof SymbolReference) {
return Optional.empty();
}
return Optional.of(context.getSymbolAllocator().newSymbol(expression, metadata.getType(GEOMETRY_TYPE_SIGNATURE)));
}
private static Optional<Symbol> newRadiusSymbol(Context context, Expression expression)
{
if (expression instanceof SymbolReference) {
return Optional.empty();
}
return Optional.of(context.getSymbolAllocator().newSymbol(expression, DOUBLE));
}
private static PlanNode addProjection(Context context, PlanNode node, Symbol symbol, Expression expression)
{
Assignments.Builder projections = Assignments.builder();
for (Symbol outputSymbol : node.getOutputSymbols()) {
projections.putIdentity(outputSymbol);
}
projections.put(symbol, expression);
return new ProjectNode(context.getIdAllocator().getNextId(), node, projections.build());
}
private static PlanNode addPartitioningNodes(Context context, PlanNode node, Symbol partitionSymbol, KdbTree kdbTree, Expression geometry, Optional<Expression> radius)
{
Assignments.Builder projections = Assignments.builder();
for (Symbol outputSymbol : node.getOutputSymbols()) {
projections.putIdentity(outputSymbol);
}
ImmutableList.Builder<Expression> partitioningArguments = ImmutableList.<Expression>builder()
.add(new Cast(new StringLiteral(KdbTreeUtils.toJson(kdbTree)), KDB_TREE_TYPENAME))
.add(geometry);
radius.map(partitioningArguments::add);
FunctionCall partitioningFunction = new FunctionCall(QualifiedName.of("spatial_partitions"), partitioningArguments.build());
Symbol partitionsSymbol = context.getSymbolAllocator().newSymbol(partitioningFunction, new ArrayType(INTEGER));
projections.put(partitionsSymbol, partitioningFunction);
return new UnnestNode(
context.getIdAllocator().getNextId(),
new ProjectNode(context.getIdAllocator().getNextId(), node, projections.build()),
node.getOutputSymbols(),
ImmutableMap.of(partitionsSymbol, ImmutableList.of(partitionSymbol)),
Optional.empty());
}
private static boolean containsNone(Collection<Symbol> values, Collection<Symbol> testValues)
{
return values.stream().noneMatch(ImmutableSet.copyOf(testValues)::contains);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.spi.security.principal;
import java.lang.reflect.Field;
import java.security.Principal;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.spi.security.AbstractCompositeConfigurationTest;
import org.apache.jackrabbit.oak.spi.security.ConfigurationBase;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.SecurityProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class CompositePrincipalConfigurationTest extends AbstractCompositeConfigurationTest<PrincipalConfiguration> {
private final Root root = mock(Root.class);
private PrincipalConfiguration principalConfigurationMock;
@Before
public void before() {
compositeConfiguration = new CompositePrincipalConfiguration();
principalConfigurationMock = mock(PrincipalConfiguration.class);
Mockito.when(principalConfigurationMock.getParameters()).thenReturn(ConfigurationParameters.EMPTY);
}
private static void assertSize(int expected, CompositePrincipalProvider pp) throws Exception {
Field f = CompositePrincipalProvider.class.getDeclaredField("providers");
f.setAccessible(true);
List<PrincipalProvider> providers = (List<PrincipalProvider>) f.get(pp);
assertEquals(expected, providers.size());
}
@Test
public void testEmptyGetPrincipalManager() {
PrincipalManager pMgr = getComposite().getPrincipalManager(root, NamePathMapper.DEFAULT);
assertTrue(pMgr instanceof PrincipalManagerImpl);
}
@Test
public void testEmptyGetProvider() {
PrincipalProvider pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertFalse(pp instanceof CompositePrincipalProvider);
assertSame(EmptyPrincipalProvider.INSTANCE, pp);
}
@Test
public void testSingleGetPrincipalManager() {
PrincipalConfiguration testConfig = new TestPrincipalConfiguration();
addConfiguration(testConfig);
PrincipalManager pMgr = getComposite().getPrincipalManager(root, NamePathMapper.DEFAULT);
assertTrue(pMgr instanceof PrincipalManagerImpl);
}
@Test
public void testSingleGetProvider() {
PrincipalConfiguration testConfig = new TestPrincipalConfiguration();
addConfiguration(testConfig);
PrincipalProvider pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertFalse(pp instanceof CompositePrincipalProvider);
assertEquals(testConfig.getPrincipalProvider(root, NamePathMapper.DEFAULT).getClass(), pp.getClass());
}
@Test
public void testMultipleGetPrincipalManager() {
addConfiguration(principalConfigurationMock);
addConfiguration(new TestPrincipalConfiguration());
PrincipalManager pMgr = getComposite().getPrincipalManager(root, NamePathMapper.DEFAULT);
assertTrue(pMgr instanceof PrincipalManagerImpl);
}
@Test
public void testMultipleGetPrincipalProvider() throws Exception {
addConfiguration(principalConfigurationMock);
addConfiguration(new TestPrincipalConfiguration());
PrincipalProvider pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertTrue(pp instanceof CompositePrincipalProvider);
assertSize(2, (CompositePrincipalProvider) pp);
}
@Test
public void testWithEmptyPrincipalProvider() throws Exception {
addConfiguration(new TestEmptyConfiguration());
PrincipalProvider pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertSame(EmptyPrincipalProvider.INSTANCE, pp);
addConfiguration(new TestPrincipalConfiguration());
pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertFalse(pp instanceof CompositePrincipalProvider);
addConfiguration(principalConfigurationMock);
pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertTrue(pp instanceof CompositePrincipalProvider);
assertSize(2, (CompositePrincipalProvider) pp);
addConfiguration(new TestEmptyConfiguration());
pp = getComposite().getPrincipalProvider(root, NamePathMapper.DEFAULT);
assertTrue(pp instanceof CompositePrincipalProvider);
assertSize(2, (CompositePrincipalProvider) pp);
}
@Test
public void testInitWithSecurityProvider() {
SecurityProvider sp = mock(SecurityProvider.class);
TestComposite cpc = new TestComposite(sp);
assertSame(PrincipalConfiguration.NAME, cpc.getName());
assertSame(sp, cpc.getSecurityProvider());
}
private static final class TestComposite extends CompositePrincipalConfiguration {
TestComposite(@NotNull SecurityProvider securityProvider) {
super(securityProvider);
}
@NotNull
public SecurityProvider getSecurityProvider() {
return super.getSecurityProvider();
}
}
private static final class TestPrincipalConfiguration extends ConfigurationBase implements PrincipalConfiguration {
@NotNull
@Override
public PrincipalManager getPrincipalManager(Root root, NamePathMapper namePathMapper) {
return new PrincipalManagerImpl(getPrincipalProvider(root, namePathMapper));
}
@NotNull
@Override
public PrincipalProvider getPrincipalProvider(Root root, NamePathMapper namePathMapper) {
return new TestPrincipalProvider();
}
@NotNull
@Override
public String getName() {
return PrincipalConfiguration.NAME;
}
}
private static class TestPrincipalProvider implements PrincipalProvider {
@Nullable
@Override
public Principal getPrincipal(@NotNull String principalName) {
return null;
}
@NotNull
@Override
public Set<Principal> getMembershipPrincipals(@NotNull Principal principal) {
return ImmutableSet.of();
}
@NotNull
@Override
public Set<? extends Principal> getPrincipals(@NotNull String userID) {
return ImmutableSet.of();
}
@NotNull
@Override
public Iterator<? extends Principal> findPrincipals(@Nullable String nameHint, int searchType) {
return Collections.emptyIterator();
}
@NotNull
@Override
public Iterator<? extends Principal> findPrincipals(int searchType) {
return Collections.emptyIterator();
}
}
private static final class TestEmptyConfiguration extends ConfigurationBase implements PrincipalConfiguration {
@NotNull
@Override
public PrincipalManager getPrincipalManager(Root root, NamePathMapper namePathMapper) {
return new PrincipalManagerImpl(getPrincipalProvider(root, namePathMapper));
}
@NotNull
@Override
public PrincipalProvider getPrincipalProvider(Root root, NamePathMapper namePathMapper) {
return EmptyPrincipalProvider.INSTANCE;
}
@NotNull
@Override
public String getName() {
return PrincipalConfiguration.NAME;
}
}
}
| |
package de.mineformers.investiture.client.util;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import de.mineformers.investiture.Investiture;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.model.Attributes;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.obj.OBJModel;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import net.minecraftforge.client.model.pipeline.VertexTransformer;
import net.minecraftforge.common.model.TRSRTransformation;
import javax.vecmath.Vector4f;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import static net.minecraft.client.renderer.vertex.VertexFormatElement.EnumUsage.POSITION;
/**
* Provides utility methods dealing with Minecraft's and Forge's model system.
*/
public class Modeling
{
private static final Function<ResourceLocation, TextureAtlasSprite> TEXTURE_GETTER =
res -> new PassthroughSprite();
/**
* Tries to load and bake an OBJ model using Forge's facilities, substituting it for the "missing" model if any errors occur.
* The baked model will have flipped UVs (helpful with Blender's default export options) and will contain all groups from the OBJ file.
* There will be no texture replacement.
*
* @param resource the location of the model to load
* @return the baked model if there was no error while trying to load it, substituting it with the missing model otherwise
*/
public static IBakedModel loadModel(ResourceLocation resource)
{
return loadModel(resource, ImmutableMap.of());
}
/**
* Tries to load and bake an OBJ model using Forge's facilities, substituting it for the "missing" model if any errors occur.
* The baked model will have flipped UVs (helpful with Blender's default export options) and will contain all groups from the OBJ file.
*
* @param resource the location of the model to load
* @param textures a map from texture variables (starting with '#') in the model to the locations of the textures to use
* @return the baked model if there was no error while trying to load it, substituting it with the missing model otherwise
*/
public static IBakedModel loadModel(ResourceLocation resource, Map<String, ResourceLocation> textures)
{
return loadModel(resource, textures, ImmutableMap.of("flip-v", "true"));
}
/**
* Tries to load and bake an OBJ model using Forge's facilities, substituting it for the "missing" model if any errors occur.
* The baked model will contain all groups from the OBJ file.
*
* @param resource the location of the model to load
* @param textures a map from texture variables (starting with '#') in the model to the locations of the textures to use
* @param visibleGroups the groups in the OBJ file to show in the baked model
* @return the baked model if there was no error while trying to load it, substituting it with the missing model otherwise
*/
public static IBakedModel loadModel(ResourceLocation resource,
Map<String, ResourceLocation> textures,
List<String> visibleGroups)
{
return loadModel(resource, textures, visibleGroups, ImmutableMap.of("flip-v", "true"));
}
/**
* Tries to load and bake an OBJ model using Forge's facilities, substituting it for the "missing" model if any errors occur.
* The baked model will contain all groups from the OBJ file.
*
* @param resource the location of the model to load
* @param textures a map from texture variables (starting with '#') in the model to the locations of the textures to use
* @param customData the custom data to pass to the OBJ loader
* @return the baked model if there was no error while trying to load it, substituting it with the missing model otherwise
*/
public static IBakedModel loadModel(ResourceLocation resource,
Map<String, ResourceLocation> textures,
ImmutableMap<String, String> customData)
{
return loadModel(resource, textures, ImmutableList.of(OBJModel.Group.ALL), customData);
}
/**
* Tries to load and bake an OBJ model using Forge's facilities, substituting it for the "missing" model if any errors occur.
*
* @param resource the location of the model to load
* @param textures a map from texture variables (starting with '#') in the model to the locations of the textures to use
* @param visibleGroups the groups in the OBJ file to show in the baked model
* @param customData the custom data to pass to the OBJ loader
* @return the baked model if there was no error while trying to load it, substituting it with the missing model otherwise
*/
public static IBakedModel loadModel(ResourceLocation resource,
Map<String, ResourceLocation> textures,
List<String> visibleGroups,
ImmutableMap<String, String> customData)
{
try
{
IModel model = ModelLoaderRegistry.getModel(resource)
.retexture(FluentIterable.from(textures.keySet())
.toMap(k -> textures.get(k).toString()))
.process(customData);
return model.bake(part -> TRSRTransformation.identity().apply(part), Attributes.DEFAULT_BAKED_FORMAT, TEXTURE_GETTER);
}
catch (Exception e)
{
Investiture.log().error("Failed loading OBJ model '%s'", resource.toString(), e);
}
return ModelLoaderRegistry.getMissingModel().bake(part -> Optional.empty(), Attributes.DEFAULT_BAKED_FORMAT, TEXTURE_GETTER);
}
public static BakedQuad scale(VertexFormat format, BakedQuad quad, Vec3d scale)
{
return transform(format, quad, (usage, data) -> {
if (usage == POSITION)
{
float[] newData = new float[4];
Vector4f vec = new Vector4f(data);
vec.set((float) scale.x * vec.x, (float) scale.y * vec.y, (float) scale.z * vec.z, vec.w);
vec.get(newData);
return newData;
}
return data;
});
}
public static BakedQuad transform(VertexFormat format, BakedQuad quad, BiFunction<VertexFormatElement.EnumUsage, float[], float[]> transformer)
{
UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(format);
IVertexConsumer cons = new VertexTransformer(builder)
{
@Override
public void put(int element, float... data)
{
VertexFormatElement el = format.getElement(element);
parent.put(element, transformer.apply(el.getUsage(), data));
}
};
quad.pipe(cons);
return builder.build();
}
public static class PassthroughSprite extends TextureAtlasSprite
{
protected PassthroughSprite()
{
super("passthrough");
this.width = 128;
this.height = 128;
this.originX = 0;
this.originY = 0;
initSprite(128, 128, 0, 0, false);
}
@Override
public int getOriginX()
{
return 0;
}
@Override
public int getOriginY()
{
return 0;
}
@Override
public float getMinU()
{
return 0;
}
@Override
public float getMaxU()
{
return 1;
}
@Override
public float getMinV()
{
return 0;
}
@Override
public float getMaxV()
{
return 1;
}
}
}
| |
/*
*
* This file was generated by LLRP Code Generator
* see http://llrp-toolkit.cvs.sourceforge.net/llrp-toolkit/
* for more information
* Generated on: Sun Apr 08 14:14:11 EDT 2012;
*
*/
/*
* Copyright 2007 ETH Zurich
*
* 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.llrp.ltk.generated.parameters;
import maximsblog.blogspot.com.llrpexplorer.Logger;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.llrp.ltk.exceptions.InvalidLLRPMessageException;
import org.llrp.ltk.exceptions.MissingParameterException;
import org.llrp.ltk.generated.LLRPConstants;
import org.llrp.ltk.types.LLRPBitList;
import org.llrp.ltk.types.LLRPMessage;
import org.llrp.ltk.types.SignedShort;
import org.llrp.ltk.types.TLVParameter;
import org.llrp.ltk.types.TVParameter;
import org.llrp.ltk.types.UnsignedInteger;
import org.llrp.ltk.types.UnsignedShort;
import java.util.LinkedList;
import java.util.List;
/**
* This parameter carries the AccessSpecID information.
See also {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=85&view=fit">LLRP Specification Section 13.2.3.15</a>}
and {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=146&view=fit">LLRP Specification Section 16.2.7.3.15</a>}
*/
/**
* This parameter carries the AccessSpecID information.
See also {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=85&view=fit">LLRP Specification Section 13.2.3.15</a>}
and {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=146&view=fit">LLRP Specification Section 16.2.7.3.15</a>}
.
*/
public class AccessSpecID extends TVParameter {
public static final SignedShort TYPENUM = new SignedShort(16);
private static final Logger LOGGER = Logger.getLogger(AccessSpecID.class);
protected UnsignedInteger accessSpecID;
/**
* empty constructor to create new parameter.
*/
public AccessSpecID() {
}
/**
* Constructor to create parameter from binary encoded parameter
* calls decodeBinary to decode parameter.
* @param list to be decoded
*/
public AccessSpecID(LLRPBitList list) {
decodeBinary(list);
}
/**
* Constructor to create parameter from xml encoded parameter
* calls decodeXML to decode parameter.
* @param element to be decoded
*/
public AccessSpecID(Element element) throws InvalidLLRPMessageException {
decodeXML(element);
}
/**
* {@inheritDoc}
*/
public LLRPBitList encodeBinarySpecific() {
LLRPBitList resultBits = new LLRPBitList();
if (accessSpecID == null) {
LOGGER.warn(" accessSpecID not set");
throw new MissingParameterException(
" accessSpecID not set for Parameter of Type AccessSpecID");
}
resultBits.append(accessSpecID.encodeBinary());
return resultBits;
}
/**
* {@inheritDoc}
*/
public Content encodeXML(String name, Namespace ns) {
// element in namespace defined by parent element
Element element = new Element(name, ns);
// child element are always in default LLRP namespace
ns = Namespace.getNamespace("llrp", LLRPConstants.LLRPNAMESPACE);
if (accessSpecID == null) {
LOGGER.warn(" accessSpecID not set");
throw new MissingParameterException(" accessSpecID not set");
} else {
element.addContent(accessSpecID.encodeXML("AccessSpecID", ns));
}
//parameters
return element;
}
/**
* {@inheritDoc}
*/
protected void decodeBinarySpecific(LLRPBitList binary) {
int position = 0;
int tempByteLength;
int tempLength = 0;
int count;
SignedShort type;
int fieldCount;
Custom custom;
accessSpecID = new UnsignedInteger(binary.subList(position,
UnsignedInteger.length()));
position += UnsignedInteger.length();
}
/**
* {@inheritDoc}
*/
public void decodeXML(Element element) throws InvalidLLRPMessageException {
List<Element> tempList = null;
boolean atLeastOnce = false;
Custom custom;
Element temp = null;
// child element are always in default LLRP namespace
Namespace ns = Namespace.getNamespace(LLRPConstants.LLRPNAMESPACE);
temp = element.getChild("AccessSpecID", ns);
if (temp != null) {
accessSpecID = new UnsignedInteger(temp);
}
element.removeChild("AccessSpecID", ns);
if (element.getChildren().size() > 0) {
String message = "AccessSpecID has unknown element " +
((Element) element.getChildren().get(0)).getName();
throw new InvalidLLRPMessageException(message);
}
}
//setters
/**
* set accessSpecID of type UnsignedInteger .
* @param accessSpecID to be set
*/
public void setAccessSpecID(final UnsignedInteger accessSpecID) {
this.accessSpecID = accessSpecID;
}
// end setter
//getters
/**
* get accessSpecID of type UnsignedInteger.
* @return type UnsignedInteger to be set
*/
public UnsignedInteger getAccessSpecID() {
return this.accessSpecID;
}
// end getters
//add methods
// end add
/**
* return length of parameter. For TV Parameter it is always length of its field plus 8 bits for type.
* @return Integer giving length
*/
public static Integer length() {
int tempLength = PARAMETERTYPELENGTH;
// the length of a TV parameter in bits is always the type
tempLength += UnsignedInteger.length();
return tempLength;
}
/**
* {@inheritDoc}
*/
public SignedShort getTypeNum() {
return TYPENUM;
}
/**
* {@inheritDoc}
*/
public String getName() {
return "AccessSpecID";
}
/**
* return string representation. All field values but no parameters are included
* @return String
*/
public String toString() {
String result = "AccessSpecID: ";
result += ", accessSpecID: ";
result += accessSpecID;
result = result.replaceFirst(", ", "");
return result;
}
}
| |
package tools.mapEditor;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import gui.logic.GuiGameMap;
import gui.logic.GuiMapData;
import gui.logic.GuiObservedGameMap;
import gui.resources.Resources;
import logic.GameMap;
public class MapEditor extends JFrame {
private final MapFrame mapFrame;
private final JButton btnAdd, btnSave;
private final GuiObservedGameMap observedMap;
public MapEditor(String mapDataPath) {
GameMap map = new GameMap(mapDataPath);
map.loadMap(mapDataPath);
GuiMapData mapModel = new GuiMapData(map);
this.observedMap = new GuiObservedGameMap(mapModel);
this.mapFrame = new MapFrame(this.observedMap);
this.btnAdd = new JButton("Create Figure");
this.btnSave = new JButton("Save Map Data");
this.setSize(400, 400);
this.setLocation(100, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildLayout();
registerListeners();
this.loadImage();
this.setVisible(true);
}
private void buildLayout() {
this.setLayout(new BorderLayout());
this.add(this.mapFrame, BorderLayout.CENTER);
this.add(this.btnAdd, BorderLayout.NORTH);
this.add(this.btnSave, BorderLayout.SOUTH);
}
private void registerListeners() {
this.btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addShape();
}
});
this.btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveData();
}
});
}
private void loadImage() {
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Open Map Image File");
try {
jfc.setCurrentDirectory(new File(Resources.getMapsURL().toURI()));
} catch (URISyntaxException ex) {
return;
}
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String fName = jfc.getSelectedFile().getName();
this.observedMap.loadMapImage(fName);
System.out.println("File name: " + fName);
Image img = this.observedMap.getMapImage();
if (img != null)
this.setSize(img.getWidth(null) + 20, img.getHeight(null) + 90);
this.repaint();
this.revalidate();
}
}
private void addShape() {
Shape shape = this.mapFrame.finalizeFigure();
if (shape == null)
return;
// Get zone name
String s = (String) JOptionPane.showInputDialog(null, "Please provide the name of the created zone", "Ok",
JOptionPane.PLAIN_MESSAGE, null, null, "");
this.observedMap.addZone(s, shape);
this.mapFrame.repaint();
this.repaint();
}
private void saveData() {
JFileChooser jfc = new JFileChooser();
jfc.setDialogTitle("Save map data");
jfc.setFileFilter(new FileNameExtensionFilter("Map Data File", "mapdata"));
try {
jfc.setCurrentDirectory(new File(Resources.getMapsURL().toURI()));
} catch (URISyntaxException ex) {
return;
}
if (jfc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String path = jfc.getSelectedFile().getAbsolutePath();
try {
this.observedMap.saveData(path);
} catch (IOException ex) {
}
}
}
}
class MapFrame extends JPanel {
private final Color RegionColor = Color.GREEN;
private final Color PointColor = Color.RED;
private final int PointSize = 6;
private Path2D tmpPath;
private final GuiGameMap mapData;
public MapFrame(GuiObservedGameMap map) {
super();
this.mapData = map;
registerListeners();
}
private void registerListeners() {
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
p.x = p.x - PointSize / 2;
p.y = p.y - PointSize / 2;
if (tmpPath == null) {
tmpPath = new Path2D.Double();
tmpPath.moveTo(p.x, p.y);
} else
tmpPath.lineTo(p.x, p.y);
repaint();
}
});
}
public Shape finalizeFigure() {
if (this.tmpPath == null)
return null;
this.tmpPath.closePath();
Area a = new Area(this.tmpPath);
// Area is not serializable, so we'll get an equivalent Shape instead
Shape res = AffineTransform.getTranslateInstance(0, 0).createTransformedShape(a);
this.tmpPath = null;
return res;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
this.paintZones(g2D);
this.paintPoints(g2D);
}
private void paintZones(Graphics2D g2D) {
Image mapImg = this.mapData.getMapImage();
if (mapImg == null)
g2D.drawString("Invalid Image", 0, 0);
else
g2D.drawImage(mapImg, 0, 0, null);
g2D.setColor(this.RegionColor);
g2D.setStroke(new BasicStroke(3));
for (Shape a : this.mapData.getZoneShapeList()) {
if (a != null)
g2D.draw(a);
}
}
private void paintPoints(Graphics2D g2D) {
if (this.tmpPath == null)
return;
g2D.setColor(this.PointColor);
double[] coords = new double[6];
PathIterator pIterator = this.tmpPath.getPathIterator(null);
while (!pIterator.isDone()) {
pIterator.currentSegment(coords);
if (coords != null)
g2D.fillOval((int) coords[0], (int) coords[1], this.PointSize, this.PointSize);
pIterator.next();
}
}
}
| |
/*
* Copyright 2015 Goldman Sachs.
*
* 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.gs.collections.impl.bag.sorted.immutable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.sorted.ImmutableSortedBag;
import com.gs.collections.api.bag.sorted.MutableSortedBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.ListIterable;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.sortedbag.ImmutableSortedBagMultimap;
import com.gs.collections.api.partition.bag.sorted.PartitionImmutableSortedBag;
import com.gs.collections.api.partition.bag.sorted.PartitionSortedBag;
import com.gs.collections.api.set.sorted.ImmutableSortedSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.primitive.ObjectIntPair;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.bag.mutable.primitive.BooleanHashBag;
import com.gs.collections.impl.bag.mutable.primitive.ByteHashBag;
import com.gs.collections.impl.bag.mutable.primitive.CharHashBag;
import com.gs.collections.impl.bag.mutable.primitive.DoubleHashBag;
import com.gs.collections.impl.bag.mutable.primitive.FloatHashBag;
import com.gs.collections.impl.bag.mutable.primitive.IntHashBag;
import com.gs.collections.impl.bag.mutable.primitive.LongHashBag;
import com.gs.collections.impl.bag.mutable.primitive.ShortHashBag;
import com.gs.collections.impl.bag.sorted.mutable.TreeBag;
import com.gs.collections.impl.block.factory.Comparators;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.IntegerPredicates;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.block.factory.Predicates2;
import com.gs.collections.impl.block.factory.PrimitiveFunctions;
import com.gs.collections.impl.block.factory.primitive.IntPredicates;
import com.gs.collections.impl.block.function.AddFunction;
import com.gs.collections.impl.block.function.NegativeIntervalFunction;
import com.gs.collections.impl.block.function.PassThruFunction0;
import com.gs.collections.impl.block.procedure.CollectionAddProcedure;
import com.gs.collections.impl.collection.immutable.AbstractImmutableCollectionTestCase;
import com.gs.collections.impl.factory.Bags;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.factory.SortedBags;
import com.gs.collections.impl.factory.SortedSets;
import com.gs.collections.impl.list.Interval;
import com.gs.collections.impl.list.mutable.AddToList;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList;
import com.gs.collections.impl.list.mutable.primitive.ByteArrayList;
import com.gs.collections.impl.list.mutable.primitive.CharArrayList;
import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList;
import com.gs.collections.impl.list.mutable.primitive.FloatArrayList;
import com.gs.collections.impl.list.mutable.primitive.IntArrayList;
import com.gs.collections.impl.list.mutable.primitive.LongArrayList;
import com.gs.collections.impl.list.mutable.primitive.ShortArrayList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.map.sorted.mutable.TreeSortedMap;
import com.gs.collections.impl.multimap.bag.sorted.mutable.TreeBagMultimap;
import com.gs.collections.impl.set.sorted.mutable.TreeSortedSet;
import com.gs.collections.impl.stack.mutable.ArrayStack;
import com.gs.collections.impl.test.Verify;
import com.gs.collections.impl.tuple.Tuples;
import com.gs.collections.impl.tuple.primitive.PrimitiveTuples;
import org.junit.Assert;
import org.junit.Test;
public abstract class AbstractImmutableSortedBagTestCase extends AbstractImmutableCollectionTestCase
{
@Override
protected abstract ImmutableSortedBag<Integer> classUnderTest();
protected abstract ImmutableSortedBag<Integer> classUnderTest(Comparator<? super Integer> comparator);
protected <T> ImmutableSortedBag<T> newWithOccurrences(ObjectIntPair<T>... elementsWithOccurrences)
{
TreeBag<T> bag = TreeBag.newBag();
for (int i = 0; i < elementsWithOccurrences.length; i++)
{
ObjectIntPair<T> itemToAdd = elementsWithOccurrences[i];
bag.addOccurrences(itemToAdd.getOne(), itemToAdd.getTwo());
}
return bag.toImmutable();
}
protected abstract <T> ImmutableSortedBag<T> newWith(T... elements);
protected abstract <T> ImmutableSortedBag<T> newWith(Comparator<? super T> comparator, T... elements);
@Test(expected = NullPointerException.class)
public void noSupportForNull()
{
this.classUnderTest().newWith(null);
}
@Test
public void equalsAndHashCode()
{
ImmutableSortedBag<Integer> immutable = this.classUnderTest();
MutableSortedBag<Integer> mutable = TreeBag.newBag(immutable);
Verify.assertEqualsAndHashCode(mutable, immutable);
Verify.assertPostSerializedEqualsAndHashCode(immutable);
Assert.assertNotEquals(FastList.newList(mutable), immutable);
ImmutableSortedBag<Integer> bag1 = SortedBags.immutable.of(1, 1, 1, 4);
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(1, 1, 1, 3);
Assert.assertNotEquals(bag1, bag2);
}
@Test
public void compareTo()
{
Assert.assertEquals(-1, SortedBags.immutable.of(1, 1, 2, 2).compareTo(SortedBags.immutable.of(1, 1, 2, 2, 2)));
Assert.assertEquals(0, SortedBags.immutable.of(1, 1, 2, 2).compareTo(SortedBags.immutable.of(1, 1, 2, 2)));
Assert.assertEquals(1, SortedBags.immutable.of(1, 1, 2, 2, 2).compareTo(SortedBags.immutable.of(1, 1, 2, 2)));
Assert.assertEquals(-1, SortedBags.immutable.of(1, 1, 2, 2).compareTo(SortedBags.immutable.of(1, 1, 3, 3)));
Assert.assertEquals(1, SortedBags.immutable.of(1, 1, 3, 3).compareTo(SortedBags.immutable.of(1, 1, 2, 2)));
Assert.assertEquals(1, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 2, 2, 1, 1, 1).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 2, 2, 1, 1)));
Assert.assertEquals(1, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2, 2)));
Assert.assertEquals(0, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2)));
Assert.assertEquals(-1, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2, 2).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2)));
Assert.assertEquals(1, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 3, 3)));
Assert.assertEquals(-1, SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 3, 3).compareTo(SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 2, 2)));
}
@Test
public void selectByOccurrences()
{
ImmutableSortedBag<Integer> ints = this.classUnderTest().selectByOccurrences(IntPredicates.isEven());
Verify.assertAllSatisfy(ints, IntegerPredicates.isEven());
ImmutableSortedBag<Integer> ints2 = this.classUnderTest().selectByOccurrences(IntPredicates.isOdd());
Assert.assertEquals(ints2, this.classUnderTest());
}
@Test
public void newWithTest()
{
ImmutableSortedBag<Integer> immutable = this.classUnderTest();
immutable = immutable.newWith(4);
// inserting at the beginning point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 1, 2, 4), immutable.newWith(1));
// inserting at the middle point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2, 2, 4), immutable.newWith(2));
// inserting at the end point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2, 4, 4), immutable.newWith(4));
// inserting at the beginning point (not existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(0, 1, 1, 1, 2, 4), immutable.newWith(0));
// inserting at the middle point (not existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2, 3, 4), immutable.newWith(3));
// inserting at the end point (not existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2, 4, 5), immutable.newWith(5));
}
@Test
public void newWithout()
{
ImmutableSortedBag<Integer> immutable = this.classUnderTest();
immutable = immutable.newWith(4);
// removing at the beginning point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 2, 4), immutable.newWithout(1));
// removing at the middle point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 4), immutable.newWithout(2));
// removing at the end point (existing element)
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2), immutable.newWithout(4));
// removing at the beginning point (not existing element)
Assert.assertEquals(immutable, immutable.newWithout(0));
// removing at the middle point (not existing element)
Assert.assertEquals(immutable, immutable.newWithout(3));
// removing at the end point (not existing element)
Assert.assertEquals(immutable, immutable.newWithout(5));
}
@Test
public void newWithAll()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
ImmutableSortedBag<Integer> actualBag = bag.newWithAll(HashBag.newBagWith(3, 4));
Assert.assertNotEquals(bag, actualBag);
TreeBag<Integer> expectedBag = TreeBag.newBagWith(Comparators.<Integer>reverseNaturalOrder(), 4, 3, 2, 1, 1, 1);
Verify.assertSortedBagsEqual(expectedBag,
actualBag);
Assert.assertSame(expectedBag.comparator(), actualBag.comparator());
}
@Test
public void toStringOfItemToCount()
{
Assert.assertEquals("{}", SortedBags.immutable.empty().toStringOfItemToCount());
Assert.assertEquals("{1=3, 2=1}", this.classUnderTest().toStringOfItemToCount());
Assert.assertEquals("{2=1, 1=3}", this.classUnderTest(Comparator.<Integer>reverseOrder()).toStringOfItemToCount());
}
@Test
public void newWithoutAll()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest();
ImmutableSortedBag<Integer> withoutAll = bag.newWithoutAll(bag);
Assert.assertEquals(SortedBags.immutable.<Integer>empty(), withoutAll);
Assert.assertEquals(Bags.immutable.<Integer>empty(), withoutAll);
ImmutableSortedBag<Integer> largeWithoutAll = bag.newWithoutAll(Interval.fromTo(101, 150));
Assert.assertEquals(bag, largeWithoutAll);
ImmutableSortedBag<Integer> largeWithoutAll2 = bag.newWithoutAll(HashBag.newBag(Interval.fromTo(151, 199)));
Assert.assertEquals(bag, largeWithoutAll2);
}
@Test
public void size()
{
ImmutableSortedBag<Object> empty = SortedBags.immutable.empty();
Assert.assertEquals(0, empty.size());
ImmutableSortedBag<?> empty2 = SortedBags.immutable.empty(Comparators.reverseNaturalOrder());
Assert.assertEquals(0, empty2.size());
ImmutableSortedBag<Integer> integers = SortedBags.immutable.of(Comparator.<Integer>reverseOrder(), 1, 2, 3, 4, 4, 4);
Assert.assertEquals(6, integers.size());
ImmutableSortedBag<Integer> integers2 = SortedBags.immutable.of(1, 2, 3, 4, 4, 4);
Assert.assertEquals(6, integers2.size());
}
@Test
public void contains()
{
ImmutableSortedBag<Integer> bag1 = this.classUnderTest();
Verify.assertContains(1, bag1);
Verify.assertContains(2, bag1);
Verify.assertNotContains(Integer.valueOf(bag1.size() + 1), bag1.toSortedBag());
}
@Test
public void containsAllArray()
{
ImmutableSortedBag<Integer> bag1 = this.classUnderTest();
Assert.assertTrue(bag1.containsAllArguments(bag1.toArray()));
}
@Test
public void containsAllIterable()
{
ImmutableSortedBag<Integer> bag1 = this.classUnderTest();
Assert.assertTrue(bag1.containsAllIterable(FastList.newListWith(1, 1, 1, 2)));
Assert.assertFalse(bag1.containsAllIterable(FastList.newListWith(50, 1, 1, 2)));
}
@Test
public void containsAll()
{
ImmutableSortedBag<Integer> bag1 = this.classUnderTest();
Assert.assertTrue(bag1.containsAll(FastList.newListWith(1, 1, 1, 2)));
Assert.assertFalse(bag1.containsAll(FastList.newListWith(50, 1, 1, 2)));
}
@Override
@Test
public void tap()
{
MutableList<Integer> tapResult = Lists.mutable.empty();
ImmutableSortedBag<Integer> collection = this.classUnderTest();
Assert.assertSame(collection, collection.tap(tapResult::add));
Assert.assertEquals(collection.toList(), tapResult);
}
@Test
public void forEach()
{
MutableBag<Integer> result = HashBag.newBag();
ImmutableSortedBag<Integer> collection = this.classUnderTest();
collection.forEach(CollectionAddProcedure.on(result));
Assert.assertEquals(collection, result);
}
@Test
public void forEachWith()
{
MutableList<Integer> result = Lists.mutable.empty();
ImmutableSortedBag<Integer> bag = this.classUnderTest();
bag.forEachWith((argument1, argument2) -> result.add(argument1 + argument2), 0);
Verify.assertListsEqual(result, bag.toList());
}
@Test
public void forEachWithIndex()
{
MutableList<Integer> result = Lists.mutable.empty();
ImmutableSortedBag<Integer> bag = this.classUnderTest();
bag.forEachWithIndex((object, index) -> result.add(object));
Verify.assertListsEqual(result, bag.toList());
}
@Override
public void toSortedSet()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableSortedSet<Integer> set = integers.toSortedSet();
Assert.assertEquals(SortedSets.immutable.of(1, 2), set);
}
@Override
public void toSortedSetWithComparator()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.reverseNaturalOrder());
MutableSortedSet<Integer> set = integers.toSortedSet();
ImmutableSortedSet<Integer> expected = SortedSets.immutable.of(Comparators.reverseNaturalOrder(), 1, 2);
Assert.assertEquals(expected, set);
Assert.assertNotSame(expected.comparator(), set.comparator());
ImmutableSortedBag<Integer> integers2 = this.classUnderTest(Comparators.reverseNaturalOrder());
MutableSortedSet<Integer> set2 = integers2.toSortedSet(Comparators.reverseNaturalOrder());
ImmutableSortedSet<Integer> expected2 = SortedSets.immutable.of(Comparators.reverseNaturalOrder(), 1, 2);
Assert.assertEquals(expected2, set2);
Assert.assertSame(expected2.comparator(), set2.comparator());
}
@Override
@Test
public void select()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Verify.assertIterableEmpty(integers.select(Predicates.greaterThan(integers.size())));
TreeBag<Integer> expectedBag = TreeBag.newBagWith(Comparators.<Integer>reverseNaturalOrder(), 1, 1, 1, 2);
ImmutableSortedBag<Integer> actualBag = integers.select(Predicates.lessThan(integers.size()));
Verify.assertSortedBagsEqual(expectedBag, actualBag);
Assert.assertSame(expectedBag.comparator(), actualBag.comparator());
}
@Override
@Test
public void selectWith()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Verify.assertIterableEmpty(integers.selectWith(Predicates2.<Integer>greaterThan(), integers.size()));
TreeBag<Integer> expectedBag = TreeBag.newBagWith(Comparators.<Integer>reverseNaturalOrder(), 1, 1, 1, 2);
ImmutableSortedBag<Integer> actualBag = integers.selectWith(Predicates2.<Integer>lessThan(), integers.size());
Verify.assertSortedBagsEqual(expectedBag, actualBag);
Assert.assertSame(expectedBag.comparator(), actualBag.comparator());
}
@Test
public void selectToTarget()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Verify.assertListsEqual(integers.toList(),
integers.select(Predicates.lessThan(integers.size() + 1), FastList.<Integer>newList()));
Verify.assertEmpty(
integers.select(Predicates.greaterThan(integers.size()), FastList.<Integer>newList()));
}
@Override
@Test
public void reject()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertEmpty(
FastList.newList(integers.reject(Predicates.lessThan(integers.size() + 1))));
Verify.assertSortedBagsEqual(integers,
integers.reject(Predicates.greaterThan(integers.size())));
}
@Override
@Test
public void rejectWith()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Verify.assertIterableEmpty(integers.rejectWith(Predicates2.<Integer>lessThanOrEqualTo(), integers.size()));
TreeBag<Integer> expectedBag = TreeBag.newBagWith(Comparators.<Integer>reverseNaturalOrder(), 1, 1, 1, 2);
ImmutableSortedBag<Integer> actualBag = integers.rejectWith(Predicates2.<Integer>greaterThanOrEqualTo(), integers.size());
Verify.assertSortedBagsEqual(expectedBag,
actualBag);
Assert.assertSame(expectedBag.comparator(), actualBag.comparator());
}
@Test
public void rejectToTarget()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Verify.assertEmpty(
integers.reject(Predicates.lessThan(integers.size() + 1), FastList.<Integer>newList()));
Verify.assertListsEqual(integers.toList(),
integers.reject(Predicates.greaterThan(integers.size()), FastList.<Integer>newList()));
ImmutableSortedBag<Integer> integers2 = this.classUnderTest();
Assert.assertEquals(HashBag.newBagWith(2),
integers2.reject(each -> each == 1, new HashBag<>()));
}
@Override
@Test
public void selectInstancesOf()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(bag, bag.selectInstancesOf(Integer.class));
Verify.assertIterableEmpty(bag.selectInstancesOf(Double.class));
Assert.assertSame(bag.comparator(), bag.selectInstancesOf(Integer.class).comparator());
Assert.assertSame(bag.comparator(), bag.selectInstancesOf(Double.class).comparator());
}
@Override
@Test
public void partition()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionImmutableSortedBag<Integer> partition1 = integers.partition(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(partition1.getSelected());
Assert.assertEquals(integers, partition1.getRejected());
Assert.assertSame(integers.comparator(), partition1.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition1.getRejected().comparator());
PartitionImmutableSortedBag<Integer> partition2 = integers.partition(integer -> integer % 2 == 0);
Verify.assertSortedBagsEqual(integers.select(integer -> integer % 2 == 0), partition2.getSelected());
Verify.assertSortedBagsEqual(integers.reject(integer -> integer % 2 == 0), partition2.getRejected());
Assert.assertSame(integers.comparator(), partition2.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition2.getRejected().comparator());
}
@Override
@Test
public void partitionWith()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionImmutableSortedBag<Integer> partition1 = integers.partitionWith(Predicates2.<Integer>greaterThan(), integers.size());
Verify.assertIterableEmpty(partition1.getSelected());
Assert.assertEquals(integers, partition1.getRejected());
Assert.assertSame(integers.comparator(), partition1.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition1.getRejected().comparator());
PartitionImmutableSortedBag<Integer> partition2 = integers.partitionWith((integer, divisor) -> integer % divisor == 0, 2);
Verify.assertSortedBagsEqual(integers.select(integer -> integer % 2 == 0), partition2.getSelected());
Verify.assertSortedBagsEqual(integers.reject(integer -> integer % 2 == 0), partition2.getRejected());
Assert.assertSame(integers.comparator(), partition2.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition2.getRejected().comparator());
}
@Test
public void partitionWhile()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
PartitionSortedBag<Integer> partition1 = integers.partitionWhile(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(partition1.getSelected());
Assert.assertEquals(integers, partition1.getRejected());
Assert.assertSame(integers.comparator(), partition1.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition1.getRejected().comparator());
PartitionSortedBag<Integer> partition2 = integers.partitionWhile(Predicates.lessThanOrEqualTo(integers.size()));
Assert.assertEquals(integers, partition2.getSelected());
Verify.assertIterableEmpty(partition2.getRejected());
Assert.assertSame(integers.comparator(), partition2.getSelected().comparator());
Assert.assertSame(integers.comparator(), partition2.getRejected().comparator());
}
@Test
public void takeWhile()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedBag<Integer> take1 = integers.takeWhile(Predicates.greaterThan(integers.size()));
Verify.assertIterableEmpty(take1);
Assert.assertSame(integers.comparator(), take1.comparator());
ImmutableSortedBag<Integer> take2 = integers.takeWhile(Predicates.lessThanOrEqualTo(integers.size()));
Assert.assertEquals(integers, take2);
Assert.assertSame(integers.comparator(), take2.comparator());
}
@Test
public void dropWhile()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableSortedBag<Integer> drop1 = integers.dropWhile(Predicates.greaterThan(integers.size()));
Assert.assertEquals(integers, drop1);
Assert.assertEquals(Collections.<Integer>reverseOrder(), drop1.comparator());
ImmutableSortedBag<Integer> drop2 = integers.dropWhile(Predicates.lessThanOrEqualTo(integers.size()));
Verify.assertIterableEmpty(drop2);
Assert.assertEquals(Collections.<Integer>reverseOrder(), drop2.comparator());
}
@Override
@Test
public void collect()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertListsEqual(integers.toList(), integers.collect(Functions.getIntegerPassThru()).castToList());
}
@Override
@Test
public void collectWith()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
Verify.assertListsEqual(integers.toList(), integers.collectWith((value, parameter) -> value / parameter, 1).castToList());
}
@Test
public void collectToTarget()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(HashBag.newBag(integers), integers.collect(Functions.getIntegerPassThru(), HashBag.<Integer>newBag()));
Verify.assertListsEqual(integers.toList(),
integers.collect(Functions.getIntegerPassThru(), FastList.<Integer>newList()));
}
@Override
@Test
public void flatCollect()
{
ImmutableList<String> actual = this.classUnderTest(Collections.<Integer>reverseOrder()).flatCollect(integer -> Lists.fixedSize.of(String.valueOf(integer)));
ImmutableList<String> expected = this.classUnderTest(Collections.<Integer>reverseOrder()).collect(String::valueOf);
Assert.assertEquals(expected, actual);
Verify.assertListsEqual(expected.toList(), actual.toList());
}
@Test
public void flatCollectWithTarget()
{
MutableBag<String> actual = this.classUnderTest().flatCollect(integer -> Lists.fixedSize.of(String.valueOf(integer)), HashBag.<String>newBag());
ImmutableList<String> expected = this.classUnderTest().collect(String::valueOf);
Assert.assertEquals(expected.toBag(), actual);
}
@Test
public void zip()
{
ImmutableSortedBag<Integer> immutableBag = this.classUnderTest(Collections.<Integer>reverseOrder());
List<Object> nulls = Collections.nCopies(immutableBag.size(), null);
List<Object> nullsPlusOne = Collections.nCopies(immutableBag.size() + 1, null);
List<Object> nullsMinusOne = Collections.nCopies(immutableBag.size() - 1, null);
ImmutableList<Pair<Integer, Object>> pairs = immutableBag.zip(nulls);
Assert.assertEquals(immutableBag.toList(), pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne));
Verify.assertListsEqual(FastList.newListWith(2, 1, 1, 1), pairs.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).toList());
Assert.assertEquals(FastList.newList(nulls), pairs.collect((Function<Pair<?, Object>, Object>) Pair::getTwo));
ImmutableList<Pair<Integer, Object>> pairsPlusOne = immutableBag.zip(nullsPlusOne);
Assert.assertEquals(immutableBag.toList(), pairsPlusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne));
Verify.assertListsEqual(FastList.newListWith(2, 1, 1, 1),
pairsPlusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).castToList());
Assert.assertEquals(FastList.newList(nulls), pairsPlusOne.collect((Function<Pair<?, Object>, Object>) Pair::getTwo));
ImmutableList<Pair<Integer, Object>> pairsMinusOne = immutableBag.zip(nullsMinusOne);
Verify.assertListsEqual(FastList.newListWith(2, 1, 1),
pairsMinusOne.collect((Function<Pair<Integer, ?>, Integer>) Pair::getOne).castToList());
Assert.assertEquals(immutableBag.zip(nulls), immutableBag.zip(nulls, FastList.<Pair<Integer, Object>>newList()));
Assert.assertEquals(immutableBag.zip(nulls).toBag(), immutableBag.zip(nulls, new HashBag<>()));
FastList<Holder> holders = FastList.newListWith(new Holder(1), new Holder(2), new Holder(3));
ImmutableList<Pair<Integer, Holder>> zipped = immutableBag.zip(holders);
Verify.assertSize(3, zipped.castToList());
AbstractImmutableSortedBagTestCase.Holder two = new Holder(-1);
AbstractImmutableSortedBagTestCase.Holder two1 = new Holder(-1);
Assert.assertEquals(Tuples.pair(10, two1), zipped.newWith(Tuples.pair(10, two)).getLast());
Assert.assertEquals(Tuples.pair(1, new Holder(3)), this.classUnderTest().zip(holders.reverseThis()).getFirst());
}
@Test
public void zipWithIndex()
{
ImmutableSortedBag<Integer> integers = SortedBags.immutable.of(Collections.<Integer>reverseOrder(), 1, 3, 5, 5, 5, 2, 4);
ImmutableSortedSet<Pair<Integer, Integer>> expected = TreeSortedSet.newSetWith(
Tuples.pair(5, 0),
Tuples.pair(5, 1),
Tuples.pair(5, 2),
Tuples.pair(4, 3),
Tuples.pair(3, 4),
Tuples.pair(2, 5),
Tuples.pair(1, 6)).toImmutable();
ImmutableSortedSet<Pair<Integer, Integer>> actual = integers.zipWithIndex();
Assert.assertEquals(expected, actual);
ImmutableSortedBag<Integer> integersNoComparator = SortedBags.immutable.of(1, 3, 5, 5, 5, 2, 4);
ImmutableSortedSet<Pair<Integer, Integer>> expected2 = TreeSortedSet.newSetWith(
Tuples.pair(1, 0),
Tuples.pair(2, 1),
Tuples.pair(3, 2),
Tuples.pair(4, 3),
Tuples.pair(5, 4),
Tuples.pair(5, 5),
Tuples.pair(5, 6)).toImmutable();
ImmutableSortedSet<Pair<Integer, Integer>> actual2 = integersNoComparator.zipWithIndex();
Assert.assertEquals(expected2, actual2);
}
@Override
@Test(expected = IllegalArgumentException.class)
public void chunk_zero_throws()
{
this.classUnderTest().chunk(0);
}
@Test
public void chunk_large_size()
{
Assert.assertEquals(this.classUnderTest(), this.classUnderTest().chunk(10).getFirst());
Verify.assertInstanceOf(ImmutableSortedBag.class, this.classUnderTest().chunk(10).getFirst());
}
@Override
@Test
public void detect()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.detect(Predicates.equal(1)));
Assert.assertNull(integers.detect(Predicates.equal(integers.size() + 1)));
}
@Override
@Test
public void detectWith()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.detectWith(Object::equals, Integer.valueOf(1)));
Assert.assertNull(integers.detectWith(Object::equals, Integer.valueOf(integers.size() + 1)));
}
@Override
@Test
public void detectWithIfNone()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Function0<Integer> function = new PassThruFunction0<Integer>(integers.size() + 1);
Integer sum = Integer.valueOf(integers.size() + 1);
Assert.assertEquals(Integer.valueOf(1), integers.detectWithIfNone(Object::equals, Integer.valueOf(1), function));
Assert.assertEquals(Integer.valueOf(integers.size() + 1), integers.detectWithIfNone(Object::equals, sum, function));
}
@Override
@Test
public void detectIfNone()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Function0<Integer> function = new PassThruFunction0<Integer>(integers.size() + 1);
Assert.assertEquals(Integer.valueOf(1), integers.detectIfNone(Predicates.equal(1), function));
Assert.assertEquals(Integer.valueOf(integers.size() + 1), integers.detectIfNone(Predicates.equal(integers.size() + 1), function));
}
@Override
@Test
public void allSatisfy()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertTrue(integers.allSatisfy(Integer.class::isInstance));
Assert.assertFalse(integers.allSatisfy(Integer.valueOf(0)::equals));
}
@Override
@Test
public void anySatisfy()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertFalse(integers.anySatisfy(String.class::isInstance));
Assert.assertTrue(integers.anySatisfy(Integer.class::isInstance));
}
@Override
@Test
public void count()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(integers.size(), integers.count(Integer.class::isInstance));
Assert.assertEquals(0, integers.count(String.class::isInstance));
}
@Override
@Test
public void collectIf()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
ImmutableList<Integer> integers1 = integers.collectIf(Integer.class::isInstance, Functions.getIntegerPassThru());
Verify.assertListsEqual(integers.toList(), integers1.toList());
}
@Test
public void collectIfToTarget()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
HashBag<Integer> actual = integers.collectIf(Integer.class::isInstance, Functions.getIntegerPassThru(), HashBag.<Integer>newBag());
Assert.assertEquals(integers.toBag(), actual);
}
@Override
@Test
public void getFirst()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(1), integers.getFirst());
ImmutableSortedBag<Integer> revInt = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(Integer.valueOf(2), revInt.getFirst());
}
@Override
@Test
public void getLast()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Assert.assertEquals(Integer.valueOf(2), integers.getLast());
ImmutableSortedBag<Integer> revInt = this.classUnderTest(Collections.<Integer>reverseOrder());
Assert.assertEquals(Integer.valueOf(1), revInt.getLast());
}
@Override
@Test
public void isEmpty()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest();
Assert.assertFalse(bag.isEmpty());
Assert.assertTrue(bag.notEmpty());
}
@Override
@Test
public void iterator()
{
ImmutableSortedBag<Integer> integers = SortedBags.immutable.of(1, 2, 3, 4);
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++)
{
Integer integer = iterator.next();
Assert.assertEquals(i + 1, integer.intValue());
}
Verify.assertThrows(NoSuchElementException.class, (Runnable) iterator::next);
Iterator<Integer> intItr = integers.iterator();
intItr.next();
Verify.assertThrows(UnsupportedOperationException.class, intItr::remove);
}
@Override
@Test
public void injectInto()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
Integer result = integers.injectInto(0, AddFunction.INTEGER);
Assert.assertEquals(FastList.newList(integers).injectInto(0, AddFunction.INTEGER_TO_INT), result.intValue());
}
@Override
@Test
public void toArray()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableList<Integer> copy = FastList.newList(integers);
Assert.assertArrayEquals(integers.toArray(), copy.toArray());
Assert.assertArrayEquals(integers.toArray(new Integer[integers.size()]), copy.toArray(new Integer[integers.size()]));
Assert.assertArrayEquals(integers.toArray(new Integer[integers.size() - 1]), copy.toArray(new Integer[integers.size() - 1]));
Assert.assertArrayEquals(integers.toArray(new Integer[integers.size() + 1]), copy.toArray(new Integer[integers.size() + 1]));
}
@Override
@Test
public void testToString()
{
Assert.assertEquals(FastList.newList(this.classUnderTest()).toString(), this.classUnderTest().toString());
}
@Override
@Test
public void makeString()
{
Assert.assertEquals(FastList.newList(this.classUnderTest()).makeString(), this.classUnderTest().makeString());
}
@Override
@Test
public void appendString()
{
Appendable builder = new StringBuilder();
this.classUnderTest().appendString(builder);
Assert.assertEquals(FastList.newList(this.classUnderTest()).makeString(), builder.toString());
}
@Test
public void toList()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableList<Integer> list = integers.toList();
Verify.assertEqualsAndHashCode(FastList.newList(integers), list);
}
@Override
@Test
public void toSortedList()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableList<Integer> copy = FastList.newList(integers);
MutableList<Integer> list = integers.toSortedList(Collections.<Integer>reverseOrder());
Assert.assertEquals(copy.sortThis(Collections.<Integer>reverseOrder()), list);
MutableList<Integer> list2 = integers.toSortedList();
Verify.assertListsEqual(copy.sortThis(), list2);
}
@Test
public void toSortedListBy()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableList<Integer> list = integers.toSortedListBy(String::valueOf);
Assert.assertEquals(integers.toList(), list);
}
@Test
public void toSortedBag()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Collections.<Integer>reverseOrder());
MutableSortedBag<Integer> bag = integers.toSortedBag();
Verify.assertSortedBagsEqual(TreeBag.newBagWith(1, 1, 1, 2), bag);
}
@Test
public void toSortedBagWithComparator()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableSortedBag<Integer> bag = integers.toSortedBag(Collections.<Integer>reverseOrder());
Assert.assertEquals(integers.toBag(), bag);
Assert.assertEquals(integers.toSortedList(Comparators.<Integer>reverseNaturalOrder()), bag.toList());
}
@Test
public void toSortedBagBy()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableSortedBag<Integer> bag = integers.toSortedBagBy(String::valueOf);
Verify.assertSortedBagsEqual(TreeBag.newBag(integers), bag);
}
@Test
public void toSortedMap()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableSortedMap<Integer, String> map = integers.toSortedMap(Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(integers.toMap(Functions.getIntegerPassThru(), String::valueOf), map);
Verify.assertListsEqual(FastList.newListWith(1, 2), map.keySet().toList());
}
@Test
public void toSortedMap_with_comparator()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest();
MutableSortedMap<Integer, String> map = integers.toSortedMap(Comparators.<Integer>reverseNaturalOrder(),
Functions.getIntegerPassThru(), String::valueOf);
Verify.assertMapsEqual(integers.toMap(Functions.getIntegerPassThru(), String::valueOf), map);
Verify.assertListsEqual(FastList.newListWith(2, 1), map.keySet().toList());
}
@Override
@Test
public void forLoop()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest();
for (Integer each : bag)
{
Assert.assertNotNull(each);
}
}
@Test
public void toMapOfItemToCount()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Collections.reverseOrder(), 1, 2, 2, 3, 3, 3);
MutableSortedMap<Integer, Integer> expected = TreeSortedMap.newMapWith(Collections.reverseOrder(), 1, 1, 2, 2, 3, 3);
MutableSortedMap<Integer, Integer> actual = bag.toMapOfItemToCount();
Assert.assertEquals(expected, actual);
Assert.assertSame(bag.comparator(), actual.comparator());
}
@Override
@Test
public void min()
{
Assert.assertEquals(Integer.valueOf(2), this.classUnderTest().min(Comparators.reverseNaturalOrder()));
}
@Override
@Test
public void max()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().max(Comparators.reverseNaturalOrder()));
}
@Override
@Test
public void min_without_comparator()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().min());
}
@Override
@Test
public void max_without_comparator()
{
Assert.assertEquals(Integer.valueOf(2), this.classUnderTest().max());
}
@Override
@Test
public void minBy()
{
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest().minBy(String::valueOf));
Assert.assertEquals(Integer.valueOf(1), this.classUnderTest(Comparator.<Integer>reverseOrder()).minBy(String::valueOf));
}
@Override
@Test
public void maxBy()
{
Assert.assertEquals(Integer.valueOf(2), this.classUnderTest().maxBy(String::valueOf));
}
@Test
public void groupBy()
{
ImmutableSortedBag<Integer> undertest = this.classUnderTest(Comparators.reverseNaturalOrder());
ImmutableSortedBagMultimap<Integer, Integer> actual = undertest.groupBy(Functions.<Integer>getPassThru());
ImmutableSortedBagMultimap<Integer, Integer> expected = TreeBag.newBag(undertest).groupBy(Functions.<Integer>getPassThru()).toImmutable();
Assert.assertEquals(expected, actual);
Assert.assertSame(Comparators.reverseNaturalOrder(), actual.comparator());
}
@Test
public void groupByEach()
{
ImmutableSortedBag<Integer> undertest = this.classUnderTest(Collections.<Integer>reverseOrder());
NegativeIntervalFunction function = new NegativeIntervalFunction();
ImmutableSortedBagMultimap<Integer, Integer> actual = undertest.groupByEach(function);
ImmutableSortedBagMultimap<Integer, Integer> expected = TreeBag.newBag(undertest).groupByEach(function).toImmutable();
Assert.assertEquals(expected, actual);
Assert.assertSame(Collections.reverseOrder(), actual.comparator());
}
@Test
public void groupByWithTarget()
{
ImmutableSortedBag<Integer> undertest = this.classUnderTest(Comparators.reverseNaturalOrder());
TreeBagMultimap<Integer, Integer> actual = undertest.groupBy(Functions.<Integer>getPassThru(), TreeBagMultimap.<Integer, Integer>newMultimap());
TreeBagMultimap<Integer, Integer> expected = TreeBag.newBag(undertest).groupBy(Functions.<Integer>getPassThru());
Assert.assertEquals(expected, actual);
}
@Test
public void groupByEachWithTarget()
{
ImmutableSortedBag<Integer> undertest = this.classUnderTest();
NegativeIntervalFunction function = new NegativeIntervalFunction();
TreeBagMultimap<Integer, Integer> actual = undertest.groupByEach(function, TreeBagMultimap.<Integer, Integer>newMultimap());
TreeBagMultimap<Integer, Integer> expected = TreeBag.newBag(undertest).groupByEach(function);
Assert.assertEquals(expected, actual);
}
@Test
public void groupByUniqueKey()
{
ImmutableSortedBag<Integer> bag1 = this.newWith(1, 2, 3);
Assert.assertEquals(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), bag1.groupByUniqueKey(id -> id));
ImmutableSortedBag<Integer> bag2 = this.classUnderTest(Comparators.reverseNaturalOrder());
Verify.assertThrows(IllegalStateException.class, () -> bag2.groupByUniqueKey(id -> id));
}
@Test
public void groupByUniqueKey_target()
{
ImmutableSortedBag<Integer> bag1 = this.newWith(1, 2, 3);
Assert.assertEquals(
UnifiedMap.newWithKeysValues(0, 0, 1, 1, 2, 2, 3, 3),
bag1.groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(0, 0)));
ImmutableSortedBag<Integer> bag2 = this.newWith(1, 2, 3);
Verify.assertThrows(IllegalStateException.class, () -> bag2.groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(2, 2)));
}
@Test
public void distinct()
{
ImmutableSortedBag<Integer> bag1 = this.classUnderTest();
Assert.assertEquals(SortedSets.immutable.of(1, 2), bag1.distinct());
ImmutableSortedBag<Integer> bag2 = this.classUnderTest(Comparators.reverseNaturalOrder());
ImmutableSortedSet<Integer> expected = SortedSets.immutable.of(Comparators.reverseNaturalOrder(), 1, 2);
ImmutableSortedSet<Integer> actual = bag2.distinct();
Assert.assertEquals(expected, actual);
Assert.assertSame(expected.comparator(), actual.comparator());
}
@Test
public void toStack()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest(Comparators.reverseNaturalOrder());
Assert.assertEquals(ArrayStack.newStackWith(2, 1, 1, 1), bag.toStack());
}
@Override
@Test
public void collectBoolean()
{
ImmutableSortedBag<String> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), "true", "nah", "TrUe");
Assert.assertEquals(
BooleanArrayList.newListWith(true, false, true),
bag.collectBoolean(Boolean::parseBoolean));
}
@Override
@Test
public void collectByte()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ByteArrayList.newListWith((byte) 3, (byte) 2, (byte) 1, (byte) 1, (byte) 1),
bag.collectByte(PrimitiveFunctions.unboxIntegerToByte()));
}
@Override
@Test
public void collectChar()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
CharArrayList.newListWith((char) 3, (char) 2, (char) 1, (char) 1, (char) 1),
bag.collectChar(PrimitiveFunctions.unboxIntegerToChar()));
}
@Override
@Test
public void collectDouble()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
DoubleArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectDouble(PrimitiveFunctions.unboxIntegerToDouble()));
}
@Override
@Test
public void collectFloat()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
FloatArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectFloat(PrimitiveFunctions.unboxIntegerToFloat()));
}
@Override
@Test
public void collectInt()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
IntArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectInt(PrimitiveFunctions.unboxIntegerToInt()));
}
@Override
@Test
public void collectLong()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
LongArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectLong(PrimitiveFunctions.unboxIntegerToLong()));
}
@Override
@Test
public void collectShort()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ShortArrayList.newListWith((short) 3, (short) 2, (short) 1, (short) 1, (short) 1),
bag.collectShort(PrimitiveFunctions.unboxIntegerToShort()));
}
@Test
public void collectBoolean_target()
{
ImmutableSortedBag<String> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), "true", "nah", "TrUe");
Assert.assertEquals(
BooleanArrayList.newListWith(true, false, true),
bag.collectBoolean(Boolean::parseBoolean, new BooleanArrayList()));
ImmutableSortedBag<String> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), "true", "nah", "TrUe");
Assert.assertEquals(
BooleanHashBag.newBagWith(true, false, true),
bag2.collectBoolean(Boolean::parseBoolean, new BooleanHashBag()));
}
@Test
public void collectByte_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ByteArrayList.newListWith((byte) 3, (byte) 2, (byte) 1, (byte) 1, (byte) 1),
bag.collectByte(PrimitiveFunctions.unboxIntegerToByte(), new ByteArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ByteHashBag.newBagWith((byte) 3, (byte) 2, (byte) 1, (byte) 1, (byte) 1),
bag2.collectByte(PrimitiveFunctions.unboxIntegerToByte(), new ByteHashBag()));
}
@Test
public void collectChar_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
CharArrayList.newListWith((char) 3, (char) 2, (char) 1, (char) 1, (char) 1),
bag.collectChar(PrimitiveFunctions.unboxIntegerToChar(), new CharArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
CharHashBag.newBagWith((char) 3, (char) 2, (char) 1, (char) 1, (char) 1),
bag2.collectChar(PrimitiveFunctions.unboxIntegerToChar(), new CharHashBag()));
}
@Test
public void collectDouble_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
DoubleArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectDouble(PrimitiveFunctions.unboxIntegerToDouble(), new DoubleArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
DoubleHashBag.newBagWith(3, 2, 1, 1, 1),
bag2.collectDouble(PrimitiveFunctions.unboxIntegerToDouble(), new DoubleHashBag()));
}
@Test
public void collectFloat_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
FloatArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectFloat(PrimitiveFunctions.unboxIntegerToFloat(), new FloatArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
FloatHashBag.newBagWith(3, 2, 1, 1, 1),
bag2.collectFloat(PrimitiveFunctions.unboxIntegerToFloat(), new FloatHashBag()));
}
@Test
public void collectInt_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
IntArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectInt(PrimitiveFunctions.unboxIntegerToInt(), new IntArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
IntHashBag.newBagWith(3, 2, 1, 1, 1),
bag2.collectInt(PrimitiveFunctions.unboxIntegerToInt(), new IntHashBag()));
}
@Test
public void collectLong_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
LongArrayList.newListWith(3, 2, 1, 1, 1),
bag.collectLong(PrimitiveFunctions.unboxIntegerToLong(), new LongArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
LongHashBag.newBagWith(3, 2, 1, 1, 1),
bag2.collectLong(PrimitiveFunctions.unboxIntegerToLong(), new LongHashBag()));
}
@Test
public void collectShort_target()
{
ImmutableSortedBag<Integer> bag = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ShortArrayList.newListWith((short) 3, (short) 2, (short) 1, (short) 1, (short) 1),
bag.collectShort(PrimitiveFunctions.unboxIntegerToShort(), new ShortArrayList()));
ImmutableSortedBag<Integer> bag2 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 1, 1, 1, 2, 3);
Assert.assertEquals(
ShortHashBag.newBagWith((short) 3, (short) 2, (short) 1, (short) 1, (short) 1),
bag2.collectShort(PrimitiveFunctions.unboxIntegerToShort(), new ShortHashBag()));
}
@Test
public void occurrencesOf()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest();
Assert.assertEquals(0, bag.occurrencesOf(5));
Assert.assertEquals(3, bag.occurrencesOf(1));
Assert.assertEquals(1, bag.occurrencesOf(2));
}
@Test
public void toImmutable()
{
ImmutableSortedBag<Integer> bag = this.classUnderTest();
ImmutableSortedBag<Integer> actual = bag.toImmutable();
Assert.assertEquals(bag, actual);
Assert.assertSame(bag, actual);
}
@Test
public void forEachFromTo()
{
MutableSortedBag<Integer> integersMutable = SortedBags.mutable.of(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1);
ImmutableSortedBag<Integer> integers1 = integersMutable.toImmutable();
MutableList<Integer> result = Lists.mutable.empty();
integers1.forEach(5, 7, result::add);
Assert.assertEquals(Lists.immutable.with(3, 3, 2), result);
MutableList<Integer> result2 = Lists.mutable.empty();
integers1.forEach(5, 5, result2::add);
Assert.assertEquals(Lists.immutable.with(3), result2);
MutableList<Integer> result3 = Lists.mutable.empty();
integers1.forEach(0, 9, result3::add);
Assert.assertEquals(Lists.immutable.with(4, 4, 4, 4, 3, 3, 3, 2, 2, 1), result3);
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers1.forEach(-1, 0, result::add));
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers1.forEach(0, -1, result::add));
Verify.assertThrows(IllegalArgumentException.class, () -> integers1.forEach(7, 5, result::add));
ImmutableSortedBag<Integer> integers2 = this.classUnderTest();
MutableList<Integer> mutableList = Lists.mutable.of();
integers2.forEach(0, integers2.size() - 1, mutableList::add);
Assert.assertEquals(this.classUnderTest().toList(), mutableList);
}
@Test
public void forEachWithIndexWithFromTo()
{
ImmutableSortedBag<Integer> integers1 = SortedBags.immutable.of(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1);
StringBuilder builder = new StringBuilder();
integers1.forEachWithIndex(5, 7, (each, index) -> builder.append(each).append(index));
Assert.assertEquals("353627", builder.toString());
StringBuilder builder2 = new StringBuilder();
integers1.forEachWithIndex(5, 5, (each, index) -> builder2.append(each).append(index));
Assert.assertEquals("35", builder2.toString());
StringBuilder builder3 = new StringBuilder();
integers1.forEachWithIndex(0, 9, (each, index) -> builder3.append(each).append(index));
Assert.assertEquals("40414243343536272819", builder3.toString());
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers1.forEachWithIndex(-1, 0, new AddToList(Lists.mutable.empty())));
Verify.assertThrows(IndexOutOfBoundsException.class, () -> integers1.forEachWithIndex(0, -1, new AddToList(Lists.mutable.empty())));
Verify.assertThrows(IllegalArgumentException.class, () -> integers1.forEachWithIndex(7, 5, new AddToList(Lists.mutable.empty())));
ImmutableSortedBag<Integer> integers2 = this.classUnderTest();
MutableList<Integer> mutableList1 = Lists.mutable.of();
integers2.forEachWithIndex(0, integers2.size() - 1, (each, index) -> mutableList1.add(each + index));
MutableList<Integer> result = Lists.mutable.of();
Lists.mutable.ofAll(integers2).forEachWithIndex(0, integers2.size() - 1, (each, index) -> result.add(each + index));
Assert.assertEquals(result, mutableList1);
}
@Test
public void topOccurrences()
{
ImmutableSortedBag<String> strings = this.newWithOccurrences(
PrimitiveTuples.pair("one", 1),
PrimitiveTuples.pair("two", 2),
PrimitiveTuples.pair("three", 3),
PrimitiveTuples.pair("four", 4),
PrimitiveTuples.pair("five", 5),
PrimitiveTuples.pair("six", 6),
PrimitiveTuples.pair("seven", 7),
PrimitiveTuples.pair("eight", 8),
PrimitiveTuples.pair("nine", 9),
PrimitiveTuples.pair("ten", 10));
ListIterable<ObjectIntPair<String>> top5 = strings.topOccurrences(5);
Assert.assertEquals(5, top5.size());
Assert.assertEquals("ten", top5.getFirst().getOne());
Assert.assertEquals(10, top5.getFirst().getTwo());
Assert.assertEquals("six", top5.getLast().getOne());
Assert.assertEquals(6, top5.getLast().getTwo());
Assert.assertEquals(0, this.newWith().topOccurrences(5).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(5).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(1).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(2).size());
Assert.assertEquals(3, this.newWith("one", "one", "two", "three").topOccurrences(2).size());
Assert.assertEquals(2, this.newWith("one", "one", "two", "two", "three").topOccurrences(1).size());
Assert.assertEquals(3, this.newWith("one", "one", "two", "two", "three", "three").topOccurrences(1).size());
Assert.assertEquals(0, this.newWith().topOccurrences(0).size());
Assert.assertEquals(0, this.newWith("one").topOccurrences(0).size());
Verify.assertThrows(IllegalArgumentException.class, () -> this.newWith().topOccurrences(-1));
}
@Test
public void bottomOccurrences()
{
ImmutableSortedBag<String> strings = this.newWithOccurrences(
PrimitiveTuples.pair("one", 1),
PrimitiveTuples.pair("two", 2),
PrimitiveTuples.pair("three", 3),
PrimitiveTuples.pair("four", 4),
PrimitiveTuples.pair("five", 5),
PrimitiveTuples.pair("six", 6),
PrimitiveTuples.pair("seven", 7),
PrimitiveTuples.pair("eight", 8),
PrimitiveTuples.pair("nine", 9),
PrimitiveTuples.pair("ten", 10));
ListIterable<ObjectIntPair<String>> bottom5 = strings.bottomOccurrences(5);
Assert.assertEquals(5, bottom5.size());
Assert.assertEquals("one", bottom5.getFirst().getOne());
Assert.assertEquals(1, bottom5.getFirst().getTwo());
Assert.assertEquals("five", bottom5.getLast().getOne());
Assert.assertEquals(5, bottom5.getLast().getTwo());
Assert.assertEquals(0, this.newWith().bottomOccurrences(5).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(5).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(1).size());
Assert.assertEquals(3, this.newWith("one", "two", "three").topOccurrences(2).size());
Assert.assertEquals(3, this.newWith("one", "one", "two", "three").topOccurrences(2).size());
Assert.assertEquals(2, this.newWith("one", "one", "two", "two", "three").topOccurrences(1).size());
Assert.assertEquals(3, this.newWith("one", "one", "two", "two", "three", "three").bottomOccurrences(1).size());
Assert.assertEquals(0, this.newWith().bottomOccurrences(0).size());
Assert.assertEquals(0, this.newWith("one").bottomOccurrences(0).size());
Verify.assertThrows(IllegalArgumentException.class, () -> this.newWith().bottomOccurrences(-1));
}
@Test
public void corresponds()
{
Assert.assertFalse(this.newWith(1, 2, 3, 4, 5).corresponds(this.newWith(1, 2, 3, 4), Predicates2.alwaysTrue()));
ImmutableSortedBag<Integer> integers1 = this.newWith(1, 2, 2, 3, 3, 3, 4, 4, 4, 4);
MutableList<Integer> integers2 = FastList.newListWith(2, 3, 3, 4, 4, 4, 5, 5, 5, 5);
Assert.assertTrue(integers1.corresponds(integers2, Predicates2.lessThan()));
Assert.assertFalse(integers1.corresponds(integers2, Predicates2.greaterThan()));
ImmutableSortedBag<Integer> integers3 = this.newWith(1, 2, 3, 4);
MutableSortedSet<Integer> integers4 = SortedSets.mutable.of(2, 3, 4, 5);
Assert.assertTrue(integers1.corresponds(integers2, Predicates2.lessThan()));
Assert.assertFalse(integers3.corresponds(integers4, Predicates2.greaterThan()));
Assert.assertTrue(integers3.corresponds(integers4, Predicates2.lessThan()));
}
@Test
public void detectIndex()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Assert.assertEquals(0, integers.detectIndex(each -> each == 2));
ImmutableSortedBag<Integer> integers2 = this.classUnderTest();
Assert.assertEquals(-1, integers2.detectIndex(each -> each == 100));
}
@Test
public void indexOf()
{
ImmutableSortedBag<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder());
Assert.assertEquals(1, integers.indexOf(1));
Assert.assertEquals(1, integers.indexOf(1));
Assert.assertEquals(0, integers.indexOf(2));
Assert.assertEquals(-1, integers.indexOf(0));
Assert.assertEquals(-1, integers.indexOf(5));
}
@Test
public void take()
{
ImmutableSortedBag<Integer> integers1 = this.classUnderTest();
Assert.assertEquals(SortedBags.immutable.empty(integers1.comparator()), integers1.take(0));
Assert.assertSame(integers1.comparator(), integers1.take(0).comparator());
Assert.assertEquals(this.newWith(integers1.comparator(), 1, 1, 1), integers1.take(3));
Assert.assertSame(integers1.comparator(), integers1.take(3).comparator());
Assert.assertEquals(this.newWith(integers1.comparator(), 1, 1, 1), integers1.take(integers1.size() - 1));
ImmutableSortedBag<Integer> integers2 = this.newWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2, 1);
Assert.assertSame(integers2, integers2.take(integers2.size()));
Assert.assertSame(integers2, integers2.take(10));
Assert.assertSame(integers2, integers2.take(Integer.MAX_VALUE));
}
@Test(expected = IllegalArgumentException.class)
public void take_throws()
{
this.classUnderTest().take(-1);
}
@Test
public void drop()
{
ImmutableSortedBag<Integer> integers1 = this.classUnderTest();
Assert.assertSame(integers1, integers1.drop(0));
Assert.assertEquals(this.newWith(integers1.comparator(), 2), integers1.drop(3));
Assert.assertEquals(this.newWith(integers1.comparator(), 2), integers1.drop(integers1.size() - 1));
Assert.assertEquals(SortedBags.immutable.empty(integers1.comparator()), integers1.drop(integers1.size()));
Assert.assertEquals(SortedBags.immutable.empty(integers1.comparator()), integers1.drop(10));
Assert.assertEquals(SortedBags.immutable.empty(integers1.comparator()), integers1.drop(Integer.MAX_VALUE));
}
@Test(expected = IllegalArgumentException.class)
public void drop_throws()
{
this.classUnderTest().drop(-1);
}
private static final class Holder
{
private final int number;
private Holder(int i)
{
this.number = i;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || this.getClass() != o.getClass())
{
return false;
}
Holder holder = (Holder) o;
return this.number == holder.number;
}
@Override
public int hashCode()
{
return this.number;
}
@Override
public String toString()
{
return String.valueOf(this.number);
}
}
}
| |
/*
* Copyright (C) 2014 The Retro Band - Open source smart band project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hardcopy.retroband.contents;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import com.hardcopy.retroband.logic.Analyzer;
import com.hardcopy.retroband.utils.Logs;
import android.content.Context;
import android.database.Cursor;
import android.text.format.Time;
public class ContentManager {
private static final String TAG = "ContentManager";
public static final int RESPONSE_INVALID_PARAMETER = -1;
public static final int RESPONSE_NO_MATCHING_CONTENT = -2;
public static final int RESPONSE_OBJECT_ADDED = 11;
public static final int RESPONSE_OBJECT_UPDATED = 12;
public static final int RESPONSE_OBJECT_DELETED = 13;
public static final int REPORT_TYPE_YEAR = 1;
public static final int REPORT_TYPE_MONTH = 2;
public static final int REPORT_TYPE_DAY = 3;
public static final int REPORT_TYPE_HOUR = 4;
private static ContentManager mContentManager = null; // Singleton pattern
private Context mContext;
private IContentManagerListener mContentManagerListener;
private DBHelper mDB = null;
private ArrayList<ContentObject> mContentList; // Cache content objects
// Time parameters
private static final int REPORT_INTERVAL = 1000;
private static final int REPORT_SAMPLING_TIME = 50;
private long mPreviousProcessTime = 0;
// Activity statistics
// WARNING: Date parameter is the zero-based number
// because we use parameters as array index
private int mThisYear = -1;
private int mThisMonth = -1; // (in the range [0,11])
private int[] mMonthArray = new int[12];
private int mThisDay = -1; // (in the range [0,30])
private int[] mDayArray = new int[31];
private int mThisHour = -1; // (in the range [0,23])
private int[] mHourArray = new int[24];
private int mThisMinute = -1; // (in the range [0,59])
private int[] mMinuteArray = new int[60];
/**
* Constructor
*/
private ContentManager(Context c, IContentManagerListener l) {
mContext = c;
mContentManagerListener = l;
mContentList = new ArrayList<ContentObject>();
//----- Make DB helper
if(mDB == null) {
mDB = new DBHelper(mContext).openWritable();
}
//----- Initialize activity data
initializeActivityParams();
getCurrentReportsFromDB();
}
/**
* Singleton pattern
*/
public synchronized static ContentManager getInstance(Context c, IContentManagerListener l) {
if(mContentManager == null)
mContentManager = new ContentManager(c, l);
return mContentManager;
}
public synchronized void finalize() {
if(mDB != null) {
mDB.close();
mDB = null;
}
if(mContentList != null)
mContentList.clear();
mContentManager = null;
}
/*****************************************************
* Private methods
******************************************************/
private void initializeBuffer() {
Arrays.fill(mMonthArray, 0x00000000);
Arrays.fill(mDayArray, 0x00000000);
Arrays.fill(mHourArray, 0x00000000);
Arrays.fill(mMinuteArray, 0x00000000);
}
private void initializeActivityParams() {
initializeBuffer();
Calendar cal = Calendar.getInstance();
mThisYear = cal.get(Calendar.YEAR);
mThisMonth = cal.get(Calendar.MONTH); // 0~11
mThisDay = cal.get(Calendar.DAY_OF_MONTH) - 1; // convert to 0~30
mThisHour = cal.get(Calendar.HOUR_OF_DAY); // 0~23
mThisMinute = cal.get(Calendar.MINUTE); // 0~59
}
/**
* Make sum of calorie at this month, day, hour.
*/
private void getCurrentReportsFromDB() {
// Get month data in this year
Cursor c = mDB.selectReportWithDate(REPORT_TYPE_MONTH, mThisYear, -1, -1, -1);
if(c != null) {
getDataFromCursor(MODE_CURRENT_TIME, REPORT_TYPE_MONTH, c);
c.close();
}
// Get day data in this month
c = mDB.selectReportWithDate(REPORT_TYPE_DAY, mThisYear, mThisMonth, -1, -1);
if(c != null) {
getDataFromCursor(MODE_CURRENT_TIME, REPORT_TYPE_DAY, c);
c.close();
}
// Get hour data in this day
c = mDB.selectReportWithDate(REPORT_TYPE_HOUR, mThisYear, mThisMonth, mThisDay, -1);
if(c != null) {
getDataFromCursor(MODE_CURRENT_TIME, REPORT_TYPE_HOUR, c);
c.close();
}
}
/**
* Load sum of calorie from DB
*/
private int[] getReportsFromDB(int type, int year, int month, int day, int hour) {
int[] timeArray = null;
// Get month data in this year
Cursor c = mDB.selectReportWithDate(type, year, month, day, hour);
if(c != null) {
timeArray = getDataFromCursor(MODE_SELECTED_TIME, type, c);
c.close();
}
return timeArray;
}
public static final int MODE_CURRENT_TIME = 1;
public static final int MODE_SELECTED_TIME = 2;
/**
* Parse cursor and make cache
* @param mode Make cache based on current time or specified time
* @param type REPORT_TYPE_MONTH or REPORT_TYPE_DAY or REPORT_TYPE_HOUR
* @param c Cursor
* @return int[] Parsed result array
*/
private int[] getDataFromCursor(int mode, int type, Cursor c) {
int[] timeArray = null;
int columnIndex = 0;
switch(type) {
case REPORT_TYPE_MONTH:
if(mode == MODE_CURRENT_TIME) {
timeArray = mMonthArray;
} else {
timeArray = new int[12];
Arrays.fill(timeArray, 0x00000000);
}
columnIndex = DBHelper.INDEX_ACCEL_MONTH;
break;
case REPORT_TYPE_DAY:
if(mode == MODE_CURRENT_TIME) {
timeArray = mDayArray;
} else {
timeArray = new int[31];
Arrays.fill(timeArray, 0x00000000);
}
columnIndex = DBHelper.INDEX_ACCEL_DAY;
break;
case REPORT_TYPE_HOUR:
if(mode == MODE_CURRENT_TIME) {
timeArray = mHourArray;
} else {
timeArray = new int[24];
Arrays.fill(timeArray, 0x00000000);
}
columnIndex = DBHelper.INDEX_ACCEL_HOUR;
break;
default:
return null;
}
if(c != null && c.getCount() > 0) {
c.moveToFirst();
while(!c.isAfterLast()) {
int index = c.getInt(columnIndex);
int calorie = c.getInt(DBHelper.INDEX_ACCEL_DATA1);
if(calorie > 0 && index > -1 && index < timeArray.length) {
timeArray[index] = calorie;
}
c.moveToNext();
}
}
return timeArray;
}
/**
* Add newly received data to cache and write on DB if needed
* @param ar Raw accel data from remote
*/
private void addActivityReport(ActivityReport ar) {
if(ar != null) {
boolean isTimeChanged = false;
Calendar cal = Calendar.getInstance();
int prevYear = mThisYear;
int prevMonth = mThisMonth;
int prevDay = mThisDay;
int prevHour = mThisHour;
// Add calorie to buffer
if(mThisMonth != cal.get(Calendar.MONTH)) {
// Push monthly report to DB
Time tempTime = new Time();
tempTime.set(1, 0, 0, 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis = tempTime.toMillis(true);
pushReportToDB(REPORT_TYPE_MONTH, millis, prevYear, prevMonth, 1, 0);
// Set new date
mThisYear = cal.get(Calendar.YEAR);
mThisMonth = cal.get(Calendar.MONTH);
if(mThisMonth == Calendar.JANUARY)
Arrays.fill(mMonthArray, 0x00000000);
isTimeChanged = true;
}
mMonthArray[mThisMonth] += ar.mCalorie;
if(mThisDay != cal.get(Calendar.DAY_OF_MONTH) - 1 || isTimeChanged) {
// Push daily report to DB
Time tempTime = new Time();
tempTime.set(1, 0, 0, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis = tempTime.toMillis(true);
pushReportToDB(REPORT_TYPE_DAY, millis, prevYear, prevMonth, prevDay, 0);
if(isTimeChanged) {
// Month changed !!
Arrays.fill(mDayArray, 0x00000000);
} else {
// Month is not changed but day changed
}
mThisDay = cal.get(Calendar.DAY_OF_MONTH) - 1;
isTimeChanged = true;
}
mDayArray[mThisDay] += ar.mCalorie;
if(mThisHour != cal.get(Calendar.HOUR_OF_DAY) || isTimeChanged) {
// Push hourly report to DB
Time tempTime = new Time();
tempTime.set(1, 0, prevHour, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis = tempTime.toMillis(true);
pushReportToDB(REPORT_TYPE_HOUR, millis, prevYear, prevMonth, prevDay, prevHour);
if(isTimeChanged) {
// Day changed !!
Arrays.fill(mHourArray, 0x00000000);
} else {
// Day is not changed but hour changed
}
mThisHour = cal.get(Calendar.HOUR_OF_DAY);
isTimeChanged = true;
}
mHourArray[mThisHour] += ar.mCalorie;
if(isTimeChanged || mThisMinute != cal.get(Calendar.MINUTE)) {
if(isTimeChanged) {
// Hour changed !!
Arrays.fill(mMinuteArray, 0x00000000);
} else {
// Hour is not changed but minute changed
}
// Add to new minute buffer
mThisMinute = cal.get(Calendar.MINUTE);
}
mMinuteArray[mThisMinute] += ar.mCalorie;
} // end of if(ar != null)
}
/**
* Write sum of calorie on DB
* @param type REPORT_TYPE_YEAR, REPORT_TYPE_MONTH, REPORT_TYPE_DAY, REPORT_TYPE_HOUR
* @param time time in milli-second
* @param year
* @param month
* @param day
* @param hour
*/
private void pushReportToDB(int type, long time, int year, int month, int day, int hour) {
int calorie = 0;
switch(type) {
case REPORT_TYPE_YEAR:
// Not available
return;
case REPORT_TYPE_MONTH:
if(month > -1 && month < mMonthArray.length) {
calorie = mMonthArray[month];
} else {
return;
}
break;
case REPORT_TYPE_DAY:
if(day > -1 && day < mDayArray.length) {
calorie = mDayArray[day];
} else {
return;
}
break;
case REPORT_TYPE_HOUR:
if(hour > -1 && hour < mHourArray.length) {
calorie = mHourArray[hour];
} else {
return;
}
break;
}
if(calorie < 1)
return;
// Make data array to save
// We use only one information, calorie.
int[] dataArray = new int[5];
Arrays.fill(dataArray, 0x00000000);
dataArray[0] = calorie;
mDB.insertActivityReport(type, time, year, month, day, hour, dataArray, null);
}
/*****************************************************
* Public methods
******************************************************/
public void setListener(IContentManagerListener l) {
mContentManagerListener = l;
}
/**
* Save sum of calorie cache to DB
*/
public void saveCurrentActivityReport() {
int prevYear = mThisYear;
int prevMonth = mThisMonth;
int prevDay = mThisDay;
int prevHour = mThisHour;
// Push monthly report to DB
Time tempTime1 = new Time();
tempTime1.set(1, 0, 0, 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis1 = tempTime1.toMillis(true);
pushReportToDB(REPORT_TYPE_MONTH, millis1, prevYear, prevMonth, 1, 0);
// Push daily report to DB
Time tempTime2 = new Time();
tempTime2.set(1, 0, 0, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis2 = tempTime2.toMillis(true);
pushReportToDB(REPORT_TYPE_DAY, millis2, prevYear, prevMonth, prevDay, 0);
// Push hourly report to DB
Time tempTime3 = new Time();
tempTime3.set(1, 0, prevHour, prevDay + 1, prevMonth, prevYear); // convert day: in the range [1,31], month: in the range [0,11]
long millis3 = tempTime3.toMillis(true);
pushReportToDB(REPORT_TYPE_HOUR, millis3, prevYear, prevMonth, prevDay, prevHour);
}
/**
* After parsing packets from remote, service calls this method with result object.
* This method analyze accel raw data and calculate walks, calories.
* And makes an activity report instance which has analyzed results.
* @param co content object which has accel raw data array
* @return activity report instance which has analyzed results.
*/
public synchronized ActivityReport addContentObject(ContentObject co) {
if(co == null) {
return null;
}
// Caching contents
mContentList.add(co);
// Get current time
long currentTime = System.currentTimeMillis();
if(mPreviousProcessTime < 1)
mPreviousProcessTime = currentTime;
// Analyze cached contents
ActivityReport ar = null;
if(currentTime - mPreviousProcessTime > REPORT_INTERVAL) {
Logs.d("#");
Logs.d("# before analyzer");
// Analyze accelerometer value and make report
ar = Analyzer.analyzeAccel(mContentList, REPORT_SAMPLING_TIME, REPORT_INTERVAL);
// Remember activity report
if(ar != null) {
addActivityReport(ar);
}
mPreviousProcessTime = currentTime;
mContentList.clear();
}
return ar;
}
/**
* Delete specified content object from cache and DB
* @param co_id content object ID
* @return result code
*/
public synchronized int deleteContentObject(int co_id) {
if(co_id < 0)
return RESPONSE_INVALID_PARAMETER;
// Remove from DB
mDB.deleteReportWithID(co_id);
// Remove cached
int count = 0;
for(int i = mContentList.size() - 1; i > -1; i--) {
ContentObject temp = mContentList.get(i);
if(temp.mId == co_id) {
mContentList.remove(i);
count++;
}
}
if(count < 1)
return RESPONSE_NO_MATCHING_CONTENT;
return RESPONSE_OBJECT_DELETED;
}
/**
* Delete all contents
* @return result code
*/
public synchronized int deleteContentsAll() {
// Remove from DB
mDB.deleteReportWithType(ContentObject.CONTENT_TYPE_ACCEL);
// Remove cached
mContentList.clear();
return RESPONSE_OBJECT_DELETED;
}
/**
* Returns cached activity data
* @param type time period type
* @return array of activity data
*/
public int[] getCurrentActivityData(int type) {
int[] activityData = null;
switch(type) {
case REPORT_TYPE_MONTH:
activityData = mMonthArray;
break;
case REPORT_TYPE_DAY:
activityData = mDayArray;
break;
case REPORT_TYPE_HOUR:
activityData = mHourArray;
break;
default:
break;
} // End of switch
return activityData;
}
/**
* Returns activity data from DB
* @param type time period type
* @param year
* @param month
* @param day
* @param hour
* @return array of activity data
*/
public int[] getActivityData(int type, int year, int month, int day, int hour) {
int[] activityData = null;
activityData = getReportsFromDB(type, year, month, day, hour);
return activityData;
}
}
| |
/**
*
*/
package io.spire;
import io.spire.api.Api;
import io.spire.api.Api.ApiDescriptionModel;
import io.spire.api.Api.ApiDescriptionModel.ApiSchemaModel;
import io.spire.api.Billing;
import io.spire.api.Capability;
import io.spire.api.Channel;
import io.spire.api.Resource;
import io.spire.api.Channel.Channels;
import io.spire.api.Subscription;
import io.spire.api.Subscription.Subscriptions;
import io.spire.api.Session;
import io.spire.request.ResponseException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Provides a main interface for authentication, session management,
* account management and creation different Spire resources
*
* <p>i.e.</p>
* <pre>
* {@code Spire spire = new Spire();}
* {@code spire.start(account_key) // starts a new session}
* </pre>
*
* <p>
* Instances of Spire are not safe for use by multiple threads.
* Instead, we recommend having multiple independent Spire instances per thread
* </p>
*
* @since 1.0
* @author Jorge Gonzalez
*
*/
@SuppressWarnings("deprecation")
public class Spire {
public static final String SPIRE_URL = "https://api.spire.io";
public static final Api SPIRE_API = new Api(SPIRE_URL);
private String spire_url;
private Api api;
private Session session;
private Billing billing;
/**
* Spire constructor
*
* Initialize spire object with default URL and API version
*/
public Spire(){
this.spire_url = SPIRE_URL;
this.api = SPIRE_API;
}
/**
* Spire constructor
*
* Initialize spire object with specified 'url' and default API 'version'
*
* @param url the Spire Api entry point
*/
public Spire(String url){
this.spire_url = url;
this.api = new Api(spire_url);
}
/**
* Spire constructor
*
* Initialize spire object with specified 'url' and API 'version'
*
* @param url the Spire Api entry point
* @param version Spire Api version
*/
public Spire(String url, String version){
this.spire_url = url;
this.api = new Api(spire_url, version);
}
/**
* Helper method, checks that the API description {@link Api#discover()} has been initialized
*
* @throws ResponseException
* @throws IOException
*/
private void initializeApi() throws ResponseException, IOException{
if(api.getApiDescription() == null)
api.discover();
}
/**
* Return the current Spire Api object
*
* @return {@link io.spire.api.Api}
*/
public Api getApi(){
return api;
}
/**
* Returns the current Spire session object
*
* @return {@link io.spire.api.Session}
*/
public Session getSession(){
return session;
}
/**
* Spire Api entry point. This method runs Spire Api discover process,
* retrieving the Api description for all available resources
*
* @throws ResponseException
* @throws IOException
*/
public void discover() throws ResponseException, IOException{
api.discover();
}
/**
* Creates an authenticated Spire session using the Spire Account key
*
* @param accountKey
* @throws ResponseException
* @throws IOException
*/
public void start(String secretKey) throws ResponseException, IOException{
this.initializeApi();
session = api.createSession(secretKey);
}
/**
* Creates an authenticated Spire session using the account login and password.
*
* @param email
* @param password
* @throws ResponseException
* @throws IOException
*/
public void login(String email, String password) throws ResponseException, IOException{
this.initializeApi();
session = api.login(email, password);
}
/**
* Creates a new Spire account.
*
* @param email
* @param password
* @param passwordConfirmation
* @throws ResponseException
* @throws IOException
*/
public void register(String email, String password, String passwordConfirmation) throws ResponseException, IOException{
this.initializeApi();
session = api.createAccount(email, password, passwordConfirmation);
}
/**
* Creates a new Spire account.
*
* @param email
* @param password
* @throws ResponseException
* @throws IOException
*/
public void register(String email, String password) throws ResponseException, IOException{
this.initializeApi();
session = api.createAccount(email, password, password);
}
// public void passwordReset(String email) throws ResponseException, IOException{
//
// }
/**
* Deletes the current authenticated Spire account
*
* @throws ResponseException
* @throws IOException
*/
public void deleteAccount() throws ResponseException, IOException{
session.getAccount().delete();
}
/**
* Gets the Account secret key
*
* @return {@link String}
*/
public String getAccountSecret(){
if(session == null || session.getAccount() == null)
return null;
return session.getAccount().getSecret();
}
/**
* Gets all the Spire channels available in the current session
*
* @return {@link Channels}
* @throws ResponseException
* @throws IOException
*/
public Channels getChannels(){
return session.getChannels();
}
/**
* Request and returns Spire Billing object with contains information about all
* the billing plans available
*
* @return {@link Billing}
* @throws ResponseException
* @throws IOException
* @deprecated v1.1.4
*/
public Billing billing() throws ResponseException, IOException{
this.initializeApi();
billing = api.billing();
return billing;
}
/**
* Request and returns all Spire Channels available for the current session.
*
* @return {@link Channels}
* @throws ResponseException
* @throws IOException
*/
public Channels channels() throws ResponseException, IOException{
return session.channels();
}
/**
* Request the creation of a new Spire Channel
*
* @param name of the channel to create
* @return {@link Channel}
* @throws ResponseException
* @throws IOException
*/
public Channel createChannel(String name) throws ResponseException, IOException{
return session.createChannel(name);
}
/**
* Gets all the Spire Subscriptions available in the current session
*
* @return {@link Subscriptions}
*/
public Subscriptions getSubscriptions(){
return session.getSubscriptions();
}
/**
* Request and returns all Spire {@link Subscriptions} available for the current session.
*
* @return {@link Subscriptions}
* @throws ResponseException
* @throws IOException
*/
public Subscriptions subscriptions() throws ResponseException, IOException{
return session.subscriptions();
}
/**
*
* Creates a returns a new subscription.
*
* @param name of the new {@link Subscription}
* @param channels is a list of channel names to subscribe to
* @return {@link Subscription}
* @throws ResponseException
* @throws IOException
*/
public Subscription subscribe(String name, String ...channels) throws ResponseException, IOException{
return session.subscribe(name, channels);
}
/**
* Spire Factory
* Convenient for quick creation of Spire objects.
* Spire Factory reuses the internal Api description object
* obtained from the first originated {@link Api#discover()}
*
* @author Jorge Gonzalez
*
*/
public static class SpireFactory{
private static ApiDescriptionModel description;
private static void initialize() throws ResponseException, IOException{
if(SPIRE_API.getApiDescription() == null){
SPIRE_API.discover();
description = SPIRE_API.getApiDescription();
}
}
/**
* Creates a new Api object using the default Url
*
* @return {@link Api}
*/
public static Api createApi(){
return new Api(Spire.SPIRE_URL);
}
/**
* Creates a new instance of a Spire Channel
*
* @return {@link Channel}
* @throws ResponseException
* @throws IOException
*/
public static Channel createChannel() throws ResponseException, IOException{
initialize();
return new Channel(description.getSchema());
}
/**
* Creates a new instance of a Spire Channel
* The channel would be completely agnostic about the current
* authenticated session. However, providing a capability and a Channel Uri
* this channel could be used to publish messages
*
*
* @param capability
* @param url
* @return {@link Channel}
* @throws ResponseException
* @throws IOException
*/
public static Channel createChannel(Capability capability, String url) throws ResponseException, IOException{
initialize();
return createResource(capability, url, Channel.class);
}
/**
* Creates a new instance of a Spire Subscription
* The subscription would be completely agnostic about the current
* authenticated session (if any). However, providing a capability and a
* Subscription Uri this subscription is capable of listening and retrieving messages
* from the channels it is subscribed to.
*
* @param capability
* @param url
* @return {@link Subscription}
* @throws ResponseException
* @throws IOException
*/
public static Subscription createSubscription(Capability capability, String url) throws ResponseException, IOException{
initialize();
return createResource(capability, url, Subscription.class);
}
/**
* Creates new instances of spire resources
*
* @param capability
* @param url
* @param T is the class of the Spire Resource to create
* @return T new instance
* @throws ResponseException
* @throws IOException
*/
public static <T>T createResource(Capability capability, String url, Class<T> T) throws ResponseException, IOException{
initialize();
Constructor<T> constructorT = null;
T t = null;
try {
constructorT = T.getConstructor(ApiSchemaModel.class);
t = constructorT.newInstance(description.getSchema());
Resource r = Resource.class.cast(t);
r.setCapability(capability);
r.setUrl(url);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return t;
}
}
}
| |
package gov.nih.nci.codegen.core.util;
import gov.nih.nci.common.util.Constant;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.jaxen.JaxenException;
import org.jaxen.jdom.JDOMXPath;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.omg.uml.foundation.core.*;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.Operation;
import org.omg.uml.foundation.core.Parameter;
import org.omg.uml.foundation.extensionmechanisms.TaggedValue;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2001-2004 SAIC. Copyright 2001-2003 SAIC. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* 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 disclaimer of Article 3, below. 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.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by the SAIC and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or SAIC-Frederick.
* 5. 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 NATIONAL CANCER INSTITUTE,
* SAIC, OR THEIR AFFILIATES 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.
* <!-- LICENSE_TEXT_END -->
*/
/**
* @author caBIO Team
* @version 1.0
*/
public class UML13JavaSourceHelper {
private static Logger log = Logger.getLogger(UML13JavaSourceHelper.class);
/**
* Creates an UML13JavaSourceHelper instance
*/
public UML13JavaSourceHelper() {
super();
}
private static String getDocumentation(Classifier klass)
{
TaggedValue doc = UML13Utils.getTaggedValue(klass, "documentation");
String docStr;
if (doc != null)
{
docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(klass, "documentation"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
}
else
{
doc = UML13Utils.getTaggedValue(klass, "description");
if (doc == null) return " ";
docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(klass, "description"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
}
return docStr;
}
private static String getDocumentation(Operation op)
{
TaggedValue doc = UML13Utils.getTaggedValue(op, "documentation");
if (doc == null) return " ";
String docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(op, "documentation"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
return docStr;
}
private static String getDocumentation(Parameter p)
{
TaggedValue doc = UML13Utils.getTaggedValue(p, "documentation");
if (doc == null) return " ";
String docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(p, "documentation"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
return docStr;
}
private static String getDocumentation(Attribute att)
{
TaggedValue doc = UML13Utils.getTaggedValue(att, "description");
String docStr;
if (doc != null)
{
docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(att, "description"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
}
else
{
doc = UML13Utils.getTaggedValue(att, "documentation");
if (doc == null ) return " ";
docStr = doc.getValue();
for(int i=2;i<=8;i++)
{
TaggedValue docNext = UML13Utils.getTaggedValue(att, "documentation"+i);
if(docNext==null) break;
docStr += docNext.getValue();
}
}
return docStr;
}
public static String getClassJavadoc(Classifier klass) {
StringBuffer javadocOut = new StringBuffer();
TaggedValue specialdep = UML13Utils.getTaggedValue(klass,
"deprecation1");
String docStr = getDocumentation(klass);
docStr = getLineFormattedJavadoc(docStr);
javadocOut.append(" /**\n");
javadocOut.append(docStr);
javadocOut.append("\n");
if (specialdep != null) {
javadocOut.append("* @deprecated ");
javadocOut.append(specialdep.getValue());
javadocOut.append("\n");
}
javadocOut.append(" */\n");
return javadocOut.toString();
}
/**
* Gets the java doc string for the specified class
*
* @param klass
* class to get java doscs
* @return String containing the java docs specs
*/
public static String getAllClassJavadoc(Classifier klass) {
try {
StringBuffer javadocOut = new StringBuffer();
TaggedValue doc = UML13Utils.getTaggedValue(klass, "documentation");
TaggedValue dep = UML13Utils.getTaggedValue(klass, "deprecation");
TaggedValue see = UML13Utils.getTaggedValue(klass, "see");
String docStr = getDocumentation(klass);
docStr = getLineFormattedJavadoc(docStr);
javadocOut.append(" /**\n");
javadocOut.append(docStr);
javadocOut.append("\n");
if (dep != null) {
javadocOut.append("* @deprecated ");
javadocOut.append(dep.getValue());
javadocOut.append("\n");
}
if (see != null) {
javadocOut.append("* @see ");
javadocOut.append(see.getValue());
javadocOut.append("\n");
}
javadocOut.append(" */\n");
return javadocOut.toString();
} catch (Exception ex) {
log.error("Exception: ", ex);
}
return "";
}
public static String getMethodJavadoc(Operation op) {
StringBuffer javadocOut = new StringBuffer();
TaggedValue dep = UML13Utils.getTaggedValue(op, "deprecated");
Classifier ret = UML13Utils.getReturnType(op);
String docStr = getDocumentation(op);
docStr = getLineFormattedJavadoc(docStr);
javadocOut.append(" /**\n");
javadocOut.append(docStr);
javadocOut.append("\n");
if (dep != null) {
javadocOut.append("* @deprecated ");
javadocOut.append(dep.getValue());
javadocOut.append("\n");
}
for (Iterator i = UML13Utils.getParameters(op).iterator(); i.hasNext();) {
Parameter p = (Parameter) i.next();
String pDocStr = getDocumentation(p);
javadocOut.append(" * @param ");
javadocOut.append(p.getName());
javadocOut.append(Constant.SPACE);
javadocOut.append(pDocStr);
javadocOut.append("\n");
}
if (ret != null && !"void".equalsIgnoreCase(ret.getName())) {
javadocOut.append(" * @return ");
javadocOut.append(ret.getName());
javadocOut.append("\n");
}
for (Iterator i = UML13Utils.getExceptions(op).iterator(); i.hasNext();) {
Classifier ex = (Classifier) i.next();
javadocOut.append(" * @throws ");
javadocOut.append(UML13Utils.getQualifiedName(ex));
javadocOut.append("\n");
}
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAssociationAttributeJavadoc(String associationType, boolean isCollection) {
StringBuffer javadocOut = new StringBuffer();
javadocOut.append("/**\n");
javadocOut.append("An associated ");
if(isCollection)
javadocOut.append(" collection of ");
javadocOut.append(associationType);
javadocOut.append(" object");
javadocOut.append("\n");
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAssociationAttributeJavadocGetter(String associationName) {
StringBuffer javadocOut = new StringBuffer();
javadocOut.append("/**\n");
javadocOut.append("Retreives the value of "+associationName+" attribue\n");
javadocOut.append(" * @return ");
javadocOut.append(associationName);
javadocOut.append("\n");
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAssociationAttributeJavadocSetter(String associationName) {
StringBuffer javadocOut = new StringBuffer();
javadocOut.append("/**\n");
javadocOut.append("Sets the value of "+associationName+" attribue\n");
javadocOut.append("@param ").append(associationName);
javadocOut.append("\n");
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAttributeJavadoc(Attribute att) {
StringBuffer javadocOut = new StringBuffer();
TaggedValue dep = UML13Utils.getTaggedValue(att, "deprecated");
String docStr = getDocumentation(att);
docStr = getLineFormattedJavadoc(docStr);
javadocOut.append("/**\n");
javadocOut.append(docStr);
javadocOut.append("\n");
if (dep != null) {
javadocOut.append("* @deprecated ");
javadocOut.append(dep.getValue());
javadocOut.append("\n");
}
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAttributeJavadocSetter(Attribute att) {
StringBuffer javadocOut = new StringBuffer();
String docStr = getDocumentation(att);
javadocOut.append("/**\n");
javadocOut.append("Sets the value of "+att.getName()+" attribue\n");
javadocOut.append("@param ").append(att.getName());
javadocOut.append(" ").append(docStr);
javadocOut.append("\n");
javadocOut.append(" */\n");
return javadocOut.toString();
}
public static String getAttributeJavadocGetter(Attribute att) {
StringBuffer javadocOut = new StringBuffer();
String docStr = getDocumentation(att);
javadocOut.append("/**\n");
javadocOut.append("Retreives the value of "+att.getName()+" attribue\n");
javadocOut.append(" * @return ");
javadocOut.append(att.getName());
javadocOut.append("\n");
javadocOut.append("\n");
javadocOut.append(" */\n");
return javadocOut.toString();
}
/**
* Formats the javadoc text
*
* @param val
* @return
*/
public static String getLineFormattedJavadoc(String val) {
StringBuffer javadocOut = new StringBuffer();
if (val == null) {
//javadocOut.append(" * DOCUMENT ME!");
} else {
// replace newlines
val.replace('\n', ' ');
val.replaceAll("<", "<");
val.replaceAll(">", ">");
if (val.length() > 80) {
javadocOut.append(" * ");
StringBuffer line = new StringBuffer();
int lineLength = 0;
StringTokenizer st = new StringTokenizer(val);
while (st.hasMoreTokens()) {
String t = st.nextToken();
lineLength += t.length();
line.append(t);
line.append(Constant.SPACE);
if (lineLength > 80) {
javadocOut.append(line.toString());
javadocOut.append("\n * ");
line = new StringBuffer();
lineLength = 0;
}
}
if (line.length() > 0) {
javadocOut.append(line.toString());
javadocOut.append("\n * ");
}
} else {
javadocOut.append(" * ");
javadocOut.append(val);
}
}
return javadocOut.toString().replaceAll("@", "\n* @");
}
public Element selectElement(String exp, Element context) {
Element result = null;
try {
JDOMXPath xpath = new JDOMXPath(exp);
result = (Element) xpath.selectSingleNode(context);
} catch (JaxenException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
if (result == null) {
log.debug("Couldn't find element for path " + exp);
/*
* throw new RuntimeException("Couldn't find element for path " +
* exp);
*/
}
return result;
}
public List selectElements(String exp, Element context) {
List result = null;
try {
JDOMXPath xpath = new JDOMXPath(exp);
result = xpath.selectNodes(context);
} catch (JaxenException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
return result;
}
public Element buildJDOMElement(String xml) {
Element root = null;
try {
root = (new SAXBuilder(false)).build(new StringReader(xml))
.getRootElement();
} catch (Exception ex) {
log.error("Couldn't build XML doc: ", ex);
throw new RuntimeException("Couldn't build XML doc", ex);
}
return root;
}
public String outputString(Element e) {
try {
XMLOutputter p = new XMLOutputter();
p.setFormat(Format.getPrettyFormat());
return p.outputString(e);
} catch (Exception ex) {
log.error("Error outputting string: " + ex.getMessage());
throw new RuntimeException("Error outputting string: "
+ ex.getMessage(), ex);
}
}
}
| |
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2015 Adobe
* %%
* 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 com.adobe.acs.commons.workflow.bulk.removal.impl;
import com.adobe.acs.commons.workflow.bulk.removal.WorkflowInstanceRemover;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/**
* ACS AEM Commons - Workflow Instance Remover
*/
@Component
@Service
public final class WorkflowInstanceRemoverImpl implements WorkflowInstanceRemover {
private static final Logger log = LoggerFactory.getLogger(WorkflowInstanceRemoverImpl.class);
private static final SimpleDateFormat WORKFLOW_FOLDER_FORMAT = new SimpleDateFormat("YYYY-MM-dd");
private static final String PN_MODEL_ID = "modelId";
private static final String PN_STARTED_AT = "startedAt";
private static final String PN_STATUS = "status";
private static final String PAYLOAD_PATH = "data/payload/path";
private static final String NT_SLING_FOLDER = "sling:Folder";
private static final String NT_CQ_WORKFLOW = "cq:Workflow";
private static final Pattern NN_SERVER_FOLDER_PATTERN = Pattern.compile("server\\d+");
private static final Pattern NN_DATE_FOLDER_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}.*");
private static final int BATCH_SIZE = 1000;
private static final int MAX_SAVE_RETRIES = 5;
private final AtomicReference<WorkflowRemovalStatus> status
= new AtomicReference<WorkflowRemovalStatus>();
private final AtomicBoolean forceQuit = new AtomicBoolean(false);
/**
* {@inheritDoc}
*/
@Override
public WorkflowRemovalStatus getStatus() {
return this.status.get();
}
/**
* {@inheritDoc}
*/
@Override
public void forceQuit() {
this.forceQuit.set(true);
}
/**
* {@inheritDoc}
*/
public int removeWorkflowInstances(final ResourceResolver resourceResolver,
final Collection<String> modelIds,
final Collection<String> statuses,
final Collection<Pattern> payloads,
final Calendar olderThan)
throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException {
return removeWorkflowInstances(resourceResolver, modelIds, statuses, payloads, olderThan, BATCH_SIZE);
}
/**
* {@inheritDoc}
*/
public int removeWorkflowInstances(final ResourceResolver resourceResolver,
final Collection<String> modelIds,
final Collection<String> statuses,
final Collection<Pattern> payloads,
final Calendar olderThan,
final int batchSize)
throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException {
int count = 0;
int checkedCount = 0;
int workflowRemovedCount = 0;
final long start = System.currentTimeMillis();
try {
this.start(resourceResolver);
final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver);
for (Resource containerFolder : containerFolders) {
log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath());
final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder);
for (final Resource folder : sortedFolders) {
int remaining = 0;
for (final Resource instance : folder.getChildren()) {
if (this.forceQuit.get()) {
throw new WorkflowRemovalForceQuitException();
}
final ValueMap properties = instance.getValueMap();
if (!StringUtils.equals(NT_CQ_WORKFLOW,
properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) {
// Only process cq:Workflow's
remaining++;
continue;
}
checkedCount++;
final String status = properties.get(PN_STATUS, String.class);
final String model = properties.get(PN_MODEL_ID, String.class);
final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class);
final String payload = properties.get(PAYLOAD_PATH, String.class);
if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(status)) {
log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]", instance.getPath(), status);
remaining++;
continue;
} else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) {
log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]", instance.getPath(), model);
remaining++;
continue;
} else if (olderThan != null && startTime != null && startTime.before(olderThan)) {
log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]", instance.getPath(),
startTime);
remaining++;
continue;
} else {
if (CollectionUtils.isNotEmpty(payloads)) {
// Only evaluate payload patterns if they are provided
boolean match = false;
if (StringUtils.isNotEmpty(payload)) {
for (final Pattern pattern : payloads) {
if (payload.matches(pattern.pattern())) {
// payload matches a pattern
match = true;
break;
}
}
if (!match) {
// Not a match; skip to next workflow instance
log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]",
instance.getPath(), payload);
remaining++;
continue;
}
}
}
// Only remove matching
try {
instance.adaptTo(Node.class).remove();
log.debug("Removed workflow instance at [ {} ]", instance.getPath());
workflowRemovedCount++;
count++;
} catch (RepositoryException e) {
log.error("Could not remove workflow instance at [ {} ]. Continuing...",
instance.getPath(), e);
}
if (count % batchSize == 0) {
this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount);
log.info("Removed a running total of [ {} ] workflow instances", count);
}
}
}
if (remaining == 0
&& NN_DATE_FOLDER_PATTERN.matcher(folder.getName()).matches()
&& !StringUtils.startsWith(folder.getName(), WORKFLOW_FOLDER_FORMAT.format(new Date()))) {
// Dont remove folders w items and dont remove any of "today's" folders
// MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders
try {
folder.adaptTo(Node.class).remove();
log.debug("Removed empty workflow folder node [ {} ]", folder.getPath());
// Incrementing only count to trigger batch save and not total since is not a WF
count++;
} catch (RepositoryException e) {
log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e);
}
}
}
// Save final batch if needed, and update tracking nodes
this.complete(resourceResolver, checkedCount, workflowRemovedCount);
}
log.info("Removed a total of [ {} ] workflow instances in [ {} ] ms", count,
System.currentTimeMillis() - start);
return count;
} catch (PersistenceException e) {
this.forceQuit.set(false);
log.error("Error persisting changes with Workflow Removal", e);
this.error(resourceResolver);
throw e;
} catch (WorkflowRemovalException e) {
this.forceQuit.set(false);
log.error("Error with Workflow Removal", e);
this.error(resourceResolver);
throw e;
} catch (InterruptedException e) {
this.forceQuit.set(false);
log.error("Errors in persistence retries during Workflow Removal", e);
this.error(resourceResolver);
throw e;
} catch (WorkflowRemovalForceQuitException e) {
this.forceQuit.set(false);
// Uncommon instance of using Exception to control flow; Force quitting is an extreme condition.
log.info("Workflow removal was force quit. The removal state is unknown.");
this.forceQuit(resourceResolver);
throw e;
}
}
private Collection<Resource> getSortedAndFilteredFolders(Resource folderResource) {
final Collection<Resource> sortedCollection = new TreeSet(new WorkflowInstanceFolderComparator());
final Iterator<Resource> folders = folderResource.listChildren();
while (folders.hasNext()) {
final Resource folder = folders.next();
if (!folder.isResourceType(NT_SLING_FOLDER)) {
// Only process sling:Folders; eg. skip rep:Policy
continue;
} else {
sortedCollection.add(folder);
}
}
return sortedCollection;
}
private void save(ResourceResolver resourceResolver) throws PersistenceException, InterruptedException {
int count = 0;
while (count++ <= MAX_SAVE_RETRIES) {
try {
if (resourceResolver.hasChanges()) {
final long start = System.currentTimeMillis();
resourceResolver.commit();
log.debug("Saving batch workflow instance removal in [ {} ] ms", System.currentTimeMillis() - start);
}
// No changes or save did not error; return from loop
return;
} catch (PersistenceException ex) {
if (count <= MAX_SAVE_RETRIES) {
// If error occurred within bounds of retries, keep retrying
resourceResolver.refresh();
log.warn("Could not persist Workflow Removal changes, trying again in {} ms", 1000 * count);
Thread.sleep(1000 * count);
} else {
// If error occurred outside bounds of returns, throw the exception to exist this method
throw ex;
}
}
}
}
private void start(final ResourceResolver resourceResolver) throws PersistenceException, WorkflowRemovalException, InterruptedException {
// Ensure forceQuit does not have a left-over value when starting a new run
this.forceQuit.set(false);
boolean running = false;
WorkflowRemovalStatus localStatus = this.getStatus();
if(localStatus != null) {
running = localStatus.isRunning();
}
if (running) {
log.warn("Unable to start workflow instance removal; Workflow removal already running.");
throw new WorkflowRemovalException("Workflow removal already started by "
+ this.getStatus().getInitiatedBy());
} else {
this.status.set(new WorkflowRemovalStatus(resourceResolver));
log.info("Starting workflow instance removal");
}
}
private void batchComplete(final ResourceResolver resourceResolver, final int checked, final int count) throws
PersistenceException, InterruptedException {
this.save(resourceResolver);
WorkflowRemovalStatus status = this.status.get();
status.setChecked(checked);
status.setRemoved(count);
this.status.set(status);
}
private void complete(final ResourceResolver resourceResolver, final int checked, final int count) throws
PersistenceException, InterruptedException {
this.save(resourceResolver);
WorkflowRemovalStatus status = this.status.get();
status.setRunning(false);
status.setChecked(checked);
status.setRemoved(count);
status.setCompletedAt(Calendar.getInstance());
this.status.set(status);
}
private void error(final ResourceResolver resourceResolver) throws
PersistenceException, InterruptedException {
WorkflowRemovalStatus status = this.status.get();
status.setRunning(false);
status.setErredAt(Calendar.getInstance());
this.status.set(status);
}
private void forceQuit(final ResourceResolver resourceResolver) {
WorkflowRemovalStatus status = this.status.get();
status.setRunning(false);
status.setForceQuitAt(Calendar.getInstance());
this.status.set(status);
// Reset force quit flag
this.forceQuit.set(false);
}
private List<Resource> getWorkflowInstanceFolders(final ResourceResolver resourceResolver) {
final List<Resource> folders = new ArrayList<Resource>();
final Resource root = resourceResolver.getResource(WORKFLOW_INSTANCES_PATH);
final Iterator<Resource> itr = root.listChildren();
boolean addedRoot = false;
while (itr.hasNext()) {
Resource resource = itr.next();
if (NN_SERVER_FOLDER_PATTERN.matcher(resource.getName()).matches()) {
folders.add(resource);
} else if (!addedRoot && NN_DATE_FOLDER_PATTERN.matcher(resource.getName()).matches()) {
folders.add(root);
addedRoot = true;
}
}
if (folders.isEmpty()) {
folders.add(root);
}
return folders;
}
@Activate
@Deactivate
protected void reset(Map<String, Object> config) {
this.forceQuit.set(false);
}
}
| |
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
import static com.google.devtools.build.lib.actions.util.ActionCacheTestHelper.AMNESIAC_CACHE;
import static com.google.devtools.build.skyframe.InMemoryMemoizingEvaluator.DEFAULT_STORED_EVENT_FILTER;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionCacheChecker;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionExecutionStatusReporter;
import com.google.devtools.build.lib.actions.ActionInputPrefetcher;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionLogBufferPathGenerator;
import com.google.devtools.build.lib.actions.ActionLookupData;
import com.google.devtools.build.lib.actions.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionResult;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.actions.BasicActionLookupValue;
import com.google.devtools.build.lib.actions.BuildFailedException;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.FileStateValue;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.actions.MetadataProvider;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.actions.TestExecException;
import com.google.devtools.build.lib.actions.cache.ActionCache;
import com.google.devtools.build.lib.actions.cache.Protos.ActionCacheStatistics;
import com.google.devtools.build.lib.actions.cache.Protos.ActionCacheStatistics.MissReason;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.actions.util.DummyExecutor;
import com.google.devtools.build.lib.actions.util.InjectedActionLookupKey;
import com.google.devtools.build.lib.actions.util.TestAction;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.ServerDirectories;
import com.google.devtools.build.lib.analysis.TopLevelArtifactContext;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.buildtool.BuildRequestOptions;
import com.google.devtools.build.lib.buildtool.SkyframeBuilder;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.NestedSetExpander;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.exec.SingleBuildFileCache;
import com.google.devtools.build.lib.packages.WorkspaceFileValue;
import com.google.devtools.build.lib.pkgcache.PathPackageLocator;
import com.google.devtools.build.lib.remote.options.RemoteOutputsMode;
import com.google.devtools.build.lib.runtime.KeepGoingOption;
import com.google.devtools.build.lib.server.FailureDetails.Execution;
import com.google.devtools.build.lib.server.FailureDetails.Execution.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.skyframe.AspectValueKey.AspectKey;
import com.google.devtools.build.lib.skyframe.ExternalFilesHelper.ExternalFileAction;
import com.google.devtools.build.lib.skyframe.PackageLookupFunction.CrossRepositoryLabelViolationStrategy;
import com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.ActionCompletedReceiver;
import com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.ProgressSupplier;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.testutil.TestPackageFactoryBuilderFactory;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.UnixGlob;
import com.google.devtools.build.skyframe.CycleInfo;
import com.google.devtools.build.skyframe.ErrorInfo;
import com.google.devtools.build.skyframe.EvaluationContext;
import com.google.devtools.build.skyframe.EvaluationProgressReceiver;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.GraphInconsistencyReceiver;
import com.google.devtools.build.skyframe.InMemoryMemoizingEvaluator;
import com.google.devtools.build.skyframe.MemoizingEvaluator.EmittedEventState;
import com.google.devtools.build.skyframe.RecordingDifferencer;
import com.google.devtools.build.skyframe.SequencedRecordingDifferencer;
import com.google.devtools.build.skyframe.SequentialBuildDriver;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.junit.Before;
/**
* The common code that's shared between various builder tests.
*/
public abstract class TimestampBuilderTestCase extends FoundationTestCase {
@AutoCodec
protected static final ActionLookupKey ACTION_LOOKUP_KEY =
new InjectedActionLookupKey("action_lookup_key");
protected static final Predicate<Action> ALWAYS_EXECUTE_FILTER = Predicates.alwaysTrue();
protected static final String CYCLE_MSG = "Yarrrr, there be a cycle up in here";
protected Clock clock = BlazeClock.instance();
protected TimestampGranularityMonitor tsgm;
protected RecordingDifferencer differencer = new SequencedRecordingDifferencer();
private Set<ActionAnalysisMetadata> actions;
protected OptionsParser options;
protected final ActionKeyContext actionKeyContext = new ActionKeyContext();
private TopDownActionCache topDownActionCache;
@Before
public final void initialize() throws Exception {
options =
OptionsParser.builder()
.optionsClasses(KeepGoingOption.class, BuildRequestOptions.class, CoreOptions.class)
.build();
options.parse();
inMemoryCache = new InMemoryActionCache();
tsgm = new TimestampGranularityMonitor(clock);
actions = new LinkedHashSet<>();
actionTemplateExpansionFunction = new ActionTemplateExpansionFunction(actionKeyContext);
topDownActionCache = initTopDownActionCache();
}
protected TopDownActionCache initTopDownActionCache() {
return null;
}
protected void clearActions() {
actions.clear();
}
protected <T extends ActionAnalysisMetadata> T registerAction(T action) {
actions.add(action);
ActionLookupData actionLookupData =
ActionLookupData.create(ACTION_LOOKUP_KEY, actions.size() - 1);
for (Artifact output : action.getOutputs()) {
((Artifact.DerivedArtifact) output).setGeneratingActionKey(actionLookupData);
}
return action;
}
protected BuilderWithResult createBuilder(ActionCache actionCache) throws Exception {
return createBuilder(actionCache, 1, /*keepGoing=*/ false);
}
protected BuilderWithResult createBuilder(
ActionCache actionCache, GraphInconsistencyReceiver graphInconsistencyReceiver)
throws Exception {
return createBuilder(
actionCache,
1,
/*keepGoing=*/ false,
/*evaluationProgressReceiver=*/ null,
graphInconsistencyReceiver);
}
/** Create a ParallelBuilder with a DatabaseDependencyChecker using the specified ActionCache. */
protected BuilderWithResult createBuilder(
ActionCache actionCache, final int threadCount, final boolean keepGoing) throws Exception {
return createBuilder(
actionCache,
threadCount,
keepGoing,
/*evaluationProgressReceiver=*/ null,
GraphInconsistencyReceiver.THROWING);
}
protected BuilderWithResult createBuilder(
final ActionCache actionCache,
final int threadCount,
final boolean keepGoing,
@Nullable EvaluationProgressReceiver evaluationProgressReceiver,
GraphInconsistencyReceiver graphInconsistencyReceiver)
throws Exception {
AtomicReference<PathPackageLocator> pkgLocator =
new AtomicReference<>(
new PathPackageLocator(
outputBase,
ImmutableList.of(Root.fromPath(rootDirectory)),
BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY));
AtomicReference<TimestampGranularityMonitor> tsgmRef = new AtomicReference<>(tsgm);
BlazeDirectories directories =
new BlazeDirectories(
new ServerDirectories(rootDirectory, outputBase, outputBase),
rootDirectory,
/* defaultSystemJavabase= */ null,
TestConstants.PRODUCT_NAME);
ExternalFilesHelper externalFilesHelper = ExternalFilesHelper.createForTesting(
pkgLocator,
ExternalFileAction.DEPEND_ON_EXTERNAL_PKG_FOR_EXTERNAL_REPO_PATHS,
directories);
differencer = new SequencedRecordingDifferencer();
ActionExecutionStatusReporter statusReporter =
ActionExecutionStatusReporter.create(new StoredEventHandler(), eventBus);
final SkyframeActionExecutor skyframeActionExecutor =
new SkyframeActionExecutor(
actionKeyContext,
new AtomicReference<>(statusReporter),
/*sourceRootSupplier=*/ () -> ImmutableList.of());
Path actionOutputBase = scratch.dir("/usr/local/google/_blaze_jrluser/FAKEMD5/action_out/");
skyframeActionExecutor.setActionLogBufferPathGenerator(
new ActionLogBufferPathGenerator(actionOutputBase, actionOutputBase));
MetadataProvider cache =
new SingleBuildFileCache(rootDirectory.getPathString(), scratch.getFileSystem());
skyframeActionExecutor.configure(cache, ActionInputPrefetcher.NONE, NestedSetExpander.DEFAULT);
final InMemoryMemoizingEvaluator evaluator =
new InMemoryMemoizingEvaluator(
ImmutableMap.<SkyFunctionName, SkyFunction>builder()
.put(
FileStateValue.FILE_STATE,
new FileStateFunction(
tsgmRef,
new AtomicReference<>(UnixGlob.DEFAULT_SYSCALLS),
externalFilesHelper))
.put(FileValue.FILE, new FileFunction(pkgLocator))
.put(Artifact.ARTIFACT, new ArtifactFunction(() -> true))
.put(
SkyFunctions.ACTION_EXECUTION,
new ActionExecutionFunction(skyframeActionExecutor, directories, tsgmRef))
.put(
SkyFunctions.PACKAGE,
new PackageFunction(null, null, null, null, null, null, null, null))
.put(
SkyFunctions.PACKAGE_LOOKUP,
new PackageLookupFunction(
null,
CrossRepositoryLabelViolationStrategy.ERROR,
BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY,
BazelSkyframeExecutorConstants.EXTERNAL_PACKAGE_HELPER))
.put(
WorkspaceFileValue.WORKSPACE_FILE,
new WorkspaceFileFunction(
TestRuleClassProvider.getRuleClassProvider(),
TestPackageFactoryBuilderFactory.getInstance()
.builder(directories)
.build(TestRuleClassProvider.getRuleClassProvider(), fileSystem),
directories,
/*bzlLoadFunctionForInlining=*/ null))
.put(
SkyFunctions.EXTERNAL_PACKAGE,
new ExternalPackageFunction(
BazelSkyframeExecutorConstants.EXTERNAL_PACKAGE_HELPER))
.put(
SkyFunctions.ACTION_TEMPLATE_EXPANSION,
new DelegatingActionTemplateExpansionFunction())
.put(SkyFunctions.ACTION_SKETCH, new ActionSketchFunction(actionKeyContext))
.build(),
differencer,
evaluationProgressReceiver,
graphInconsistencyReceiver,
DEFAULT_STORED_EVENT_FILTER,
new EmittedEventState(),
/*keepEdges=*/ true);
final SequentialBuildDriver driver = new SequentialBuildDriver(evaluator);
PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
PrecomputedValue.ACTION_ENV.set(differencer, ImmutableMap.<String, String>of());
PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
PrecomputedValue.REMOTE_OUTPUTS_MODE.set(differencer, RemoteOutputsMode.ALL);
return new BuilderWithResult() {
@Nullable EvaluationResult<SkyValue> latestResult = null;
@Override
public EvaluationResult<SkyValue> getLatestResult() {
return Preconditions.checkNotNull(latestResult);
}
private void setGeneratingActions() throws ActionConflictException {
if (evaluator.getExistingValue(ACTION_LOOKUP_KEY) == null) {
differencer.inject(
ImmutableMap.of(
ACTION_LOOKUP_KEY,
new BasicActionLookupValue(
Actions.assignOwnersAndFilterSharedActionsAndThrowActionConflict(
actionKeyContext,
ImmutableList.copyOf(actions),
ACTION_LOOKUP_KEY,
/*outputFiles=*/ null))));
}
}
@Override
public void buildArtifacts(
Reporter reporter,
Set<Artifact> artifacts,
Set<ConfiguredTarget> parallelTests,
Set<ConfiguredTarget> exclusiveTests,
Set<ConfiguredTarget> targetsToBuild,
Set<ConfiguredTarget> targetsToSkip,
ImmutableSet<AspectKey> aspects,
Executor executor,
Set<ConfiguredTargetKey> builtTargets,
Set<AspectKey> builtAspects,
OptionsProvider options,
Range<Long> lastExecutionTimeRange,
TopLevelArtifactContext topLevelArtifactContext,
boolean trustRemoteArtifacts)
throws BuildFailedException, InterruptedException, TestExecException {
latestResult = null;
skyframeActionExecutor.prepareForExecution(
reporter,
executor,
options,
new ActionCacheChecker(
actionCache, null, actionKeyContext, ALWAYS_EXECUTE_FILTER, null),
topDownActionCache,
null);
skyframeActionExecutor.setActionExecutionProgressReportingObjects(
EMPTY_PROGRESS_SUPPLIER, EMPTY_COMPLETION_RECEIVER);
List<SkyKey> keys = new ArrayList<>();
for (Artifact artifact : artifacts) {
keys.add(Artifact.key(artifact));
}
try {
setGeneratingActions();
} catch (ActionConflictException e) {
throw new IllegalStateException(e);
}
EvaluationContext evaluationContext =
EvaluationContext.newBuilder()
.setKeepGoing(keepGoing)
.setNumThreads(threadCount)
.setEventHandler(reporter)
.build();
EvaluationResult<SkyValue> result = driver.evaluate(keys, evaluationContext);
this.latestResult = result;
if (result.hasError()) {
boolean hasCycles = false;
for (Map.Entry<SkyKey, ErrorInfo> entry : result.errorMap().entrySet()) {
Iterable<CycleInfo> cycles = entry.getValue().getCycleInfo();
hasCycles |= !Iterables.isEmpty(cycles);
}
if (hasCycles) {
throw new BuildFailedException(CYCLE_MSG, createDetailedExitCode(Code.CYCLE));
} else if (result.errorMap().isEmpty() || keepGoing) {
// The specific detailed code used here doesn't matter.
throw new BuildFailedException(
null, createDetailedExitCode(Code.NON_ACTION_EXECUTION_FAILURE));
} else {
SkyframeBuilder.rethrow(Preconditions.checkNotNull(result.getError().getException()));
}
}
}
};
}
/** A non-persistent cache. */
protected InMemoryActionCache inMemoryCache;
protected GraphInconsistencyReceiver graphInconsistencyReceiver =
GraphInconsistencyReceiver.THROWING;
protected SkyFunction actionTemplateExpansionFunction;
/** A class that records an event. */
protected static class Button implements Runnable {
protected boolean pressed = false;
@Override
public void run() {
pressed = true;
}
}
/** A class that counts occurrences of an event. */
static class Counter implements Runnable {
int count = 0;
@Override
public void run() {
count++;
}
}
protected Artifact createSourceArtifact(String name) {
return createSourceArtifact(scratch.getFileSystem(), name);
}
private static Artifact createSourceArtifact(FileSystem fs, String name) {
Path root = fs.getPath(TestUtils.tmpDir());
return ActionsTestUtil.createArtifactWithExecPath(
ArtifactRoot.asSourceRoot(Root.fromPath(root)), PathFragment.create(name));
}
protected Artifact createDerivedArtifact(String name) {
return createDerivedArtifact(scratch.getFileSystem(), name);
}
Artifact createDerivedArtifact(FileSystem fs, String name) {
Path execRoot = fs.getPath(TestUtils.tmpDir());
PathFragment execPath = PathFragment.create("out").getRelative(name);
return new Artifact.DerivedArtifact(
ArtifactRoot.asDerivedRoot(execRoot, "out"), execPath, ACTION_LOOKUP_KEY);
}
/** Creates and returns a new "amnesiac" builder based on the amnesiac cache. */
protected BuilderWithResult amnesiacBuilder() throws Exception {
return createBuilder(AMNESIAC_CACHE);
}
/**
* Creates and returns a new caching builder based on the {@link #inMemoryCache} and {@link
* #graphInconsistencyReceiver}.
*/
protected BuilderWithResult cachingBuilder() throws Exception {
return createBuilder(inMemoryCache, graphInconsistencyReceiver);
}
/** {@link Builder} that saves its most recent {@link EvaluationResult}. */
protected interface BuilderWithResult extends Builder {
EvaluationResult<SkyValue> getLatestResult();
}
/**
* Creates a TestAction from 'inputs' to 'outputs', and a new button, such that executing the
* action causes the button to be pressed. The button is returned.
*/
protected Button createActionButton(NestedSet<Artifact> inputs, ImmutableSet<Artifact> outputs) {
Button button = new Button();
registerAction(new TestAction(button, inputs, outputs));
return button;
}
/**
* Creates a TestAction from 'inputs' to 'outputs', and a new counter, such that executing the
* action causes the counter to be incremented. The counter is returned.
*/
protected Counter createActionCounter(
NestedSet<Artifact> inputs, ImmutableSet<Artifact> outputs) {
Counter counter = new Counter();
registerAction(new TestAction(counter, inputs, outputs));
return counter;
}
protected static Set<Artifact> emptySet = Collections.emptySet();
protected static NestedSet<Artifact> emptyNestedSet =
NestedSetBuilder.emptySet(Order.STABLE_ORDER);
protected void buildArtifacts(Builder builder, Artifact... artifacts)
throws BuildFailedException, AbruptExitException, InterruptedException, TestExecException {
buildArtifacts(builder, new DummyExecutor(fileSystem, rootDirectory), artifacts);
}
protected void buildArtifacts(Builder builder, Executor executor, Artifact... artifacts)
throws BuildFailedException, AbruptExitException, InterruptedException, TestExecException {
tsgm.setCommandStartTime();
Set<Artifact> artifactsToBuild = Sets.newHashSet(artifacts);
Set<ConfiguredTargetKey> builtTargets = new HashSet<>();
Set<AspectKey> builtAspects = new HashSet<>();
try {
builder.buildArtifacts(
reporter,
artifactsToBuild,
null,
null,
null,
null,
null,
executor,
builtTargets,
builtAspects,
options,
null,
null,
/* trustRemoteArtifacts= */ false);
} finally {
tsgm.waitForTimestampGranularity(reporter.getOutErr());
}
}
private static DetailedExitCode createDetailedExitCode(Code detailedCode) {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setExecution(Execution.newBuilder().setCode(detailedCode))
.build());
}
/** {@link TestAction} that copies its single input to its single output. */
protected static class CopyingAction extends TestAction {
CopyingAction(Runnable effect, Artifact input, Artifact output) {
super(effect, NestedSetBuilder.create(Order.STABLE_ORDER, input), ImmutableSet.of(output));
}
@Override
public ActionResult execute(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException {
ActionResult actionResult = super.execute(actionExecutionContext);
try {
FileSystemUtils.copyFile(
getInputs().getSingleton().getPath(), Iterables.getOnlyElement(getOutputs()).getPath());
} catch (IOException e) {
throw new IllegalStateException(e);
}
return actionResult;
}
}
/** In-memory {@link ActionCache} backed by a HashMap */
protected static class InMemoryActionCache implements ActionCache {
private final Map<String, Entry> actionCache = new HashMap<>();
@Override
public synchronized void put(String key, ActionCache.Entry entry) {
actionCache.put(key, entry);
}
@Override
public synchronized Entry get(String key) {
return actionCache.get(key);
}
@Override
public synchronized void remove(String key) {
actionCache.remove(key);
}
public synchronized void reset() {
actionCache.clear();
}
@Override
public long save() {
// safe to ignore
return 0;
}
@Override
public void clear() {
// safe to ignore
}
@Override
public void dump(PrintStream out) {
out.println("In-memory action cache has " + actionCache.size() + " records");
}
@Override
public void accountHit() {
// Not needed for these tests.
}
@Override
public void accountMiss(MissReason reason) {
// Not needed for these tests.
}
@Override
public void mergeIntoActionCacheStatistics(ActionCacheStatistics.Builder builder) {
// Not needed for these tests.
}
@Override
public void resetStatistics() {
// Not needed for these tests.
}
}
private class DelegatingActionTemplateExpansionFunction implements SkyFunction {
@Override
public SkyValue compute(SkyKey skyKey, Environment env)
throws SkyFunctionException, InterruptedException {
return actionTemplateExpansionFunction.compute(skyKey, env);
}
@Override
public String extractTag(SkyKey skyKey) {
return actionTemplateExpansionFunction.extractTag(skyKey);
}
}
private static final ProgressSupplier EMPTY_PROGRESS_SUPPLIER =
new ProgressSupplier() {
@Override
public String getProgressString() {
return "";
}
};
private static final ActionCompletedReceiver EMPTY_COMPLETION_RECEIVER =
new ActionCompletedReceiver() {
@Override
public void actionCompleted(ActionLookupData actionLookupData) {}
@Override
public void noteActionEvaluationStarted(ActionLookupData actionLookupData, Action action) {}
};
}
| |
/*
* Copyright 2013 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.kie.spring.factorybeans;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.command.Command;
import org.kie.api.event.KieRuntimeEventManager;
import org.kie.api.event.process.ProcessEventListener;
import org.kie.api.event.rule.AgendaEventListener;
import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.logger.KieLoggers;
import org.kie.api.logger.KieRuntimeLogger;
import org.kie.api.runtime.KieRuntime;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieSessionConfiguration;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.spring.KieObjectsResolver;
import org.kie.spring.factorybeans.helper.KSessionFactoryBeanHelper;
import org.kie.spring.factorybeans.helper.StatefulKSessionFactoryBeanHelper;
import org.kie.spring.factorybeans.helper.StatelessKSessionFactoryBeanHelper;
import org.kie.spring.namespace.EventListenersUtil;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.ManagedList;
public class KSessionFactoryBean
implements
FactoryBean,
InitializingBean {
private Object kSession;
private String id;
private String type;
private KieBase kBase;
private String kBaseName;
private String name;
private String clockType;
private List<Command<?>> batch;
private KieSessionConfiguration conf;
private StatefulKSessionFactoryBeanHelper.JpaConfiguration jpaConfiguration;
protected KSessionFactoryBeanHelper helper;
protected ManagedList<LoggerAdaptor> loggerAdaptors = new ManagedList<LoggerAdaptor>();
protected List<AgendaEventListener> agendaEventListeners;
protected List<ProcessEventListener> processEventListeners;
protected List<RuleRuntimeEventListener> ruleRuntimeEventListeners;
protected List<Object> groupedListeners = new ArrayList<Object>();
private ReleaseId releaseId;
private String def;
private String scope;
public KSessionFactoryBean() {
agendaEventListeners = new ArrayList<AgendaEventListener>();
processEventListeners = new ArrayList<ProcessEventListener>();
ruleRuntimeEventListeners = new ArrayList<RuleRuntimeEventListener>();
}
public ReleaseId getReleaseId() {
return releaseId;
}
public void setReleaseId(ReleaseId releaseId) {
this.releaseId = releaseId;
}
public KieSessionConfiguration getConf() {
return conf;
}
public void setConf(KieSessionConfiguration conf) {
this.conf = conf;
}
public String getKBaseName() {
return kBaseName;
}
public void setKBaseName(String kBaseName) {
this.kBaseName = kBaseName;
}
/**
* Additional Setter to satisfy Spring Eclipse support (avoiding "No setter found" errors).
*/
public void setkBaseName(String kBaseName) {
this.kBaseName = kBaseName;
}
public List<Command<?>> getBatch() {
return batch;
}
public void setBatch(List<Command<?>> commands) {
this.batch = commands;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClockType() {
return clockType;
}
public void setClockType( String clockType ) {
this.clockType = clockType;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public KieBase getKBase() {
return kBase;
}
public void setKBase(KieBase kBase) {
this.kBase = kBase;
}
/**
* Additional Setter to satisfy Spring Eclipse support (avoiding "No setter found" errors).
*/
public void setkBase(KieBase kBase) {
this.kBase = kBase;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
public Object getObject() throws Exception {
if ("prototype".equalsIgnoreCase(scope)) {
helper.setKieBase(kBase);
Object kSession = helper.internalNewObject();
attachLoggers((KieRuntimeEventManager) kSession);
attachListeners((KieRuntimeEventManager) kSession);
return kSession;
}
return helper.internalGetObject();
}
public Class<? extends KieRuntime> getObjectType() {
return KieRuntime.class;
}
public boolean isSingleton() {
return "singleton".equalsIgnoreCase(scope);
}
public void afterPropertiesSet() throws Exception {
if ( "singleton".equalsIgnoreCase(scope) ) {
KieObjectsResolver kieObjectsResolver = new KieObjectsResolver();
kSession = kieObjectsResolver.resolveKSession(name, releaseId);
if (kSession instanceof StatelessKieSession) {
helper = new StatelessKSessionFactoryBeanHelper(this, (StatelessKieSession) kSession);
} else if (kSession instanceof KieSession) {
helper = new StatefulKSessionFactoryBeanHelper(this, (KieSession) kSession);
}
helper.internalAfterPropertiesSet();
// get ksession from helper as it might change the ksession when persistence is configured
kSession = helper.internalGetObject();
attachLoggers((KieRuntimeEventManager) kSession);
attachListeners((KieRuntimeEventManager) kSession);
helper.executeBatch();
} else {
if ("stateless".equalsIgnoreCase(type)) {
helper = new StatelessKSessionFactoryBeanHelper(this, null);
} else {
helper = new StatefulKSessionFactoryBeanHelper(this, null);
}
}
}
public StatefulKSessionFactoryBeanHelper.JpaConfiguration getJpaConfiguration() {
return jpaConfiguration;
}
public void setJpaConfiguration(StatefulKSessionFactoryBeanHelper.JpaConfiguration jpaConfiguration) {
this.jpaConfiguration = jpaConfiguration;
}
public void setEventListenersFromGroup(List<Object> eventListenerList) {
for (Object eventListener : eventListenerList) {
if (eventListener instanceof AgendaEventListener) {
agendaEventListeners.add((AgendaEventListener) eventListener);
}
if (eventListener instanceof RuleRuntimeEventListener) {
ruleRuntimeEventListeners.add((RuleRuntimeEventListener) eventListener);
}
if (eventListener instanceof ProcessEventListener) {
processEventListeners.add((ProcessEventListener) eventListener);
}
}
groupedListeners.addAll(eventListenerList);
}
public List<LoggerAdaptor> getKnowledgeRuntimeLoggers() {
return loggerAdaptors;
}
public void setKnowledgeRuntimeLoggers(List<LoggerAdaptor> loggers) {
this.loggerAdaptors.addAll(loggers);
}
public void attachLoggers(KieRuntimeEventManager ksession) {
if (loggerAdaptors != null && !loggerAdaptors.isEmpty()) {
KieServices ks = KieServices.Factory.get();
KieLoggers loggers = ks.getLoggers();
for (LoggerAdaptor adaptor : loggerAdaptors) {
KieRuntimeLogger runtimeLogger;
switch (adaptor.getLoggerType()) {
case LOGGER_TYPE_FILE:
runtimeLogger = loggers.newFileLogger(ksession, adaptor.getFile());
adaptor.setRuntimeLogger(runtimeLogger);
break;
case LOGGER_TYPE_THREADED_FILE:
runtimeLogger = loggers.newThreadedFileLogger(ksession, adaptor.getFile(), adaptor.getInterval());
adaptor.setRuntimeLogger(runtimeLogger);
break;
case LOGGER_TYPE_CONSOLE:
runtimeLogger = loggers.newConsoleLogger(ksession);
adaptor.setRuntimeLogger(runtimeLogger);
break;
}
}
}
}
public void setEventListeners(Map<String, List> eventListenerMap) {
for (Map.Entry<String, List> entry : eventListenerMap.entrySet()) {
String key = entry.getKey();
List<Object> eventListenerList = entry.getValue();
if (EventListenersUtil.TYPE_AGENDA_EVENT_LISTENER.equalsIgnoreCase(key)) {
for (Object eventListener : eventListenerList) {
if (eventListener instanceof AgendaEventListener) {
agendaEventListeners.add((AgendaEventListener) eventListener);
} else {
throw new IllegalArgumentException("The agendaEventListener (" + eventListener.getClass()
+ ") is not an instance of " + AgendaEventListener.class);
}
}
} else if (EventListenersUtil.TYPE_WORKING_MEMORY_EVENT_LISTENER.equalsIgnoreCase(key)) {
for (Object eventListener : eventListenerList) {
if (eventListener instanceof RuleRuntimeEventListener) {
ruleRuntimeEventListeners.add((RuleRuntimeEventListener) eventListener);
} else {
throw new IllegalArgumentException("The ruleRuntimeEventListener (" + eventListener.getClass()
+ ") is not an instance of " + RuleRuntimeEventListener.class);
}
}
} else if (EventListenersUtil.TYPE_PROCESS_EVENT_LISTENER.equalsIgnoreCase(key)) {
for (Object eventListener : eventListenerList) {
if (eventListener instanceof ProcessEventListener) {
processEventListeners.add((ProcessEventListener) eventListener);
} else {
throw new IllegalArgumentException("The processEventListener (" + eventListener.getClass()
+ ") is not an instance of " + ProcessEventListener.class);
}
}
}
}
}
public List<AgendaEventListener> getAgendaEventListeners() {
return agendaEventListeners;
}
public void setAgendaEventListeners(List<AgendaEventListener> agendaEventListeners) {
this.agendaEventListeners = agendaEventListeners;
}
public List<ProcessEventListener> getProcessEventListeners() {
return processEventListeners;
}
public void setProcessEventListeners(List<ProcessEventListener> processEventListeners) {
this.processEventListeners = processEventListeners;
}
public List<RuleRuntimeEventListener> getRuleRuntimeEventListeners() {
return ruleRuntimeEventListeners;
}
public void setRuleRuntimeEventListeners(List<RuleRuntimeEventListener> ruleRuntimeEventListeners) {
this.ruleRuntimeEventListeners = ruleRuntimeEventListeners;
}
public void attachListeners(KieRuntimeEventManager kieRuntimeEventManager) {
for (AgendaEventListener agendaEventListener : getAgendaEventListeners()) {
kieRuntimeEventManager.addEventListener(agendaEventListener);
}
for (ProcessEventListener processEventListener : getProcessEventListeners()) {
kieRuntimeEventManager.addEventListener(processEventListener);
}
for (RuleRuntimeEventListener ruleRuntimeEventListener : getRuleRuntimeEventListeners()) {
kieRuntimeEventManager.addEventListener(ruleRuntimeEventListener);
}
}
}
| |
/**
* Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.service.client;
import java.lang.reflect.AnnotatedElement;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.Path;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.proxy.WebResourceFactory;
import org.glassfish.jersey.uri.UriComponent;
import org.locationtech.geowave.service.StoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StoreServiceClient implements StoreService {
private static final Logger LOGGER = LoggerFactory.getLogger(StoreServiceClient.class);
private final StoreService storeService;
// Jersey 2 web resource proxy client doesn't work well with dynamic
// key-value pair queryparams such as the generic addStore
private final WebTarget addStoreTarget;
public StoreServiceClient(final String baseUrl) {
this(baseUrl, null, null);
}
public StoreServiceClient(final String baseUrl, final String user, final String password) {
final WebTarget target = ClientBuilder.newClient().target(baseUrl);
storeService = WebResourceFactory.newResource(StoreService.class, target);
addStoreTarget = createAddStoreTarget(target);
}
private static WebTarget createAddStoreTarget(final WebTarget baseTarget) {
WebTarget addStoreTarget = addPathFromAnnotation(StoreService.class, baseTarget);
try {
addStoreTarget =
addPathFromAnnotation(
StoreService.class.getMethod(
"addStoreReRoute",
String.class,
String.class,
String.class,
Map.class),
addStoreTarget);
} catch (NoSuchMethodException | SecurityException e) {
LOGGER.warn("Unable to derive path from method annotations", e);
// default to hardcoded method path
addStoreTarget = addStoreTarget.path("/add/{type}");
}
return addStoreTarget;
}
private static WebTarget addPathFromAnnotation(final AnnotatedElement ae, WebTarget target) {
final Path p = ae.getAnnotation(Path.class);
if (p != null) {
target = target.path(p.value());
}
return target;
}
@Override
public Response listPlugins() {
final Response resp = storeService.listPlugins();
resp.bufferEntity();
return resp;
}
@Override
public Response version(final String storeName) {
final Response resp = storeService.version(storeName);
return resp;
}
@Override
public Response clear(final String storeName) {
final Response resp = storeService.clear(storeName);
return resp;
}
public Response addHBaseStore(final String name, final String zookeeper) {
return addHBaseStore(
name,
zookeeper,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
@Override
public Response addHBaseStore(
final String name,
final String zookeeper,
final Boolean makeDefault,
final String geowaveNamespace,
final Boolean disableServiceSide,
final String coprocessorjar,
final Boolean persistAdapter,
final Boolean persistIndex,
final Boolean persistDataStatistics,
final Boolean createTable,
final Boolean useAltIndex,
final Boolean enableBlockCache) {
final Response resp =
storeService.addHBaseStore(
name,
zookeeper,
makeDefault,
geowaveNamespace,
disableServiceSide,
coprocessorjar,
persistAdapter,
persistIndex,
persistDataStatistics,
createTable,
useAltIndex,
enableBlockCache);
return resp;
}
public Response addAccumuloStore(
final String name,
final String zookeeper,
final String instance,
final String user,
final String password) {
return addAccumuloStore(
name,
zookeeper,
instance,
user,
password,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
@Override
public Response addAccumuloStore(
final String name,
final String zookeeper,
final String instance,
final String user,
final String password,
final Boolean makeDefault,
final String geowaveNamespace,
final Boolean useLocalityGroups,
final Boolean persistAdapter,
final Boolean persistIndex,
final Boolean persistDataStatistics,
final Boolean createTable,
final Boolean useAltIndex,
final Boolean enableBlockCache) {
final Response resp =
storeService.addAccumuloStore(
name,
zookeeper,
instance,
user,
password,
makeDefault,
geowaveNamespace,
useLocalityGroups,
persistAdapter,
persistIndex,
persistDataStatistics,
createTable,
useAltIndex,
enableBlockCache);
return resp;
}
public Response addBigTableStore(final String name) {
return addBigTableStore(
name,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
@Override
public Response addBigTableStore(
final String name,
final Boolean makeDefault,
final Integer scanCacheSize,
final String projectId,
final String instanceId,
final String geowaveNamespace,
final Boolean useLocalityGroups,
final Boolean persistAdapter,
final Boolean persistIndex,
final Boolean persistDataStatistics,
final Boolean createTable,
final Boolean useAltIndex,
final Boolean enableBlockCache) {
final Response resp =
storeService.addBigTableStore(
name,
makeDefault,
scanCacheSize,
projectId,
instanceId,
geowaveNamespace,
useLocalityGroups,
persistAdapter,
persistIndex,
persistDataStatistics,
createTable,
useAltIndex,
enableBlockCache);
return resp;
}
public Response addDynamoDBStore(final String name) {
return addDynamoDBStore(
name,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
@Override
public Response addDynamoDBStore(
final String name,
final Boolean makeDefault,
final String endpoint,
final String region,
final Long writeCapacity,
final Long readCapacity,
final Integer maxConnections,
final String protocol,
final Boolean enableCacheResponseMetadata,
final String geowaveNamespace,
final Boolean persistAdapter,
final Boolean persistIndex,
final Boolean persistDataStatistics,
final Boolean createTable,
final Boolean useAltIndex,
final Boolean enableBlockCache,
final Boolean enableServerSideLibrary) {
final Response resp =
storeService.addDynamoDBStore(
name,
makeDefault,
endpoint,
region,
writeCapacity,
readCapacity,
maxConnections,
protocol,
enableCacheResponseMetadata,
geowaveNamespace,
persistAdapter,
persistIndex,
persistDataStatistics,
createTable,
useAltIndex,
enableBlockCache,
enableServerSideLibrary);
return resp;
}
public Response addCassandraStore(final String name) {
return addCassandraStore(
name,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
@Override
public Response addCassandraStore(
final String name,
final Boolean makeDefault,
final String contactPoint,
final Integer batchWriteSize,
final Boolean durableWrites,
final Integer replicationFactor,
final String geowaveNamespace,
final Boolean persistAdapter,
final Boolean persistIndex,
final Boolean persistDataStatistics,
final Boolean createTable,
final Boolean useAltIndex,
final Boolean enableBlockCache,
final Boolean enableServerSideLibrary) {
final Response resp =
storeService.addCassandraStore(
name,
makeDefault,
contactPoint,
batchWriteSize,
durableWrites,
replicationFactor,
geowaveNamespace,
persistAdapter,
persistIndex,
persistDataStatistics,
createTable,
useAltIndex,
enableBlockCache,
enableServerSideLibrary);
return resp;
}
@Override
public Response removeStore(final String name) {
final Response resp = storeService.removeStore(name);
return resp;
}
@Override
public Response addStoreReRoute(
final String name,
final String type,
final String geowaveNamespace,
final Map<String, String> additionalQueryParams) {
WebTarget internalAddStoreTarget = addStoreTarget.resolveTemplate("type", type);
internalAddStoreTarget = internalAddStoreTarget.queryParam("name", name);
if ((geowaveNamespace != null) && !geowaveNamespace.isEmpty()) {
internalAddStoreTarget =
internalAddStoreTarget.queryParam("geowaveNamespace", geowaveNamespace);
}
for (final Entry<String, String> e : additionalQueryParams.entrySet()) {
if (e.getKey().equals("protocol")) {
internalAddStoreTarget =
internalAddStoreTarget.queryParam(e.getKey(), e.getValue().toUpperCase());
} else {
internalAddStoreTarget =
internalAddStoreTarget.queryParam(
e.getKey(),
// we want to allow curly braces to be in the config values
UriComponent.encodeTemplateNames(e.getValue()));
}
}
return internalAddStoreTarget.request().accept(MediaType.APPLICATION_JSON).method("POST");
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zmlx.hg4idea.branch;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.dvcs.repo.Repository;
import com.intellij.dvcs.ui.NewBranchAction;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.impl.HashImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.HgVcs;
import org.zmlx.hg4idea.action.HgCommandResultNotifier;
import org.zmlx.hg4idea.command.HgBookmarkCommand;
import org.zmlx.hg4idea.command.HgBranchCreateCommand;
import org.zmlx.hg4idea.execution.HgCommandException;
import org.zmlx.hg4idea.execution.HgCommandResult;
import org.zmlx.hg4idea.provider.commit.HgCloseBranchExecutor;
import org.zmlx.hg4idea.repo.HgRepository;
import org.zmlx.hg4idea.repo.HgRepositoryManager;
import org.zmlx.hg4idea.ui.HgBookmarkDialog;
import org.zmlx.hg4idea.util.HgErrorUtil;
import org.zmlx.hg4idea.util.HgUtil;
import java.util.*;
import static com.intellij.dvcs.ui.BranchActionGroupPopup.wrapWithMoreActionIfNeeded;
import static com.intellij.dvcs.ui.BranchActionUtil.FAVORITE_BRANCH_COMPARATOR;
import static com.intellij.dvcs.ui.BranchActionUtil.getNumOfTopShownBranches;
import static java.util.stream.Collectors.toList;
import static org.zmlx.hg4idea.util.HgUtil.getNewBranchNameFromUser;
import static org.zmlx.hg4idea.util.HgUtil.getSortedNamesWithoutHashes;
public class HgBranchPopupActions {
@NotNull private final Project myProject;
@NotNull private final HgRepository myRepository;
HgBranchPopupActions(@NotNull Project project, @NotNull HgRepository repository) {
myProject = project;
myRepository = repository;
}
ActionGroup createActions() {
return createActions(null, "", false);
}
ActionGroup createActions(@Nullable DefaultActionGroup toInsert, @NotNull String repoInfo, boolean firstLevelGroup) {
DefaultActionGroup popupGroup = new DefaultActionGroup(null, false);
popupGroup.addAction(new HgNewBranchAction(myProject, Collections.singletonList(myRepository), myRepository));
popupGroup.addAction(new HgNewBookmarkAction(Collections.singletonList(myRepository), myRepository));
popupGroup.addAction(new HgBranchPopupActions.HgCloseBranchAction(Collections.singletonList(myRepository), myRepository));
popupGroup.addAction(new HgShowUnnamedHeadsForCurrentBranchAction(myRepository));
if (toInsert != null) {
popupGroup.addAll(toInsert);
}
popupGroup.addSeparator("Bookmarks" + repoInfo);
List<HgCommonBranchActions> bookmarkActions = getSortedNamesWithoutHashes(myRepository.getBookmarks()).stream()
.map(bm -> new BookmarkActions(myProject, Collections.singletonList(myRepository), bm))
.collect(toList());
// if there are only a few local favorites -> show all; for remotes it's better to show only favorites;
wrapWithMoreActionIfNeeded(myProject, popupGroup, ContainerUtil.sorted(bookmarkActions, FAVORITE_BRANCH_COMPARATOR),
getNumOfTopShownBranches(bookmarkActions), firstLevelGroup ? HgBranchPopup.SHOW_ALL_BOOKMARKS_KEY : null,
firstLevelGroup);
//only opened branches have to be shown
popupGroup.addSeparator("Branches" + repoInfo);
List<HgCommonBranchActions> branchActions =
myRepository.getOpenedBranches().stream()
.sorted()
.filter(b -> !b.equals(myRepository.getCurrentBranch()))
.map(b -> new BranchActions(myProject, Collections.singletonList(myRepository), b))
.collect(toList());
wrapWithMoreActionIfNeeded(myProject, popupGroup, ContainerUtil.sorted(branchActions, FAVORITE_BRANCH_COMPARATOR),
getNumOfTopShownBranches(branchActions), firstLevelGroup ? HgBranchPopup.SHOW_ALL_BRANCHES_KEY : null,
firstLevelGroup);
return popupGroup;
}
public static class HgNewBranchAction extends NewBranchAction<HgRepository> {
@NotNull final HgRepository myPreselectedRepo;
public HgNewBranchAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull HgRepository preselectedRepo) {
super(project, repositories);
myPreselectedRepo = preselectedRepo;
}
@Override
public void actionPerformed(AnActionEvent e) {
final String name = getNewBranchNameFromUser(myPreselectedRepo, "Create New Branch");
if (name == null) {
return;
}
new Task.Backgroundable(myProject, "Creating " + StringUtil.pluralize("Branch", myRepositories.size()) + "...") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
createNewBranchInCurrentThread(name);
}
}.queue();
}
public void createNewBranchInCurrentThread(@NotNull final String name) {
for (final HgRepository repository : myRepositories) {
try {
HgCommandResult result = new HgBranchCreateCommand(myProject, repository.getRoot(), name).executeInCurrentThread();
repository.update();
if (HgErrorUtil.hasErrorsInCommandExecution(result)) {
new HgCommandResultNotifier(myProject)
.notifyError(result, "Creation failed", "Branch creation [" + name + "] failed");
}
}
catch (HgCommandException exception) {
HgErrorUtil.handleException(myProject, "Can't create new branch: ", exception);
}
}
}
}
public static class HgCloseBranchAction extends DumbAwareAction {
@NotNull private final List<HgRepository> myRepositories;
@NotNull final HgRepository myPreselectedRepo;
HgCloseBranchAction(@NotNull List<HgRepository> repositories, @NotNull HgRepository preselectedRepo) {
super("Close " + StringUtil.pluralize("branch", repositories.size()),
"Close current " + StringUtil.pluralize("branch", repositories.size()), AllIcons.Actions.Delete);
myRepositories = repositories;
myPreselectedRepo = preselectedRepo;
}
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = myPreselectedRepo.getProject();
ApplicationManager.getApplication().saveAll();
ChangeListManager.getInstance(project)
.invokeAfterUpdate(() -> commitAndCloseBranch(project), InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, VcsBundle
.message("waiting.changelists.update.for.show.commit.dialog.message"),
ModalityState.current());
}
private void commitAndCloseBranch(@NotNull final Project project) {
final LocalChangeList activeChangeList = ChangeListManager.getInstance(project).getDefaultChangeList();
HgVcs vcs = HgVcs.getInstance(project);
assert vcs != null;
final HgRepositoryManager repositoryManager = HgUtil.getRepositoryManager(project);
List<Change> changesForRepositories = ContainerUtil.filter(activeChangeList.getChanges(),
change -> myRepositories.contains(repositoryManager.getRepositoryForFile(
ChangesUtil.getFilePath(change))));
HgCloseBranchExecutor closeBranchExecutor = vcs.getCloseBranchExecutor();
closeBranchExecutor.setRepositories(myRepositories);
CommitChangeListDialog.commitChanges(project, changesForRepositories, activeChangeList,
Collections.singletonList(closeBranchExecutor),
false, vcs, "Close Branch", null, false);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabledAndVisible(ContainerUtil.and(myRepositories,
repository -> repository.getOpenedBranches()
.contains(repository.getCurrentBranch())));
}
}
public static class HgNewBookmarkAction extends DumbAwareAction {
@NotNull protected final List<HgRepository> myRepositories;
@NotNull final HgRepository myPreselectedRepo;
HgNewBookmarkAction(@NotNull List<HgRepository> repositories, @NotNull HgRepository preselectedRepo) {
super("New Bookmark", "Create new bookmark", AllIcons.Modules.AddContentEntry);
myRepositories = repositories;
myPreselectedRepo = preselectedRepo;
}
@Override
public void update(AnActionEvent e) {
if (DvcsUtil.anyRepositoryIsFresh(myRepositories)) {
e.getPresentation().setEnabled(false);
e.getPresentation().setDescription("Bookmark creation is not possible before the first commit.");
}
}
@Override
public void actionPerformed(AnActionEvent e) {
final HgBookmarkDialog bookmarkDialog = new HgBookmarkDialog(myPreselectedRepo);
if (bookmarkDialog.showAndGet()) {
final String name = bookmarkDialog.getName();
if (!StringUtil.isEmptyOrSpaces(name)) {
HgBookmarkCommand.createBookmarkAsynchronously(myRepositories, name, bookmarkDialog.isActive());
}
}
}
}
public static class HgShowUnnamedHeadsForCurrentBranchAction extends ActionGroup {
@NotNull final HgRepository myRepository;
@NotNull final String myCurrentBranchName;
@NotNull Collection<Hash> myHeads = new HashSet<>();
public HgShowUnnamedHeadsForCurrentBranchAction(@NotNull HgRepository repository) {
super(null, true);
myRepository = repository;
myCurrentBranchName = repository.getCurrentBranch();
getTemplatePresentation().setText(String.format("Unnamed heads for %s", myCurrentBranchName));
myHeads = filterUnnamedHeads();
}
@NotNull
private Collection<Hash> filterUnnamedHeads() {
Collection<Hash> branchWithHashes = myRepository.getBranches().get(myCurrentBranchName);
String currentHead = myRepository.getCurrentRevision();
if (branchWithHashes == null || currentHead == null || myRepository.getState() != Repository.State.NORMAL) {
// repository is fresh or branch is fresh or complex state
return Collections.emptySet();
}
else {
Collection<Hash> bookmarkHashes = ContainerUtil.map(myRepository.getBookmarks(), info -> info.getHash());
branchWithHashes.removeAll(bookmarkHashes);
branchWithHashes.remove(HashImpl.build(currentHead));
}
return branchWithHashes;
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
List<AnAction> branchHeadActions = new ArrayList<>();
for (Hash hash : myHeads) {
branchHeadActions
.add(new HgCommonBranchActions(myRepository.getProject(), Collections.singletonList(myRepository), hash.toShortString()));
}
return ContainerUtil.toArray(branchHeadActions, new AnAction[branchHeadActions.size()]);
}
@Override
public void update(final AnActionEvent e) {
if (myRepository.isFresh() || myHeads.isEmpty()) {
e.getPresentation().setEnabledAndVisible(false);
}
else if (!Repository.State.NORMAL.equals(myRepository.getState())) {
e.getPresentation().setEnabled(false);
}
}
}
static class BranchActions extends HgCommonBranchActions {
BranchActions(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull String branchName) {
super(project, repositories, branchName, HgBranchType.BRANCH);
}
}
/**
* Actions available for bookmarks.
*/
static class BookmarkActions extends HgCommonBranchActions {
BookmarkActions(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull String branchName) {
super(project, repositories, branchName, HgBranchType.BOOKMARK);
if (myRepositories.size() == 1 && branchName.equals(myRepositories.get(0).getCurrentBookmark())) {
getTemplatePresentation().setIcon(PlatformIcons.CHECK_ICON);
}
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
return ArrayUtil.append(super.getChildren(e), new DeleteBookmarkAction(myProject, myRepositories, myBranchName));
}
private static class DeleteBookmarkAction extends HgBranchAbstractAction {
DeleteBookmarkAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull String branchName) {
super(project, "Delete", repositories, branchName);
}
@Override
public void actionPerformed(AnActionEvent e) {
HgUtil.executeOnPooledThread(() -> {
for (HgRepository repository : myRepositories) {
HgBookmarkCommand.deleteBookmarkSynchronously(myProject, repository.getRoot(), myBranchName);
}
}, myProject);
}
}
}
}
| |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.config;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.nio.serialization.impl.Versioned;
import java.io.IOException;
/**
* Contains the configuration for an {@link com.hazelcast.core.IExecutorService}.
*/
public class ExecutorConfig implements IdentifiedDataSerializable, Versioned {
/**
* The number of executor threads per Member for the Executor based on this configuration.
*/
public static final int DEFAULT_POOL_SIZE = 16;
/**
* Capacity of queue.
*/
public static final int DEFAULT_QUEUE_CAPACITY = Integer.MAX_VALUE;
private String name = "default";
private int poolSize = DEFAULT_POOL_SIZE;
private int queueCapacity = DEFAULT_QUEUE_CAPACITY;
private boolean statisticsEnabled = true;
private String quorumName;
private transient ExecutorConfigReadOnly readOnly;
public ExecutorConfig() {
}
public ExecutorConfig(String name) {
this.name = name;
}
public ExecutorConfig(String name, int poolSize) {
this.name = name;
this.poolSize = poolSize;
}
public ExecutorConfig(ExecutorConfig config) {
this.name = config.name;
this.poolSize = config.poolSize;
this.queueCapacity = config.queueCapacity;
this.statisticsEnabled = config.statisticsEnabled;
this.quorumName = config.quorumName;
}
/**
* Gets immutable version of this configuration.
*
* @return immutable version of this configuration
* @deprecated this method will be removed in 4.0; it is meant for internal usage only
*/
public ExecutorConfigReadOnly getAsReadOnly() {
if (readOnly == null) {
readOnly = new ExecutorConfigReadOnly(this);
}
return readOnly;
}
/**
* Gets the name of the executor task.
*
* @return the name of the executor task
*/
public String getName() {
return name;
}
/**
* Sets the name of the executor task.
*
* @param name the name of the executor task
* @return this executor config instance
*/
public ExecutorConfig setName(String name) {
this.name = name;
return this;
}
/**
* Gets the number of executor threads per member for the executor.
*
* @return the number of executor threads per member for the executor
*/
public int getPoolSize() {
return poolSize;
}
/**
* Sets the number of executor threads per member for the executor.
*
* @param poolSize the number of executor threads per member for the executor
* @return this executor config instance
*/
public ExecutorConfig setPoolSize(final int poolSize) {
if (poolSize <= 0) {
throw new IllegalArgumentException("poolSize must be positive");
}
this.poolSize = poolSize;
return this;
}
/**
* Gets the queue capacity of the executor task. 0 means {@code Integer.MAX_VALUE}.
*
* @return Queue capacity of the executor task. 0 means {@code Integer.MAX_VALUE}
*/
public int getQueueCapacity() {
return queueCapacity;
}
/**
* Sets the queue capacity of the executor task. 0 means {@code Integer.MAX_VALUE}.
*
* @param queueCapacity Queue capacity of the executor task. 0 means {@code Integer.MAX_VALUE}
* @return this executor config instance
*/
public ExecutorConfig setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
return this;
}
/**
* Gets if statistics gathering is enabled or disabled on the executor task.
*
* @return {@code true} if statistics gathering is enabled on the executor task (default), {@code false} otherwise
*/
public boolean isStatisticsEnabled() {
return statisticsEnabled;
}
/**
* Enables or disables statistics gathering on the executor task.
*
* @param statisticsEnabled {@code true} if statistics gathering is enabled on the executor task, {@code false} otherwise
* @return this executor config instance
*/
public ExecutorConfig setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
return this;
}
/**
* Returns the quorum name for operations.
*
* @return the quorum name
*/
public String getQuorumName() {
return quorumName;
}
/**
* Sets the quorum name for operations.
*
* @param quorumName the quorum name
* @return the updated configuration
*/
public ExecutorConfig setQuorumName(String quorumName) {
this.quorumName = quorumName;
return this;
}
@Override
public String toString() {
return "ExecutorConfig{"
+ "name='" + name + '\''
+ ", poolSize=" + poolSize
+ ", queueCapacity=" + queueCapacity
+ ", quorumName=" + quorumName
+ '}';
}
@Override
public int getFactoryId() {
return ConfigDataSerializerHook.F_ID;
}
@Override
public int getId() {
return ConfigDataSerializerHook.EXECUTOR_CONFIG;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(name);
out.writeInt(poolSize);
out.writeInt(queueCapacity);
out.writeBoolean(statisticsEnabled);
out.writeUTF(quorumName);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
name = in.readUTF();
poolSize = in.readInt();
queueCapacity = in.readInt();
statisticsEnabled = in.readBoolean();
quorumName = in.readUTF();
}
@Override
@SuppressWarnings("checkstyle:npathcomplexity")
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ExecutorConfig)) {
return false;
}
ExecutorConfig that = (ExecutorConfig) o;
if (poolSize != that.poolSize) {
return false;
}
if (queueCapacity != that.queueCapacity) {
return false;
}
if (statisticsEnabled != that.statisticsEnabled) {
return false;
}
if (quorumName != null ? !quorumName.equals(that.quorumName) : that.quorumName != null) {
return false;
}
return name.equals(that.name);
}
@Override
public final int hashCode() {
int result = name.hashCode();
result = 31 * result + poolSize;
result = 31 * result + queueCapacity;
result = 31 * result + (statisticsEnabled ? 1 : 0);
result = 31 * result + (quorumName != null ? quorumName.hashCode() : 0);
return result;
}
}
| |
/* 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 java.util.prefs;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.harmony.prefs.internal.nls.Messages;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Utility class for the Preferences import/export from XML file.
*
*/
class XMLParser {
/*
* Constant - the specified DTD URL
*/
static final String PREFS_DTD_NAME = "http://java.sun.com/dtd/preferences.dtd"; //$NON-NLS-1$
/*
* Constant - the DTD string
*/
static final String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" //$NON-NLS-1$
+ " <!ELEMENT preferences (root)>" //$NON-NLS-1$
+ " <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA \"0.0\" >" //$NON-NLS-1$
+ " <!ELEMENT root (map, node*) >" //$NON-NLS-1$
+ " <!ATTLIST root type (system|user) #REQUIRED >" //$NON-NLS-1$
+ " <!ELEMENT node (map, node*) >" //$NON-NLS-1$
+ " <!ATTLIST node name CDATA #REQUIRED >" //$NON-NLS-1$
+ " <!ELEMENT map (entry*) >" //$NON-NLS-1$
+ " <!ELEMENT entry EMPTY >" //$NON-NLS-1$
+ " <!ATTLIST entry key CDATA #REQUIRED value CDATA #REQUIRED >"; //$NON-NLS-1$
/*
* Constant - the specified header
*/
static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
/*
* Constant - the specified DOCTYPE
*/
static final String DOCTYPE = "<!DOCTYPE preferences SYSTEM"; //$NON-NLS-1$
/*
* empty string array constant
*/
private static final String[] EMPTY_SARRAY = new String[0];
/*
* Constant - used by FilePreferencesImpl, which is default implementation of Linux platform
*/
private static final String FILE_PREFS = "<!DOCTYPE map SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>"; //$NON-NLS-1$
/*
* Constant - specify the DTD version
*/
private static final float XML_VERSION = 1.0f;
/*
* DOM builder
*/
private static final DocumentBuilder builder;
/*
* specify the indent level
*/
private static int indent = -1;
/*
* init DOM builder
*/
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new Error(e);
}
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (systemId.equals(PREFS_DTD_NAME)) {
InputSource result = new InputSource(new StringReader(
PREFS_DTD));
result.setSystemId(PREFS_DTD_NAME);
return result;
}
// prefs.1=Invalid DOCTYPE declaration: {0}
throw new SAXException(
Messages.getString("prefs.1", systemId)); //$NON-NLS-1$
}
});
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
throw e;
}
public void error(SAXParseException e) throws SAXException {
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
});
}
private XMLParser() {// empty constructor
}
/***************************************************************************
* utilities for Preferences export
**************************************************************************/
static void exportPrefs(Preferences prefs, OutputStream stream,
boolean withSubTree) throws IOException, BackingStoreException {
indent = -1;
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8")); //$NON-NLS-1$
out.write(HEADER);
out.newLine();
out.newLine();
out.write(DOCTYPE);
out.write(" '"); //$NON-NLS-1$
out.write(PREFS_DTD_NAME);
out.write("'>"); //$NON-NLS-1$
out.newLine();
out.newLine();
flushStartTag(
"preferences", new String[] { "EXTERNAL_XML_VERSION" }, new String[] { String.valueOf(XML_VERSION) }, out); //$NON-NLS-1$ //$NON-NLS-2$
flushStartTag(
"root", new String[] { "type" }, new String[] { prefs.isUserNode() ? "user" : "system" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
flushEmptyElement("map", out); //$NON-NLS-1$
StringTokenizer ancestors = new StringTokenizer(prefs.absolutePath(),
"/"); //$NON-NLS-1$
exportNode(ancestors, prefs, withSubTree, out);
flushEndTag("root", out); //$NON-NLS-1$
flushEndTag("preferences", out); //$NON-NLS-1$
out.flush();
out = null;
}
private static void exportNode(StringTokenizer ancestors,
Preferences prefs, boolean withSubTree, BufferedWriter out)
throws IOException, BackingStoreException {
if (ancestors.hasMoreTokens()) {
String name = ancestors.nextToken();
flushStartTag(
"node", new String[] { "name" }, new String[] { name }, out); //$NON-NLS-1$ //$NON-NLS-2$
if (ancestors.hasMoreTokens()) {
flushEmptyElement("map", out); //$NON-NLS-1$
exportNode(ancestors, prefs, withSubTree, out);
} else {
exportEntries(prefs, out);
if (withSubTree) {
exportSubTree(prefs, out);
}
}
flushEndTag("node", out); //$NON-NLS-1$
}
}
private static void exportSubTree(Preferences prefs, BufferedWriter out)
throws BackingStoreException, IOException {
String[] names = prefs.childrenNames();
if (names.length > 0) {
for (int i = 0; i < names.length; i++) {
Preferences child = prefs.node(names[i]);
flushStartTag(
"node", new String[] { "name" }, new String[] { names[i] }, out); //$NON-NLS-1$ //$NON-NLS-2$
exportEntries(child, out);
exportSubTree(child, out);
flushEndTag("node", out); //$NON-NLS-1$
}
}
}
private static void exportEntries(Preferences prefs, BufferedWriter out)
throws BackingStoreException, IOException {
String[] keys = prefs.keys();
String[] values = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
values[i] = prefs.get(keys[i], null);
}
exportEntries(keys, values, out);
}
private static void exportEntries(String[] keys, String[] values,
BufferedWriter out) throws IOException {
if (keys.length == 0) {
flushEmptyElement("map", out); //$NON-NLS-1$
return;
}
flushStartTag("map", out); //$NON-NLS-1$
for (int i = 0; i < keys.length; i++) {
if (values[i] != null) {
flushEmptyElement(
"entry", new String[] { "key", "value" }, new String[] { keys[i], values[i] }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
flushEndTag("map", out); //$NON-NLS-1$
}
private static void flushEndTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(indent--, out);
out.write("</"); //$NON-NLS-1$
out.write(tagName);
out.write(">"); //$NON-NLS-1$
out.newLine();
}
private static void flushEmptyElement(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
out.write("<"); //$NON-NLS-1$
out.write(tagName);
out.write(" />"); //$NON-NLS-1$
out.newLine();
indent--;
}
private static void flushEmptyElement(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
out.write("<"); //$NON-NLS-1$
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
out.write(" />"); //$NON-NLS-1$
out.newLine();
indent--;
}
private static void flushPairs(String[] attrKeys, String[] attrValues,
BufferedWriter out) throws IOException {
for (int i = 0; i < attrKeys.length; i++) {
out.write(" "); //$NON-NLS-1$
out.write(attrKeys[i]);
out.write("=\""); //$NON-NLS-1$
out.write(htmlEncode(attrValues[i]));
out.write("\""); //$NON-NLS-1$
}
}
private static void flushIndent(int ind, BufferedWriter out)
throws IOException {
for (int i = 0; i < ind; i++) {
out.write(" "); //$NON-NLS-1$
}
}
private static void flushStartTag(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
out.write("<"); //$NON-NLS-1$
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
out.write(">"); //$NON-NLS-1$
out.newLine();
}
private static void flushStartTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
out.write("<"); //$NON-NLS-1$
out.write(tagName);
out.write(">"); //$NON-NLS-1$
out.newLine();
}
private static String htmlEncode(String s) {
StringBuffer sb = new StringBuffer();
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
switch (c) {
case '<':
sb.append("<"); //$NON-NLS-1$
break;
case '>':
sb.append(">"); //$NON-NLS-1$
break;
case '&':
sb.append("&"); //$NON-NLS-1$
break;
case '\\':
sb.append("'"); //$NON-NLS-1$
break;
case '"':
sb.append("""); //$NON-NLS-1$
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/***************************************************************************
* utilities for Preferences import
**************************************************************************/
static void importPrefs(InputStream in) throws IOException,
InvalidPreferencesFormatException {
try {
// load XML document
Document doc = builder.parse(new InputSource(in));
// check preferences' export version
Element preferences;
preferences = doc.getDocumentElement();
String version = preferences.getAttribute("EXTERNAL_XML_VERSION"); //$NON-NLS-1$
if (version != null && Float.parseFloat(version) > XML_VERSION) {
// prefs.2=This preferences exported version is not supported:{0}
throw new InvalidPreferencesFormatException(
Messages.getString("prefs.2", version)); //$NON-NLS-1$
}
// check preferences root's type
Element root = (Element) preferences
.getElementsByTagName("root").item(0); //$NON-NLS-1$
Preferences prefsRoot = null;
String type = root.getAttribute("type"); //$NON-NLS-1$
if (type.equals("user")) { //$NON-NLS-1$
prefsRoot = Preferences.userRoot();
} else {
prefsRoot = Preferences.systemRoot();
}
// load node
loadNode(prefsRoot, root);
} catch (FactoryConfigurationError e) {
throw new InvalidPreferencesFormatException(e);
} catch (SAXException e) {
throw new InvalidPreferencesFormatException(e);
} catch (TransformerException e) {
throw new InvalidPreferencesFormatException(e);
}
}
private static void loadNode(Preferences prefs, Element node)
throws TransformerException {
// load preferences
NodeList children = XPathAPI.selectNodeList(node, "node"); //$NON-NLS-1$
NodeList entries = XPathAPI.selectNodeList(node, "map/entry"); //$NON-NLS-1$
int childNumber = children.getLength();
Preferences[] prefChildren = new Preferences[childNumber];
int entryNumber = entries.getLength();
synchronized (((AbstractPreferences) prefs).lock) {
if (((AbstractPreferences) prefs).isRemoved()) {
return;
}
for (int i = 0; i < entryNumber; i++) {
Element entry = (Element) entries.item(i);
String key = entry.getAttribute("key"); //$NON-NLS-1$
String value = entry.getAttribute("value"); //$NON-NLS-1$
prefs.put(key, value);
}
// get children preferences node
for (int i = 0; i < childNumber; i++) {
Element child = (Element) children.item(i);
String name = child.getAttribute("name"); //$NON-NLS-1$
prefChildren[i] = prefs.node(name);
}
}
// load children nodes after unlock
for (int i = 0; i < childNumber; i++) {
loadNode(prefChildren[i], (Element) children.item(i));
}
}
/***************************************************************************
* utilities for FilePreferencesImpl, which is default implementation of Linux platform
**************************************************************************/
/**
* load preferences from file, if cannot load, create a new one FIXME: need
* lock or not?
*
* @param file the XML file to be read
* @return Properties instance which indicates the preferences key-value pairs
*/
static Properties loadFilePrefs(final File file) {
return AccessController.doPrivileged(new PrivilegedAction<Properties>() {
public Properties run() {
return loadFilePrefsImpl(file);
}
});
// try {
// //FIXME: lines below can be deleted, because it is not required to
// persistent at the very beginning
// flushFilePrefs(file, result);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
static Properties loadFilePrefsImpl(final File file) {
Properties result = new Properties();
if (!file.exists()) {
file.getParentFile().mkdirs();
} else if (file.canRead()) {
InputStream in = null;
FileLock lock = null;
try {
FileInputStream istream = new FileInputStream(file);
in = new BufferedInputStream(istream);
FileChannel channel = istream.getChannel();
lock = channel.lock(0L, Long.MAX_VALUE, true);
Document doc = builder.parse(in);
NodeList entries = XPathAPI.selectNodeList(doc
.getDocumentElement(), "entry"); //$NON-NLS-1$
int length = entries.getLength();
for (int i = 0; i < length; i++) {
Element node = (Element) entries.item(i);
String key = node.getAttribute("key"); //$NON-NLS-1$
String value = node.getAttribute("value"); //$NON-NLS-1$
result.setProperty(key, value);
}
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
lock.release();
} catch (Exception e) {//ignore
}
try {
in.close();
} catch (Exception e) {//ignore
}
}
} else {
file.delete();
}
return result;
}
/**
*
* @param file
* @param prefs
* @throws PrivilegedActionException
*/
static void flushFilePrefs(final File file, final Properties prefs) throws PrivilegedActionException {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws IOException {
flushFilePrefsImpl(file, prefs);
return null;
}
});
}
static void flushFilePrefsImpl(File file, Properties prefs) throws IOException {
BufferedWriter out = null;
FileLock lock = null;
try {
FileOutputStream ostream = new FileOutputStream(file);
out = new BufferedWriter(new OutputStreamWriter(ostream, "UTF-8")); //$NON-NLS-1$
FileChannel channel = ostream.getChannel();
lock = channel.lock();
out.write(HEADER);
out.newLine();
out.write(FILE_PREFS);
out.newLine();
if (prefs.size() == 0) {
exportEntries(EMPTY_SARRAY, EMPTY_SARRAY, out);
} else {
String[] keys = prefs.keySet().toArray(new String[prefs.size()]);
int length = keys.length;
String[] values = new String[length];
for (int i = 0; i < length; i++) {
values[i] = prefs.getProperty(keys[i]);
}
exportEntries(keys, values, out);
}
out.flush();
} finally {
try {
lock.release();
} catch (Exception e) {//ignore
}
try {
if (null != out) {
out.close();
}
} catch (Exception e) {//ignore
}
}
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.deprecation;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.ExternalAnnotationsManager;
import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.jvm.JvmMethod;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.TextRange;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.compiled.ClsMethodImpl;
import com.intellij.psi.impl.source.PsiJavaModuleReference;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.*;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import one.util.streamex.MoreCollectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
abstract class DeprecationInspectionBase extends AbstractBaseJavaLocalInspectionTool {
public boolean IGNORE_IN_SAME_OUTERMOST_CLASS;
@Override
public boolean isEnabledByDefault() {
return true;
}
protected static class DeprecationElementVisitor extends JavaElementVisitor {
private final ProblemsHolder myHolder;
private final boolean myIgnoreInsideDeprecated;
private final boolean myIgnoreAbstractDeprecatedOverrides;
private final boolean myIgnoreImportStatements;
private final boolean myIgnoreMethodsOfDeprecated;
private final boolean myIgnoreInSameOutermostClass;
private final boolean myForRemoval;
private final ProblemHighlightType myHighlightType;
DeprecationElementVisitor(@NotNull ProblemsHolder holder,
boolean ignoreInsideDeprecated,
boolean ignoreAbstractDeprecatedOverrides,
boolean ignoreImportStatements,
boolean ignoreMethodsOfDeprecated,
boolean ignoreInSameOutermostClass,
boolean forRemoval,
@Nullable HighlightSeverity severity) {
myHolder = holder;
myIgnoreInsideDeprecated = ignoreInsideDeprecated;
myIgnoreAbstractDeprecatedOverrides = ignoreAbstractDeprecatedOverrides;
myIgnoreImportStatements = ignoreImportStatements;
myIgnoreMethodsOfDeprecated = ignoreMethodsOfDeprecated;
myIgnoreInSameOutermostClass = ignoreInSameOutermostClass;
myForRemoval = forRemoval;
myHighlightType = forRemoval && severity == HighlightSeverity.ERROR
? ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL
: ProblemHighlightType.LIKE_DEPRECATED;
}
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
JavaResolveResult result = reference.advancedResolve(true);
PsiElement resolved = result.getElement();
checkDeprecated(resolved, reference.getReferenceNameElement(), null, myIgnoreInsideDeprecated, myIgnoreImportStatements,
myIgnoreMethodsOfDeprecated, myIgnoreInSameOutermostClass, myHolder, myForRemoval, myHighlightType);
}
@Override
public void visitImportStaticStatement(PsiImportStaticStatement statement) {
PsiFile file = statement.getContainingFile();
if (file instanceof PsiJavaFile && ((PsiJavaFile)file).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_9)) return;
final PsiJavaCodeReferenceElement importReference = statement.getImportReference();
if (importReference != null) {
PsiElement resolved = importReference.resolve();
checkDeprecated(resolved, importReference.getReferenceNameElement(), null, myIgnoreInsideDeprecated,
false, true, myIgnoreInSameOutermostClass, myHolder, myForRemoval, myHighlightType);
}
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
visitReferenceElement(expression);
}
@Override
public void visitNewExpression(PsiNewExpression expression) {
PsiType type = expression.getType();
PsiExpressionList list = expression.getArgumentList();
if (!(type instanceof PsiClassType)) return;
PsiClassType.ClassResolveResult typeResult = ((PsiClassType)type).resolveGenerics();
PsiClass aClass = typeResult.getElement();
if (aClass == null) return;
if (aClass instanceof PsiAnonymousClass) {
type = ((PsiAnonymousClass)aClass).getBaseClassType();
typeResult = ((PsiClassType)type).resolveGenerics();
aClass = typeResult.getElement();
if (aClass == null) return;
}
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(expression.getProject()).getResolveHelper();
final PsiMethod[] constructors = aClass.getConstructors();
if (constructors.length > 0 && list != null) {
JavaResolveResult[] results = resolveHelper.multiResolveConstructor((PsiClassType)type, list, list);
MethodCandidateInfo result = null;
if (results.length == 1) result = (MethodCandidateInfo)results[0];
PsiMethod constructor = result == null ? null : result.getElement();
if (constructor != null && expression.getClassOrAnonymousClassReference() != null) {
if (expression.getClassReference() == null && constructor.getParameterList().isEmpty()) return;
checkDeprecated(constructor, expression.getClassOrAnonymousClassReference(), null, myIgnoreInsideDeprecated,
myIgnoreImportStatements, true, myIgnoreInSameOutermostClass, myHolder, myForRemoval, myHighlightType);
}
}
}
@Override
public void visitMethod(PsiMethod method) {
MethodSignatureBackedByPsiMethod methodSignature = MethodSignatureBackedByPsiMethod.create(method, PsiSubstitutor.EMPTY);
if (!method.isConstructor()) {
List<MethodSignatureBackedByPsiMethod> superMethodSignatures = method.findSuperMethodSignaturesIncludingStatic(true);
checkMethodOverridesDeprecated(methodSignature, superMethodSignatures, myIgnoreAbstractDeprecatedOverrides, myHolder, myForRemoval,
myHighlightType);
}
else {
checkImplicitCallToSuper(method);
}
}
private void checkImplicitCallToSuper(PsiMethod method) {
final PsiClass containingClass = method.getContainingClass();
assert containingClass != null;
final PsiClass superClass = containingClass.getSuperClass();
if (superClass != null && hasDefaultDeprecatedConstructor(superClass, myForRemoval)) {
if (superClass instanceof PsiAnonymousClass) {
final PsiExpressionList argumentList = ((PsiAnonymousClass)superClass).getArgumentList();
if (argumentList != null && !argumentList.isEmpty()) return;
}
final PsiCodeBlock body = method.getBody();
if (body != null) {
final PsiStatement[] statements = body.getStatements();
if (statements.length == 0 || !JavaHighlightUtil.isSuperOrThisCall(statements[0], true, true)) {
registerDefaultConstructorProblem(superClass, method.getNameIdentifier(), false);
}
}
}
}
private void registerDefaultConstructorProblem(PsiClass superClass, PsiElement nameIdentifier, boolean asDeprecated) {
String description =
JavaErrorMessages.message(myForRemoval ? "marked.for.removal.default.constructor" : "deprecated.default.constructor",
superClass.getQualifiedName());
ProblemHighlightType type = asDeprecated ? myHighlightType : ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
myHolder.registerProblem(nameIdentifier, getDescription(description, myForRemoval, myHighlightType), type);
}
@Override
public void visitClass(PsiClass aClass) {
if (aClass instanceof PsiTypeParameter) return;
final PsiMethod[] currentConstructors = aClass.getConstructors();
if (currentConstructors.length == 0) {
final PsiClass superClass = aClass.getSuperClass();
if (superClass != null && hasDefaultDeprecatedConstructor(superClass, myForRemoval)) {
final boolean isAnonymous = aClass instanceof PsiAnonymousClass;
if (isAnonymous) {
final PsiExpressionList argumentList = ((PsiAnonymousClass)aClass).getArgumentList();
if (argumentList != null && !argumentList.isEmpty()) return;
}
registerDefaultConstructorProblem(superClass,
isAnonymous ? ((PsiAnonymousClass)aClass).getBaseClassReference() : aClass.getNameIdentifier(),
isAnonymous);
}
}
}
@Override
public void visitRequiresStatement(PsiRequiresStatement statement) {
PsiJavaModuleReferenceElement refElement = statement.getReferenceElement();
PsiJavaModule target = PsiJavaModuleReference.resolve(refElement);
if (target != null && isMarkedForRemoval(target, myForRemoval) && PsiImplUtil.isDeprecatedByAnnotation(target)) {
String key = myForRemoval ? "marked.for.removal.symbol" : "deprecated.symbol";
String description = JavaErrorMessages.message(key, HighlightMessageUtil.getSymbolName(target));
myHolder.registerProblem(refElement, getDescription(description, myForRemoval, myHighlightType), myHighlightType);
}
}
@Override
public void visitNameValuePair(PsiNameValuePair pair) {
String name = pair.getName();
PsiIdentifier identifier = pair.getNameIdentifier();
if (name != null && identifier != null) {
PsiAnnotation annotation = PsiTreeUtil.getParentOfType(pair, PsiAnnotation.class);
if (annotation != null) {
PsiJavaCodeReferenceElement reference = annotation.getNameReferenceElement();
if (reference != null) {
PsiElement resolved = reference.resolve();
if (resolved instanceof PsiClass) {
for (JvmMethod method : ((PsiClass)resolved).findMethodsByName(name)) {
if (method instanceof PsiMethod &&
isMarkedForRemoval((PsiMethod)method, myForRemoval) &&
((PsiMethod)method).isDeprecated()) {
String description = JavaErrorMessages.message(myForRemoval ? "marked.for.removal.symbol" : "deprecated.symbol", name);
myHolder.registerProblem(identifier, getDescription(description, myForRemoval, myHighlightType), myHighlightType);
break;
}
}
}
}
}
}
}
}
private static boolean hasDefaultDeprecatedConstructor(@NotNull PsiClass superClass, boolean forRemoval) {
PsiMethod[] constructors = superClass.getConstructors();
if (constructors.length == 0) {
/*
The default constructor of a class can be externally annotated (IDEA-200832).
There cannot be inferred annotations for a default constructor,
so here is no need to check all annotations returned
by `AnnotationUtil.findAnnotations()`, but only external ones.
Note that there may be multiple external annotations roots,
so we check them all.
*/
List<PsiAnnotation> externalDeprecated = ExternalAnnotationsManager
.getInstance(superClass.getProject())
.findDefaultConstructorExternalAnnotations(superClass, CommonClassNames.JAVA_LANG_DEPRECATED);
return externalDeprecated != null
&& !externalDeprecated.isEmpty()
&& ContainerUtil.exists(externalDeprecated, annotation -> isMarkedForRemoval(annotation) == forRemoval);
}
return Arrays.stream(constructors)
.anyMatch(constructor -> constructor.getParameterList().isEmpty() &&
constructor.isDeprecated() &&
isMarkedForRemoval(constructor, forRemoval));
}
//@top
private static void checkMethodOverridesDeprecated(MethodSignatureBackedByPsiMethod methodSignature,
List<MethodSignatureBackedByPsiMethod> superMethodSignatures,
boolean ignoreAbstractDeprecatedOverrides, ProblemsHolder holder,
boolean forRemoval, @NotNull ProblemHighlightType highlightType) {
PsiMethod method = methodSignature.getMethod();
PsiElement methodName = method.getNameIdentifier();
if (methodName == null) return;
for (MethodSignatureBackedByPsiMethod superMethodSignature : superMethodSignatures) {
PsiMethod superMethod = superMethodSignature.getMethod();
PsiClass aClass = superMethod.getContainingClass();
if (aClass == null) continue;
// do not show deprecated warning for class implementing deprecated methods
if (ignoreAbstractDeprecatedOverrides && !aClass.isDeprecated() && superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) continue;
if (superMethod.isDeprecated() && isMarkedForRemoval(superMethod, forRemoval)) {
String description = JavaErrorMessages.message(forRemoval ? "overrides.marked.for.removal.method" : "overrides.deprecated.method",
HighlightMessageUtil.getSymbolName(aClass, PsiSubstitutor.EMPTY));
holder.registerProblem(methodName, getDescription(description, forRemoval, highlightType), highlightType);
}
}
}
static void checkDeprecated(PsiElement refElement,
PsiElement elementToHighlight,
@Nullable TextRange rangeInElement,
boolean ignoreInsideDeprecated,
boolean ignoreImportStatements,
boolean ignoreMethodsOfDeprecated,
boolean ignoreInSameOutermostClass,
ProblemsHolder holder,
boolean forRemoval,
@NotNull ProblemHighlightType highlightType) {
if (!(refElement instanceof PsiDocCommentOwner) ||
!isMarkedForRemoval((PsiDocCommentOwner)refElement, forRemoval) ||
isInSameOutermostClass(refElement, elementToHighlight, ignoreInSameOutermostClass)) {
return;
}
if (!((PsiDocCommentOwner)refElement).isDeprecated()) {
if (!ignoreMethodsOfDeprecated) {
checkDeprecated(((PsiDocCommentOwner)refElement).getContainingClass(), elementToHighlight, rangeInElement,
ignoreInsideDeprecated, ignoreImportStatements, false, ignoreInSameOutermostClass,
holder, forRemoval, highlightType);
}
return;
}
if (ignoreInsideDeprecated) {
PsiElement parent = elementToHighlight;
while ((parent = PsiTreeUtil.getParentOfType(parent, PsiDocCommentOwner.class, true)) != null) {
if (((PsiDocCommentOwner)parent).isDeprecated()) return;
}
}
if (ignoreImportStatements && PsiTreeUtil.getParentOfType(elementToHighlight, PsiImportStatement.class) != null) {
return;
}
String description = JavaErrorMessages.message(forRemoval ? "marked.for.removal.symbol" : "deprecated.symbol",
HighlightMessageUtil.getSymbolName(refElement, PsiSubstitutor.EMPTY));
LocalQuickFix quickFix = null;
PsiMethodCallExpression methodCall = getMethodCall(elementToHighlight);
if (refElement instanceof PsiMethod && methodCall != null) {
PsiMethod replacement = findReplacementInJavaDoc((PsiMethod)refElement, methodCall);
if (replacement != null) {
quickFix = new ReplaceMethodCallFix((PsiMethodCallExpression)elementToHighlight.getParent().getParent(), replacement);
}
}
holder.registerProblem(elementToHighlight, getDescription(description, forRemoval, highlightType), highlightType, rangeInElement, quickFix);
}
private static boolean isMarkedForRemoval(PsiModifierListOwner element, boolean forRemoval) {
PsiAnnotation annotation = AnnotationUtil.findAnnotation(element, CommonClassNames.JAVA_LANG_DEPRECATED);
if (annotation == null) {
return !forRemoval;
}
return isMarkedForRemoval(annotation) == forRemoval;
}
private static boolean isInSameOutermostClass(PsiElement refElement, PsiElement elementToHighlight, boolean ignoreInSameOutermostClass) {
if (!ignoreInSameOutermostClass) {
return false;
}
PsiClass outermostClass = CachedValuesManager.getCachedValue(
refElement,
() -> new CachedValueProvider.Result<>(getOutermostClass(refElement), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT));
return outermostClass != null && outermostClass == getOutermostClass(elementToHighlight);
}
private static PsiClass getOutermostClass(PsiElement element) {
PsiElement maybeClass = PsiTreeUtil.findFirstParent(element, e -> e instanceof PsiClass && e.getParent() instanceof PsiFile);
return maybeClass instanceof PsiClass ? (PsiClass)maybeClass : null;
}
/**
* Returns value of {@link Deprecated#forRemoval} attribute, which is available since Java 9.
*
* @param deprecatedAnnotation annotation instance to extract value of
* @return {@code true} if the {@code forRemoval} attribute is set to true,
* {@code false} if it isn't set or is set to {@code false}.
*/
private static boolean isMarkedForRemoval(@NotNull PsiAnnotation deprecatedAnnotation) {
PsiAnnotationMemberValue value = deprecatedAnnotation.findAttributeValue("forRemoval");
Object result = null;
if (value instanceof PsiLiteral) {
result = ((PsiLiteral)value).getValue();
}
else if (value instanceof PsiExpression) {
result = JavaConstantExpressionEvaluator.computeConstantExpression((PsiExpression)value, false);
}
return result instanceof Boolean && (Boolean)result;
}
static void addSameOutermostClassCheckBox(MultipleCheckboxOptionsPanel panel) {
panel.addCheckbox("Ignore in the same outermost class", "IGNORE_IN_SAME_OUTERMOST_CLASS");
}
private static String getDescription(String description, boolean forRemoval, ProblemHighlightType highlightType) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
ProblemHighlightType defaultType = forRemoval ? ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL : ProblemHighlightType.LIKE_DEPRECATED;
if (highlightType != defaultType) {
return description + "(" + highlightType + ")";
}
}
return description;
}
private static PsiMethod findReplacementInJavaDoc(@NotNull PsiMethod method, @NotNull PsiMethodCallExpression call) {
if (method instanceof PsiConstructorCall) return null;
if (method instanceof ClsMethodImpl) {
PsiMethod sourceMethod = ((ClsMethodImpl)method).getSourceMirrorMethod();
return sourceMethod == null ? null : findReplacementInJavaDoc(sourceMethod, call);
}
PsiDocComment doc = method.getDocComment();
if (doc == null) return null;
Collection<PsiDocTag> docTags = PsiTreeUtil.findChildrenOfType(doc, PsiDocTag.class);
if (docTags.isEmpty()) return null;
return docTags
.stream()
.filter(t -> {
String name = t.getName();
return "link".equals(name) || "see".equals(name);
})
.map(tag -> tag.getValueElement())
.filter(Objects::nonNull)
.map(value -> value.getReference())
.filter(Objects::nonNull)
.map(reference -> reference.resolve())
.distinct()
.map(resolved -> (PsiMethod)(resolved instanceof PsiMethod ? resolved : null))
.filter(Objects::nonNull)
.filter(tagMethod -> !tagMethod.isDeprecated())
.filter(tagMethod -> !tagMethod.isEquivalentTo(method))
.filter(tagMethod -> areReplaceable(method, tagMethod, call))
.collect(MoreCollectors.onlyOne())
.orElse(null);
}
private static boolean areReplaceable(@NotNull PsiMethod initial,
@NotNull PsiMethod suggestedReplacement,
@NotNull PsiMethodCallExpression call) {
if (!PsiResolveHelper.SERVICE.getInstance(call.getProject()).isAccessible(suggestedReplacement, call, null)) {
return false;
}
boolean isInitialStatic = initial.hasModifierProperty(PsiModifier.STATIC);
boolean isSuggestedStatic = suggestedReplacement.hasModifierProperty(PsiModifier.STATIC);
if (isInitialStatic && !isSuggestedStatic) {
return false;
}
if (!isInitialStatic && !isSuggestedStatic && !InheritanceUtil.isInheritorOrSelf(getQualifierClass(call), suggestedReplacement.getContainingClass(), true)) {
return false;
}
String qualifierText;
if (isInitialStatic) {
qualifierText = ObjectUtils.notNull(suggestedReplacement.getContainingClass()).getQualifiedName() + ".";
}
else {
PsiExpression qualifierExpression = call.getMethodExpression().getQualifierExpression();
qualifierText = qualifierExpression == null ? "" : qualifierExpression.getText() + ".";
}
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(initial.getProject());
PsiExpressionList arguments = call.getArgumentList();
PsiMethodCallExpression suggestedCall = (PsiMethodCallExpression)elementFactory
.createExpressionFromText(qualifierText + suggestedReplacement.getName() + arguments.getText(), call);
MethodCandidateInfo result = ObjectUtils.tryCast(suggestedCall.resolveMethodGenerics(), MethodCandidateInfo.class);
return result != null && result.isApplicable();
}
@Nullable
private static PsiClass getQualifierClass(@NotNull PsiMethodCallExpression call) {
PsiExpression expression = call.getMethodExpression().getQualifierExpression();
if (expression == null) {
return RefactoringChangeUtil.getThisClass(call);
}
return PsiUtil.resolveClassInType(expression.getType());
}
@Nullable
private static PsiMethodCallExpression getMethodCall(@NotNull PsiElement element) {
if (!(element instanceof PsiIdentifier)) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiReferenceExpression)) return null;
return ObjectUtils.tryCast(parent.getParent(), PsiMethodCallExpression.class);
}
}
| |
package ru.job4j.start;
import ru.job4j.models.Item;
import java.util.ArrayList;
import java.util.List;
/**
* The class represents menu.
*
* @author abondarev.
* @since 24.07.2017.
*/
public class MenuTracker {
/**
* The variable contains value of menu size.
*/
public static final int SIZE = 7;
/**
* The variable contains number of first item menu.
*/
public static final int FIRST = 1;
/**
* The list of all action in menu.
*/
private List<UserAction> actions = new ArrayList<>();
/**
* The input system instance.
*/
private Input input;
/**
* The tracker instance.
*/
private Tracker tracker;
/**
* The constructor.
*
* @param input is an input system instance.
* @param tracker is the tracker instance.
*/
public MenuTracker(Input input, Tracker tracker) {
this.input = input;
this.tracker = tracker;
}
/**
* The method fill actions of the menu.
*/
public void fillActions() {
this.actions.add(this.new AddAction(1, "Add an item."));
this.actions.add(new MenuTracker.ShowAllAction(2, "Show all items."));
this.actions.add(this.new EditAction(3, "Edit an item."));
this.actions.add(this.new DeleteAction(4, "Delete an action."));
this.actions.add(this.new FindByIdAction(5, "Find the item by Id."));
this.actions.add(new FindByNameAction(6, "Find items by name."));
this.actions.add(this.new ExitAction(7, "Exit."));
}
/**
* The method selects an menu action for execution.
*
* @param selected is an action key.
*/
public void select(int selected) {
for (UserAction action : this.actions) {
if (action != null && selected == action.key()) {
action.execute(this.input, this.tracker);
break;
}
}
}
/**
* The method shows te menu items for users.
*/
public void show() {
String lineSeparator = System.getProperty("line.separator");
StringBuilder builder = new StringBuilder();
builder.append("******************************").append(lineSeparator)
.append("* MENU *").append(lineSeparator)
.append("******************************").append(lineSeparator);
for (UserAction action : this.actions) {
if (action != null) {
builder.append(String.format(
"%s. %s", action.key(), action.info()))
.append(lineSeparator);
}
}
builder.append("******************************").append(lineSeparator);
System.out.println(builder);
}
/**
* The class implements UserAction for addition an item.
*/
private class AddAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
AddAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
Item item = tracker.add(
new Item(input.ask("Please enter name of item: "),
input.ask("Please enter description of item: "),
System.currentTimeMillis()
));
System.out.println(String.format("Id of your item: %s", item.getId()));
}
}
/**
* The class implements UserAction for show all items.
*/
private class ShowAllAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
ShowAllAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
List<Item> items = tracker.findAll();
if (items.size() != 0) {
for (Item item : items) {
System.out.println(item);
}
} else {
System.out.println("List is empty");
}
System.out.println("Done.");
}
}
/**
* The class implements UserAction for updating an item.
*/
private class EditAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
EditAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
String id = input.ask("Please enter yours item Id: ");
Item existed = tracker.findById(id);
if (existed != null) {
Item updated = new Item(input.ask("Please enter name of item: "),
input.ask("Please enter description of item: "),
existed.getCreate());
updated.setId(existed.getId());
tracker.update(updated);
System.out.println("Operation complete.");
} else {
System.out.println("Operation failure! Invalid id!");
}
}
}
/**
* The class implements UserAction for removing an item.
*/
private class DeleteAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
DeleteAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
String id = input.ask("Please enter yours item Id: ");
Item item = tracker.findById(id);
if (item != null) {
tracker.delete(item);
}
System.out.println("Operation complete.");
}
}
/**
* The class implements UserAction for searching the item by id.
*/
private class FindByIdAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
FindByIdAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
String id = input.ask("Please enter items Id: ");
Item item = tracker.findById(id);
if (item != null) {
System.out.println(item);
} else {
System.out.println("Not found");
}
}
}
/**
* The class implements UserAction for exit.
*/
private class ExitAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
ExitAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
System.out.println("Good bye.");
}
}
}
/**
* The class implements UserAction for searching items by name.
*/
class FindByNameAction extends BaseAction {
/**
* The constructor takes as parameter key and name of action.
*
* @param key of action.
* @param name of action.
*/
FindByNameAction(int key, String name) {
super(key, name);
}
/**
* <@inheritedDoc>.
*
* @param input an input instance.
* @param tracker an tracker instance.
*/
public void execute(Input input, Tracker tracker) {
String name = input.ask("Please enter name of item: ");
List<Item> items = tracker.findByName(name);
if (items.size() != 0) {
for (Item item : items) {
System.out.println(item);
}
} else {
System.out.println("Not found");
}
System.out.println("Done.");
}
}
| |
/*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* 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.jcwhatever.nucleus.internal.providers.bankitems;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.collections.timed.TimedHashMap;
import com.jcwhatever.nucleus.mixins.IDisposable;
import com.jcwhatever.nucleus.providers.bankitems.IBankItemsAccount;
import com.jcwhatever.nucleus.providers.bankitems.IBankItemsBank;
import com.jcwhatever.nucleus.storage.DataPath;
import com.jcwhatever.nucleus.providers.storage.DataStorage;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.storage.IDataNode.AutoSaveMode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.TimeScale;
import org.bukkit.Bukkit;
import java.util.Date;
import java.util.UUID;
import javax.annotation.Nullable;
/**
* Nucleus implementation of {@link IBankItemsBank}.
*/
class BankItemsBank implements IBankItemsBank, IDisposable {
private final String _name;
private final String _searchName;
private final UUID _ownerId;
private final IDataNode _dataNode;
private final IDataNode _accountsNode;
private final Object _sync = new Object();
private final Date _created;
private final TimedHashMap<UUID, BankItemsAccount> _accounts
= new TimedHashMap<>(Nucleus.getPlugin(), 10, 20, TimeScale.MINUTES);
volatile long _lastAccess;
private volatile boolean _isDisposed;
/**
* Constructor.
*
* @param name The name of the bank.
* @param ownerId The optional ID of the player owner.
* @param dataNode The banks data node.
*/
BankItemsBank(String name, @Nullable UUID ownerId, IDataNode dataNode) {
_name = name;
_searchName = name.toLowerCase();
_ownerId = ownerId;
_dataNode = dataNode;
String fileName = Bukkit.getOnlineMode() ? name : "offline-" + name;
_accountsNode = DataStorage.get(Nucleus.getPlugin(), new DataPath("bankitems.banks." + fileName));
_accountsNode.load();
_accountsNode.setAutoSaveMode(AutoSaveMode.ENABLED);
long created = _dataNode.getLong("created");
if (created == 0) {
created = System.currentTimeMillis();
_dataNode.set("created", created);
_dataNode.save();
}
_created = new Date(created);
_lastAccess = _dataNode.getLong("last-access", created);
}
@Override
public String getName() {
return _name;
}
@Override
public String getSearchName() {
return _searchName;
}
@Nullable
@Override
public UUID getOwnerId() {
return _ownerId;
}
@Override
public Date getCreatedDate() {
return _created;
}
@Override
public Date getLastAccess() {
return new Date(_lastAccess);
}
@Override
public boolean hasAccount(UUID playerId) {
return getAccount(playerId) != null;
}
@Nullable
@Override
public IBankItemsAccount getAccount(UUID playerId) {
PreCon.notNull(playerId);
synchronized (_sync) {
BankItemsAccount account = _accounts.get(playerId);
if (account == null) {
account = loadAccount(playerId);
if (account == null)
return null;
_accounts.put(playerId, account);
}
return account;
}
}
@Override
public IBankItemsAccount createAccount(UUID playerId) {
PreCon.notNull(playerId);
if (_isDisposed)
throw new IllegalStateException("Cannot use a disposed item bank.");
synchronized (_sync) {
BankItemsAccount account = _accounts.get(playerId);
if (account == null) {
IDataNode node = _dataNode.getNode(playerId.toString());
account = new BankItemsAccount(playerId, this, node);
node.set("created", System.currentTimeMillis());
node.save();
_accounts.put(playerId, account);
}
return account;
}
}
@Override
public boolean deleteAccount(UUID playerId) {
PreCon.notNull(playerId);
if (_isDisposed)
throw new IllegalStateException("Cannot use a disposed item bank.");
synchronized (_sync) {
IBankItemsAccount account = _accounts.remove(playerId);
if (account == null)
return false;
_dataNode.getNode(playerId.toString()).remove();
_dataNode.save();
return true;
}
}
@Override
public boolean isDisposed() {
return _isDisposed;
}
@Override
public void dispose() {
if (_isDisposed)
return;
synchronized (_sync) {
if (_isDisposed)
return;
String fileName = Bukkit.getOnlineMode() ? _name : "offline-" + _name;
DataStorage.remove(Nucleus.getPlugin(), new DataPath("bankitems.banks." + fileName));
_dataNode.remove();
_dataNode.save();
_isDisposed = true;
}
}
@Nullable
BankItemsAccount loadAccount (UUID playerId) {
if (!_accountsNode.hasNode(playerId.toString()))
return null;
return new BankItemsAccount(playerId, null, _accountsNode.getNode(playerId.toString()));
}
void updateLastAccess() {
_lastAccess = System.currentTimeMillis();
_dataNode.set("last-access", _lastAccess);
}
}
| |
/* 1: */ package com.usst.app.order.cashBasis.pay.action;
/* 15: */ import java.util.ArrayList;
/* 16: */ import java.util.HashMap;
/* 17: */ import java.util.List;
/* 18: */ import java.util.Map;
/* 19: */ import org.apache.commons.lang.StringUtils;
/* 20: */ import org.apache.log4j.Logger;
import com.usst.app.baseInfo.bankAccount.service.BankAccountService;
import com.usst.app.baseInfo.supplier.model.Supplier;
import com.usst.app.baseInfo.supplier.service.SupplierService;
import com.usst.app.component.serialNumber.service.SerialNumberService;
import com.usst.app.customer.model.Customer;
import com.usst.app.order.cashBasis.pay.model.CashItem;
import com.usst.app.order.cashBasis.pay.model.Pay;
import com.usst.app.order.cashBasis.pay.service.CashItemService;
import com.usst.app.order.cashBasis.pay.service.PayService;
import com.usst.app.system.user.model.SysUser;
import com.usst.code.struct.BaseAction;
import com.usst.code.util.PageInfo;
/* 21: */
/* 22: */ public class PayAction
/* 23: */ extends BaseAction
/* 24: */ {
/* 25: */ private static final long serialVersionUID = 1L;
/* 26: 31 */ private static final Logger logger = Logger.getLogger(PayAction.class);
/* 27: */ private Pay pay;
/* 28: */ private PayService payService;
/* 29: */ private CashItem cashItem;
/* 30: */ private CashItemService cashItemService;
/* 31: */ private SerialNumberService serialNumberService;
/* 32: */ private BankAccountService bankAccountService;
/* 33: */ private Customer customer;
/* 34: */ private Supplier supplier;
/* 35: */ private SupplierService supplierService;
/* 36: */ private double[] moneyArr;
/* 37: */ private String[] bankAccountCodeArr;
/* 38: */ private String[] bankAccountIdArr;
/* 39: */ private String[] accountArr;
/* 40: */ private String[] bankAccountNameArr;
/* 41: */ private String[] accountHolderArr;
/* 42: */ private String[] bankArr;
/* 43: */ private String[] remarkArr;
/* 44: */
/* 45: */ public String list()
/* 46: */ {
/* 47: 55 */ return "list_pay";
/* 48: */ }
/* 49: */
/* 50: */ public String listJosn()
/* 51: */ {
/* 52: 65 */ logger.info("start list pay");
/* 53: 66 */ List<Pay> resultList = null;
/* 54: 67 */ int totalRows = 0;
/* 55: */ try
/* 56: */ {
/* 57: 70 */ PageInfo pageInfo = createPageInfo();
/* 58: 71 */ if (this.pay == null) {
/* 59: 72 */ this.pay = new Pay();
/* 60: */ }
/* 61: 74 */ resultList = this.payService.pageList(pageInfo, this.pay, true);
/* 62: 75 */ totalRows = pageInfo.getCount();
/* 63: */ }
/* 64: */ catch (Exception e)
/* 65: */ {
/* 66: 77 */ logger.error("error occur when list pay", e);
/* 67: */ }
/* 68: 80 */ if (resultList == null) {
/* 69: 81 */ resultList = new ArrayList();
/* 70: */ }
/* 71: 83 */ this.jsonMap = new HashMap();
/* 72: 84 */ this.jsonMap.put("total", Integer.valueOf(totalRows));
/* 73: 85 */ this.jsonMap.put("rows", resultList);
/* 74: 86 */ return "success";
/* 75: */ }
/* 76: */
/* 77: */ public String edit()
/* 78: */ {
/* 79: 97 */ SysUser loginMan = getSessionUserInfo();
/* 80: 98 */ if (this.pay == null) {
/* 81: 99 */ this.pay = new Pay();
/* 82: */ }
/* 83: */ try
/* 84: */ {
/* 85:103 */ if (StringUtils.isBlank(this.pay.getId()))
/* 86: */ {
/* 87:104 */ this.pay.setState("c");
/* 88:105 */ initModel(true, this.pay, loginMan);
/* 89:106 */ this.pay.setHandlerId(loginMan.getId());
/* 90:107 */ this.pay.setHandlerName(loginMan.getName());
/* 91:108 */ this.pay.setDeptId(loginMan.getDeptId());
/* 92:109 */ this.pay.setDeptName(loginMan.getDeptName());
/* 93: */ try
/* 94: */ {
/* 95:111 */ this.pay.setCode(this.serialNumberService.getSerialNumberByDate("FKD", "pay"));
/* 96: */ }
/* 97: */ catch (Exception e)
/* 98: */ {
/* 99:113 */ logger.error("error occur when get code", e);
/* 100: */ }
/* 101: */ }
/* 102: */ else
/* 103: */ {
/* 104:116 */ this.pay = ((Pay)this.payService.getModel(this.pay.getId()));
/* 105:117 */ initModel(false, this.pay, loginMan);
/* 106: */ }
/* 107: */ }
/* 108: */ catch (Exception e)
/* 109: */ {
/* 110:120 */ logger.error("error occur when list pay", e);
/* 111:121 */ responseFlag(false);
/* 112: */ }
/* 113:123 */ return "edit_pay";
/* 114: */ }
/* 115: */
/* 116: */ public void save()
/* 117: */ {
/* 118:133 */ logger.info("start to update pay information");
/* 119:134 */ if (this.pay == null) {
/* 120:135 */ this.pay = new Pay();
/* 121: */ }
/* 122: */ try
/* 123: */ {
/* 124:138 */ if (StringUtils.isBlank(this.pay.getId()))
/* 125: */ {
/* 126:139 */ this.pay.setId(this.payService.makeId());
/* 127:140 */ this.payService.insert(this.pay);
/* 128: */ }
/* 129: */ else
/* 130: */ {
/* 131:142 */ this.payService.update(this.pay);
/* 132: */ }
/* 133:144 */ responseFlag(true);
/* 134: */ }
/* 135: */ catch (Exception e)
/* 136: */ {
/* 137:146 */ logger.info("error occur when save pay information");
/* 138:147 */ e.printStackTrace();
/* 139:148 */ responseFlag(false);
/* 140: */ }
/* 141: */ try
/* 142: */ {
/* 143:151 */ this.cashItemService.deleteByIntoId(this.pay.getId());
/* 144: */ }
/* 145: */ catch (Exception e)
/* 146: */ {
/* 147:153 */ responseFlag(false);
/* 148:154 */ logger.error("error occur when delete pay", e);
/* 149: */ }
/* 150:157 */ String orderId = this.pay.getId();
/* 151:158 */ if ((this.bankAccountIdArr != null) && (this.bankAccountIdArr.length != 0)) {
/* 152:159 */ for (int i = 0; i < this.bankAccountIdArr.length; i++)
/* 153: */ {
/* 154:160 */ CashItem cashItem = new CashItem();
/* 155:161 */ cashItem.setOrderId(orderId);
/* 156:162 */ cashItem.setMoney(Double.valueOf(this.moneyArr[i]));
/* 157:163 */ cashItem.setRemark(this.remarkArr[i]);
/* 158:164 */ cashItem.setAccount(this.accountArr[i]);
/* 159:165 */ cashItem.setAccountHolder(this.accountHolderArr[i]);
/* 160:166 */ cashItem.setBank(this.bankArr[i]);
/* 161:167 */ cashItem.setBankAccountId(this.bankAccountIdArr[i]);
/* 162:168 */ cashItem.setBankAccountCode(this.bankAccountCodeArr[i]);
/* 163:169 */ cashItem.setBankAccountName(this.bankAccountNameArr[i]);
/* 164:170 */ cashItem.setSort(Integer.valueOf(i));
/* 165: */ try
/* 166: */ {
/* 167:172 */ this.cashItemService.insert(cashItem);
/* 168: */ }
/* 169: */ catch (Exception e)
/* 170: */ {
/* 171:174 */ responseFlag(false);
/* 172:175 */ logger.error("error occur when insert a cashItem", e);
/* 173: */ }
/* 174:177 */ if ("s".equals(this.pay.getState())) {
/* 175: */ try
/* 176: */ {
/* 177:179 */ this.bankAccountService.updateMoney(this.bankAccountIdArr[i], Double.valueOf(0.0D - this.moneyArr[i]));
/* 178: */ }
/* 179: */ catch (Exception e)
/* 180: */ {
/* 181:181 */ responseFlag(false);
/* 182:182 */ logger.error("error occur when insert a cashItem", e);
/* 183: */ }
/* 184: */ }
/* 185: */ }
/* 186: */ }
/* 187:187 */ if ("s".equals(this.pay.getState()))
/* 188: */ {
/* 189:189 */ String customerId = this.pay.getCustomerId();
/* 190:190 */ Supplier supplier = (Supplier)this.supplierService.getModel(customerId);
/* 191:191 */ if (supplier != null) {
/* 192: */ try
/* 193: */ {
/* 194:193 */ this.supplierService.updateReceivables(customerId, Double.valueOf(0.0D + this.pay.getMoneyPayment().doubleValue()));
/* 195: */ }
/* 196: */ catch (Exception e)
/* 197: */ {
/* 198:195 */ logger.error("error occur when update supplier money", e);
/* 199:196 */ responseFlag(false);
/* 200: */ }
/* 201: */ }
/* 202: */ }
/* 203: */ }
/* 204: */
/* 205: */ public void delete()
/* 206: */ {
/* 207:218 */ SysUser loginMan = getSessionUserInfo();
/* 208: */ try
/* 209: */ {
/* 210:220 */ if (this.pay == null) {
/* 211:221 */ this.pay = new Pay();
/* 212: */ }
/* 213:223 */ this.cashItemService.deleteByIntoId(this.pay.getId());
/* 214:224 */ this.payService.delete(this.pay.getId());
/* 215:225 */ logger.info(loginMan.getCode() + " delete pay,id:" + this.pay.getId());
/* 216:226 */ responseFlag(true);
/* 217: */ }
/* 218: */ catch (Exception e)
/* 219: */ {
/* 220:228 */ responseFlag(false);
/* 221:229 */ logger.error("error occur when delete a pay", e);
/* 222: */ }
/* 223: */ }
/* 224: */
/* 225: */ public Pay getPay()
/* 226: */ {
/* 227:234 */ return this.pay;
/* 228: */ }
/* 229: */
/* 230: */ public void setPay(Pay pay)
/* 231: */ {
/* 232:237 */ this.pay = pay;
/* 233: */ }
/* 234: */
/* 235: */ public PayService getPayService()
/* 236: */ {
/* 237:240 */ return this.payService;
/* 238: */ }
/* 239: */
/* 240: */ public void setPayService(PayService payService)
/* 241: */ {
/* 242:243 */ this.payService = payService;
/* 243: */ }
/* 244: */
/* 245: */ public SerialNumberService getSerialNumberService()
/* 246: */ {
/* 247:246 */ return this.serialNumberService;
/* 248: */ }
/* 249: */
/* 250: */ public void setSerialNumberService(SerialNumberService serialNumberService)
/* 251: */ {
/* 252:249 */ this.serialNumberService = serialNumberService;
/* 253: */ }
/* 254: */
/* 255: */ public double[] getMoneyArr()
/* 256: */ {
/* 257:252 */ return this.moneyArr;
/* 258: */ }
/* 259: */
/* 260: */ public void setMoneyArr(double[] moneyArr)
/* 261: */ {
/* 262:255 */ this.moneyArr = moneyArr;
/* 263: */ }
/* 264: */
/* 265: */ public String[] getRemarkArr()
/* 266: */ {
/* 267:258 */ return this.remarkArr;
/* 268: */ }
/* 269: */
/* 270: */ public void setRemarkArr(String[] remarkArr)
/* 271: */ {
/* 272:261 */ this.remarkArr = remarkArr;
/* 273: */ }
/* 274: */
/* 275: */ public CashItem getCashItem()
/* 276: */ {
/* 277:265 */ return this.cashItem;
/* 278: */ }
/* 279: */
/* 280: */ public void setCashItem(CashItem cashItem)
/* 281: */ {
/* 282:269 */ this.cashItem = cashItem;
/* 283: */ }
/* 284: */
/* 285: */ public void setCashItemService(CashItemService cashItemService)
/* 286: */ {
/* 287:273 */ this.cashItemService = cashItemService;
/* 288: */ }
/* 289: */
/* 290: */ public String[] getBankAccountCodeArr()
/* 291: */ {
/* 292:277 */ return this.bankAccountCodeArr;
/* 293: */ }
/* 294: */
/* 295: */ public void setBankAccountCodeArr(String[] bankAccountCodeArr)
/* 296: */ {
/* 297:281 */ this.bankAccountCodeArr = bankAccountCodeArr;
/* 298: */ }
/* 299: */
/* 300: */ public String[] getBankAccountIdArr()
/* 301: */ {
/* 302:285 */ return this.bankAccountIdArr;
/* 303: */ }
/* 304: */
/* 305: */ public void setBankAccountIdArr(String[] bankAccountIdArr)
/* 306: */ {
/* 307:289 */ this.bankAccountIdArr = bankAccountIdArr;
/* 308: */ }
/* 309: */
/* 310: */ public String[] getAccountArr()
/* 311: */ {
/* 312:293 */ return this.accountArr;
/* 313: */ }
/* 314: */
/* 315: */ public void setAccountArr(String[] accountArr)
/* 316: */ {
/* 317:297 */ this.accountArr = accountArr;
/* 318: */ }
/* 319: */
/* 320: */ public String[] getBankAccountNameArr()
/* 321: */ {
/* 322:301 */ return this.bankAccountNameArr;
/* 323: */ }
/* 324: */
/* 325: */ public void setBankAccountNameArr(String[] bankAccountNameArr)
/* 326: */ {
/* 327:305 */ this.bankAccountNameArr = bankAccountNameArr;
/* 328: */ }
/* 329: */
/* 330: */ public String[] getAccountHolderArr()
/* 331: */ {
/* 332:309 */ return this.accountHolderArr;
/* 333: */ }
/* 334: */
/* 335: */ public void setAccountHolderArr(String[] accountHolderArr)
/* 336: */ {
/* 337:313 */ this.accountHolderArr = accountHolderArr;
/* 338: */ }
/* 339: */
/* 340: */ public String[] getBankArr()
/* 341: */ {
/* 342:317 */ return this.bankArr;
/* 343: */ }
/* 344: */
/* 345: */ public void setBankArr(String[] bankArr)
/* 346: */ {
/* 347:321 */ this.bankArr = bankArr;
/* 348: */ }
/* 349: */
/* 350: */ public void setBankAccountService(BankAccountService bankAccountService)
/* 351: */ {
/* 352:325 */ this.bankAccountService = bankAccountService;
/* 353: */ }
/* 354: */
/* 355: */ public void setSupplierService(SupplierService supplierService)
/* 356: */ {
/* 357:329 */ this.supplierService = supplierService;
/* 358: */ }
/* 359: */
/* 360: */ public Customer getCustomer()
/* 361: */ {
/* 362:333 */ return this.customer;
/* 363: */ }
/* 364: */
/* 365: */ public void setCustomer(Customer customer)
/* 366: */ {
/* 367:337 */ this.customer = customer;
/* 368: */ }
/* 369: */
/* 370: */ public Supplier getSupplier()
/* 371: */ {
/* 372:341 */ return this.supplier;
/* 373: */ }
/* 374: */
/* 375: */ public void setSupplier(Supplier supplier)
/* 376: */ {
/* 377:345 */ this.supplier = supplier;
/* 378: */ }
/* 379: */ }
/* Location: D:\Program Files\apache-tomcat-8.0.20\webapps\demo2\WEB-INF\classes\
* Qualified Name: com.usst.app.order.cashBasis.pay.action.PayAction
* JD-Core Version: 0.7.0.1
*/
| |
package com.android.supervolley;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
abstract class ParameterHandler<T> {
abstract void apply(RequestBuilder builder, T value) throws IOException;
final ParameterHandler<Iterable<T>> iterable() {
return new ParameterHandler<Iterable<T>>() {
@Override
void apply(RequestBuilder builder, Iterable<T> values) throws IOException {
if (values == null) return; // Skip null values.
for (T value : values) {
ParameterHandler.this.apply(builder, value);
}
}
};
}
final ParameterHandler<Object> array() {
return new ParameterHandler<Object>() {
@Override
void apply(RequestBuilder builder, Object values) throws IOException {
if (values == null) return; // Skip null values.
for (int i = 0, size = Array.getLength(values); i < size; i++) {
//noinspection unchecked
ParameterHandler.this.apply(builder, (T) Array.get(values, i));
}
}
};
}
static final class RelativeUrl extends ParameterHandler<Object> {
@Override
void apply(RequestBuilder builder, Object value) {
builder.setRelativeUrl(value);
}
}
static final class Header<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
Header(String name, Converter<T, String> valueConverter) {
this.name = Utils.checkNotNull(name, "name == null");
this.valueConverter = valueConverter;
}
@Override
void apply(RequestBuilder builder, T value) throws IOException {
if (value == null) return; // Skip null values.
builder.addHeader(name, valueConverter.convert(value));
}
}
static final class Path<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Path(String name, Converter<T, String> valueConverter, boolean encoded) {
this.name = Utils.checkNotNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, T value) throws IOException {
if (value == null) {
throw new IllegalArgumentException(
"Path parameter \"" + name + "\" value must not be null.");
}
builder.addPathParam(name, valueConverter.convert(value), encoded);
}
}
static final class Query<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Query(String name, Converter<T, String> valueConverter, boolean encoded) {
this.name = Utils.checkNotNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, T value) throws IOException {
if (value == null) return; // Skip null values.
builder.addQueryParam(name, valueConverter.convert(value), encoded);
}
}
static final class QueryMap<T> extends ParameterHandler<Map<String, T>> {
private final Converter<T, String> valueConverter;
private final boolean encoded;
QueryMap(Converter<T, String> valueConverter, boolean encoded) {
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
if (value == null) {
throw new IllegalArgumentException("Query map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw new IllegalArgumentException("Query map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw new IllegalArgumentException(
"Query map contained null value for key '" + entryKey + "'.");
}
builder.addQueryParam(entryKey, valueConverter.convert(entryValue), encoded);
}
}
}
static final class HeaderMap<T> extends ParameterHandler<Map<String, T>> {
private final Converter<T, String> valueConverter;
HeaderMap(Converter<T, String> valueConverter) {
this.valueConverter = valueConverter;
}
@Override
void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
if (value == null) {
throw new IllegalArgumentException("Header map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String headerName = entry.getKey();
if (headerName == null) {
throw new IllegalArgumentException("Header map contained null key.");
}
T headerValue = entry.getValue();
if (headerValue == null) {
throw new IllegalArgumentException(
"Header map contained null value for key '" + headerName + "'.");
}
builder.addHeader(headerName, valueConverter.convert(headerValue));
}
}
}
static final class Field<T> extends ParameterHandler<T> {
private final String name;
private final Converter<T, String> valueConverter;
private final boolean encoded;
Field(String name, Converter<T, String> valueConverter, boolean encoded) {
this.name = Utils.checkNotNull(name, "name == null");
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, T value) throws IOException {
if (value == null) return; // Skip null values.
builder.addFormField(name, valueConverter.convert(value), encoded);
}
}
static final class FieldMap<T> extends ParameterHandler<Map<String, T>> {
private final Converter<T, String> valueConverter;
private final boolean encoded;
FieldMap(Converter<T, String> valueConverter, boolean encoded) {
this.valueConverter = valueConverter;
this.encoded = encoded;
}
@Override
void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
if (value == null) {
throw new IllegalArgumentException("Field map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw new IllegalArgumentException("Field map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw new IllegalArgumentException(
"Field map contained null value for key '" + entryKey + "'.");
}
builder.addFormField(entryKey, valueConverter.convert(entryValue), encoded);
}
}
}
static final class Part<T> extends ParameterHandler<T> {
private final Headers headers;
private final Converter<T, RequestBody> converter;
Part(Headers headers, Converter<T, RequestBody> converter) {
this.headers = headers;
this.converter = converter;
}
@Override
void apply(RequestBuilder builder, T value) {
if (value == null) return; // Skip null values.
RequestBody body;
try {
body = converter.convert(value);
} catch (IOException e) {
throw new RuntimeException("Unable to convert " + value + " to RequestBody", e);
}
builder.addPart(headers, body);
}
}
static final class RawPart extends ParameterHandler<MultipartBody.Part> {
static final RawPart INSTANCE = new RawPart();
private RawPart() {
}
@Override
void apply(RequestBuilder builder, MultipartBody.Part value) throws IOException {
if (value != null) { // Skip null values.
builder.addPart(value);
}
}
}
static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
private final Converter<T, RequestBody> valueConverter;
private final String transferEncoding;
PartMap(Converter<T, RequestBody> valueConverter, String transferEncoding) {
this.valueConverter = valueConverter;
this.transferEncoding = transferEncoding;
}
@Override
void apply(RequestBuilder builder, Map<String, T> value) throws IOException {
if (value == null) {
throw new IllegalArgumentException("Part map was null.");
}
for (Map.Entry<String, T> entry : value.entrySet()) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw new IllegalArgumentException("Part map contained null key.");
}
T entryValue = entry.getValue();
if (entryValue == null) {
throw new IllegalArgumentException(
"Part map contained null value for key '" + entryKey + "'.");
}
Headers headers = Headers.of(
"Content-Disposition", "form-data; name=\"" + entryKey + "\"",
"Content-Transfer-Encoding", transferEncoding);
builder.addPart(headers, valueConverter.convert(entryValue));
}
}
}
static final class Body<T> extends ParameterHandler<T> {
private final Converter<T, RequestBody> converter;
Body(Converter<T, RequestBody> converter) {
this.converter = converter;
}
@Override
void apply(RequestBuilder builder, T value) {
if (value == null) {
throw new IllegalArgumentException("Body parameter value must not be null.");
}
RequestBody body;
try {
body = converter.convert(value);
} catch (IOException e) {
throw new RuntimeException("Unable to convert " + value + " to RequestBody", e);
}
builder.setBody(body);
}
}
}
| |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.core;
import com.hazelcast.cardinality.CardinalityEstimator;
import com.hazelcast.config.Config;
import com.hazelcast.durableexecutor.DurableExecutorService;
import com.hazelcast.logging.LoggingService;
import com.hazelcast.mapreduce.JobTracker;
import com.hazelcast.quorum.QuorumService;
import com.hazelcast.reliableidgen.ReliableIdGenerator;
import com.hazelcast.replicatedmap.ReplicatedMapCantBeCreatedOnLiteMemberException;
import com.hazelcast.ringbuffer.Ringbuffer;
import com.hazelcast.scheduledexecutor.IScheduledExecutorService;
import com.hazelcast.transaction.HazelcastXAResource;
import com.hazelcast.transaction.TransactionContext;
import com.hazelcast.transaction.TransactionException;
import com.hazelcast.transaction.TransactionOptions;
import com.hazelcast.transaction.TransactionalTask;
import java.util.Collection;
import java.util.concurrent.ConcurrentMap;
/**
* Hazelcast instance. Each Hazelcast instance is a member (node) in a cluster.
* Multiple Hazelcast instances can be created on a JVM.
* Each Hazelcast instance has its own socket, threads.
*
* @see Hazelcast#newHazelcastInstance(Config config)
*/
public interface HazelcastInstance {
/**
* Returns the name of this Hazelcast instance.
*
* @return name of this Hazelcast instance
*/
String getName();
/**
* Returns the distributed queue instance with the specified name.
*
* @param name name of the distributed queue
* @return distributed queue instance with the specified name
*/
<E> IQueue<E> getQueue(String name);
/**
* Returns the distributed topic instance with the specified name.
*
* @param name name of the distributed topic
* @return distributed topic instance with the specified name
*/
<E> ITopic<E> getTopic(String name);
/**
* Returns the distributed set instance with the specified name.
*
* @param name name of the distributed set
* @return distributed set instance with the specified name
*/
<E> ISet<E> getSet(String name);
/**
* Returns the distributed list instance with the specified name.
* Index based operations on the list are not supported.
*
* @param name name of the distributed list
* @return distributed list instance with the specified name
*/
<E> IList<E> getList(String name);
/**
* Returns the distributed map instance with the specified name.
*
* @param name name of the distributed map
* @return distributed map instance with the specified name
*/
<K, V> IMap<K, V> getMap(String name);
/**
* Returns the replicated map instance with the specified name.
*
* @param name name of the distributed map
* @return replicated map instance with specified name
* @throws ReplicatedMapCantBeCreatedOnLiteMemberException if it is called on a lite member
* @since 3.2
*/
<K, V> ReplicatedMap<K, V> getReplicatedMap(String name);
/**
* Returns the job tracker instance with the specified name.
*
* @param name name of the job tracker
* @return job tracker instance with the specified name
* @since 3.2
* @deprecated MapReduce is deprecated and will be removed in 4.0.
* For map aggregations, you can use {@link com.hazelcast.aggregation.Aggregator} on IMap.
* For general data processing, it is superseded by <a href="http://jet.hazelcast.org">Hazelcast Jet</a>.
*/
JobTracker getJobTracker(String name);
/**
* Returns the distributed multimap instance with the specified name.
*
* @param name name of the distributed multimap
* @return distributed multimap instance with the specified name
*/
<K, V> MultiMap<K, V> getMultiMap(String name);
/**
* Returns the distributed lock instance for the specified key object.
* The specified object is considered to be the key for this lock.
* So keys are considered equals cluster-wide as long as
* they are serialized to the same byte array such as String, long,
* Integer.
* <p/>
* Locks are fail-safe. If a member holds a lock and some of the
* members go down, the cluster will keep your locks safe and available.
* Moreover, when a member leaves the cluster, all the locks acquired
* by this dead member will be removed so that these locks can be
* available for live members immediately.
* <pre>
* Lock lock = hazelcastInstance.getLock("PROCESS_LOCK");
* lock.lock();
* try {
* // process
* } finally {
* lock.unlock();
* }
* </pre>
*
* @param key key of the lock instance
* @return distributed lock instance for the specified key.
*/
ILock getLock(String key);
/**
* Returns the distributed Ringbuffer instance with the specified name.
*
* @param name name of the distributed Ringbuffer
* @return distributed RingBuffer instance with the specified name
*/
<E> Ringbuffer<E> getRingbuffer(String name);
/**
* Returns the reliable ReliableTopic instance with the specified name.
*
* @param name name of the reliable ITopic
* @return the reliable ITopic
*/
<E> ITopic<E> getReliableTopic(String name);
/**
* Returns the Cluster that this Hazelcast instance is part of.
* Cluster interface allows you to add a listener for membership
* events and to learn more about the cluster that this Hazelcast
* instance is part of.
*
* @return the cluster that this Hazelcast instance is part of
*/
Cluster getCluster();
/**
* Returns the local Endpoint which this HazelcastInstance belongs to.
* <p>
* Returned endpoint will be a {@link Member} instance for cluster nodes
* and a {@link Client} instance for clients.
*
* @return the local {@link Endpoint} which this HazelcastInstance belongs to
* @see Member
* @see Client
*/
Endpoint getLocalEndpoint();
/**
* Returns the distributed executor service for the given name.
* Executor service enables you to run your <tt>Runnable</tt>s and <tt>Callable</tt>s
* on the Hazelcast cluster.
* <p>
* <p><b>Note:</b> Note that it doesn't support {@code invokeAll/Any}
* and doesn't have standard shutdown behavior</p>
*
* @param name name of the executor service
* @return the distributed executor service for the given name
*/
IExecutorService getExecutorService(String name);
/**
* Returns the durable executor service for the given name.
* DurableExecutor service enables you to run your <tt>Runnable</tt>s and <tt>Callable</tt>s
* on the Hazelcast cluster.
* <p>
* <p><b>Note:</b> Note that it doesn't support {@code invokeAll/Any}
* and doesn't have standard shutdown behavior</p>
*
* @param name name of the executor service
* @return the durable executor service for the given name
*/
DurableExecutorService getDurableExecutorService(String name);
/**
* Executes the given transactional task in current thread using default options
* and returns the result of the task.
*
* @param task the transactional task to be executed
* @param <T> return type of task
* @return result of the transactional task
* @throws TransactionException if an error occurs during transaction.
*/
<T> T executeTransaction(TransactionalTask<T> task) throws TransactionException;
/**
* Executes the given transactional task in current thread using given options
* and returns the result of the task.
*
* @param options options for this transactional task
* @param task task to be executed
* @param <T> return type of task
* @return result of the transactional task
* @throws TransactionException if an error occurs during transaction.
*/
<T> T executeTransaction(TransactionOptions options, TransactionalTask<T> task) throws TransactionException;
/**
* Creates a new TransactionContext associated with the current thread using default options.
*
* @return new TransactionContext associated with the current thread
*/
TransactionContext newTransactionContext();
/**
* Creates a new TransactionContext associated with the current thread with given options.
*
* @param options options for this transaction
* @return new TransactionContext associated with the current thread
*/
TransactionContext newTransactionContext(TransactionOptions options);
/**
* Creates cluster-wide unique ID generator. Generated IDs are {@code long} primitive values
* between <tt>0</tt> and <tt>Long.MAX_VALUE</tt>. ID generation occurs almost at the speed of
* local <tt>AtomicLong.incrementAndGet()</tt>. Generated IDs are unique during the life
* cycle of the cluster. If the entire cluster is restarted, IDs start from <tt>0</tt> again.
*
* @param name name of the {@link IdGenerator}
* @return IdGenerator for the given name
*
* @deprecated The implementation can produce duplicate IDs in case of network split, even
* with split-brain protection enabled (during short window while split-brain is detected).
* Use {@link #getReliableIdGenerator(String)} for an alternative implementation which does not
* suffer from this problem.
*/
@Deprecated
IdGenerator getIdGenerator(String name);
/**
* Creates cluster-wide unique ID generator. Generated IDs are {@code long} primitive values
* and are k-ordered (roughly ordered). IDs are in the range from {@code Long.MIN_VALUE} to
* {@code Long.MAX_VALUE}. This type of generator is generally known as Flake ID generator.
* <p>
* The IDs contain timestamp component and a node ID component, which is assigned when the member
* joins the cluster. This allows the IDs to be ordered and unique without any coordination between
* members, which makes the generator safe even in split-brain scenario (for caveats,
* {@link com.hazelcast.internal.cluster.ClusterService#getMemberListJoinVersion() see here}).
* <p>
* For more details and caveats, see class documentation for {@link ReliableIdGenerator}.
* <p>
* Note: this implementation doesn't share namespace with {@link #getIdGenerator(String)}.
* That is, {@code getIdGenerator("a")} is distinct from {@code getReliableIdGenerator("a")}.
*
* @param name name of the {@link IdGenerator}
* @return ReliableIdGenerator for the given name
*/
ReliableIdGenerator getReliableIdGenerator(String name);
/**
* Creates cluster-wide atomic long. Hazelcast {@link IAtomicLong} is distributed
* implementation of <tt>java.util.concurrent.atomic.AtomicLong</tt>.
*
* @param name name of the {@link IAtomicLong} proxy
* @return IAtomicLong proxy for the given name
*/
IAtomicLong getAtomicLong(String name);
/**
* Creates cluster-wide atomic reference. Hazelcast {@link IAtomicReference} is distributed
* implementation of <tt>java.util.concurrent.atomic.AtomicReference</tt>.
*
* @param name name of the {@link IAtomicReference} proxy
* @return {@link IAtomicReference} proxy for the given name
*/
<E> IAtomicReference<E> getAtomicReference(String name);
/**
* Creates cluster-wide CountDownLatch. Hazelcast {@link ICountDownLatch} is distributed
* implementation of <tt>java.util.concurrent.CountDownLatch</tt>.
*
* @param name name of the {@link ICountDownLatch} proxy
* @return {@link ICountDownLatch} proxy for the given name
*/
ICountDownLatch getCountDownLatch(String name);
/**
* Creates cluster-wide semaphore. Hazelcast {@link ISemaphore} is distributed
* implementation of <tt>java.util.concurrent.Semaphore</tt>.
*
* @param name name of the {@link ISemaphore} proxy
* @return {@link ISemaphore} proxy for the given name
*/
ISemaphore getSemaphore(String name);
/**
* Returns all {@link DistributedObject}'s such as; queue, map, set, list, topic, lock, multimap.
*
* @return the collection of instances created by Hazelcast.
*/
Collection<DistributedObject> getDistributedObjects();
/**
* Adds a Distributed Object listener which will be notified when a
* new {@link DistributedObject} will be created or destroyed.
*
* @param distributedObjectListener instance listener
* @return returns registration ID
*/
String addDistributedObjectListener(DistributedObjectListener distributedObjectListener);
/**
* Removes the specified Distributed Object listener. Returns silently
* if the specified instance listener does not exist.
*
* @param registrationId ID of listener registration
* @return {@code true} if registration is removed, {@code false} otherwise
*/
boolean removeDistributedObjectListener(String registrationId);
/**
* Returns the configuration of this Hazelcast instance.
*
* @return configuration of this Hazelcast instance
*/
Config getConfig();
/**
* Returns the partition service of this Hazelcast instance.
* InternalPartitionService allows you to introspect current partitions in the
* cluster, partition the owner members, and listen for partition migration events.
*
* @return the partition service of this Hazelcast instance
*/
PartitionService getPartitionService();
/**
* Returns the quorum service of this Hazelcast instance.
* <p>
* Quorum service can be used to retrieve quorum callbacks which let you to notify quorum results of your own to
* the cluster quorum service.
*
* @return the quorum service of this Hazelcast instance
*/
QuorumService getQuorumService();
/**
* Returns the client service of this Hazelcast instance.
* Client service allows you to get information about connected clients.
*
* @return the {@link ClientService} of this Hazelcast instance.
*/
ClientService getClientService();
/**
* Returns the logging service of this Hazelcast instance.
* <p>
* LoggingService allows you to listen for LogEvents generated by Hazelcast runtime.
* You can log the events somewhere or take action based on the message.
*
* @return the logging service of this Hazelcast instance
*/
LoggingService getLoggingService();
/**
* Returns the lifecycle service for this instance.
* <p>
* LifecycleService allows you to shutdown this HazelcastInstance and listen for the lifecycle events.
*
* @return the lifecycle service for this instance
*/
LifecycleService getLifecycleService();
/**
* @param serviceName name of the service
* @param name name of the object
* @param <T> type of the DistributedObject
* @return DistributedObject created by the service
*/
<T extends DistributedObject> T getDistributedObject(String serviceName, String name);
/**
* Returns a ConcurrentMap that can be used to add user-context to the HazelcastInstance. This can be used
* to store dependencies that otherwise are hard to obtain. HazelcastInstance can be
* obtained by implementing a {@link HazelcastInstanceAware} interface when submitting a Runnable/Callable to
* Hazelcast ExecutorService. By storing the dependencies in the user-context, they can be retrieved as soon
* as you have a reference to the HazelcastInstance.
* <p>
* This structure is purely local and Hazelcast remains agnostic abouts its content.
*
* @return a ConcurrentMap that can be used to add user-context to the HazelcastInstance.
*/
ConcurrentMap<String, Object> getUserContext();
/**
* Gets xaResource which will participate in XATransaction.
*
* @return the xaResource
*/
HazelcastXAResource getXAResource();
/**
* Obtain the {@link ICacheManager} that provides access to JSR-107 (JCache) caches configured on a Hazelcast cluster.
* <p>
* Note that this method does not return a JCache {@code CacheManager}; to obtain a JCache
* {@link javax.cache.CacheManager} use JCache standard API.
*
* @return the Hazelcast {@link ICacheManager}
* @see ICacheManager
*/
ICacheManager getCacheManager();
/**
* Obtain a {@link CardinalityEstimator} with the given name.
* <p>
* The estimator can be used to efficiently estimate the cardinality of <strong>unique</strong> entities
* in big data sets, without the need of storing them.
* <p>
* The estimator is based on a HyperLogLog++ data-structure.
*
* @param name the name of the estimator
* @return a {@link CardinalityEstimator}
*/
CardinalityEstimator getCardinalityEstimator(String name);
/**
* Returns the {@link IScheduledExecutorService} scheduled executor service for the given name.
* ScheduledExecutor service enables you to schedule your <tt>Runnable</tt>s and <tt>Callable</tt>s
* on the Hazelcast cluster.
*
* @param name name of the executor service
* @return the scheduled executor service for the given name
*/
IScheduledExecutorService getScheduledExecutorService(String name);
/**
* Shuts down this HazelcastInstance. For more information see {@link com.hazelcast.core.LifecycleService#shutdown()}.
*/
void shutdown();
}
| |
/**
* OWASP Enterprise Security API (ESAPI)
*
* This file is part of the Open Web Application Security Project (OWASP)
* Enterprise Security API (ESAPI) project. For details, please see
* <a href="http://www.owasp.org/index.php/ESAPI">http://www.owasp.org/index.php/ESAPI</a>.
*
* Copyright (c) 2007 - The OWASP Foundation
*
* The ESAPI is published by OWASP under the BSD license. You should read and accept the
* LICENSE before you use, modify, and/or redistribute this software.
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created 2007
*/
package org.owasp.esapi.reference;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.owasp.esapi.Authenticator;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.User;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.errors.AuthenticationException;
import org.owasp.esapi.errors.EncryptionException;
/**
* The Class AccessReferenceMapTest.
*
* @author Jeff Williams (jeff.williams@aspectsecurity.com)
*/
public class AccessReferenceMapTest extends TestCase {
/**
* Instantiates a new access reference map test.
*
* @param testName
* the test name
*/
public AccessReferenceMapTest(String testName) {
super(testName);
}
/**
* {@inheritDoc}
* @throws Exception
*/
protected void setUp() throws Exception {
// none
}
/**
* {@inheritDoc}
* @throws Exception
*/
protected void tearDown() throws Exception {
// none
}
/**
* Suite.
*
* @return the test
*/
public static Test suite() {
TestSuite suite = new TestSuite(AccessReferenceMapTest.class);
return suite;
}
/**
* Test of update method, of class org.owasp.esapi.AccessReferenceMap.
*
* @throws AuthenticationException
* the authentication exception
* @throws EncryptionException
*/
public void testUpdate() throws AuthenticationException, EncryptionException {
System.out.println("update");
RandomAccessReferenceMap arm = new RandomAccessReferenceMap();
Authenticator auth = ESAPI.authenticator();
String pass = auth.generateStrongPassword();
User u = auth.createUser( "armUpdate", pass, pass );
// test to make sure update returns something
arm.update(auth.getUserNames());
String indirect = arm.getIndirectReference( u.getAccountName() );
if ( indirect == null ) fail();
// test to make sure update removes items that are no longer in the list
auth.removeUser( u.getAccountName() );
arm.update(auth.getUserNames());
indirect = arm.getIndirectReference( u.getAccountName() );
if ( indirect != null ) fail();
// test to make sure old indirect reference is maintained after an update
arm.update(auth.getUserNames());
String newIndirect = arm.getIndirectReference( u.getAccountName() );
assertEquals(indirect, newIndirect);
}
/**
* Test of iterator method, of class org.owasp.esapi.AccessReferenceMap.
*/
public void testIterator() {
System.out.println("iterator");
RandomAccessReferenceMap arm = new RandomAccessReferenceMap();
Authenticator auth = ESAPI.authenticator();
arm.update(auth.getUserNames());
Iterator i = arm.iterator();
while ( i.hasNext() ) {
String userName = (String)i.next();
User u = auth.getUser( userName );
if ( u == null ) fail();
}
}
/**
* Test of getIndirectReference method, of class
* org.owasp.esapi.AccessReferenceMap.
*/
public void testGetIndirectReference() {
System.out.println("getIndirectReference");
String directReference = "234";
Set list = new HashSet();
list.add( "123" );
list.add( directReference );
list.add( "345" );
RandomAccessReferenceMap instance = new RandomAccessReferenceMap( list );
String expResult = directReference;
String result = instance.getIndirectReference(directReference);
assertNotSame(expResult, result);
}
/**
* Test of getDirectReference method, of class
* org.owasp.esapi.AccessReferenceMap.
*
* @throws AccessControlException
* the access control exception
*/
public void testGetDirectReference() throws AccessControlException {
System.out.println("getDirectReference");
String directReference = "234";
Set list = new HashSet();
list.add( "123" );
list.add( directReference );
list.add( "345" );
RandomAccessReferenceMap instance = new RandomAccessReferenceMap( list );
String ind = instance.getIndirectReference(directReference);
String dir = (String)instance.getDirectReference(ind);
assertEquals(directReference, dir);
try {
instance.getDirectReference("invalid");
fail();
} catch( AccessControlException e ) {
// success
}
}
/**
*
* @throws org.owasp.esapi.errors.AccessControlException
*/
public void testAddDirectReference() throws AccessControlException {
System.out.println("addDirectReference");
String directReference = "234";
Set list = new HashSet();
list.add( "123" );
list.add( directReference );
list.add( "345" );
RandomAccessReferenceMap instance = new RandomAccessReferenceMap( list );
String newDirect = instance.addDirectReference("newDirect");
assertNotNull( newDirect );
String ind = instance.addDirectReference(directReference);
String dir = (String)instance.getDirectReference(ind);
assertEquals(directReference, dir);
String newInd = instance.addDirectReference(directReference);
assertEquals(ind, newInd);
}
/**
*
* @throws org.owasp.esapi.errors.AccessControlException
*/
public void testRemoveDirectReference() throws AccessControlException {
System.out.println("removeDirectReference");
String directReference = "234";
Set list = new HashSet();
list.add( "123" );
list.add( directReference );
list.add( "345" );
RandomAccessReferenceMap instance = new RandomAccessReferenceMap( list );
String indirect = instance.getIndirectReference(directReference);
assertNotNull(indirect);
String deleted = instance.removeDirectReference(directReference);
assertEquals(indirect,deleted);
deleted = instance.removeDirectReference("ridiculous");
assertNull(deleted);
}
}
| |
package mekanism.client.nei;
import static codechicken.lib.gui.GuiDraw.changeTexture;
import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import mekanism.client.gui.GuiSolarEvaporationController;
import mekanism.common.ObfuscatedNames;
import mekanism.common.recipe.RecipeHandler.Recipe;
import mekanism.common.recipe.machines.SolarEvaporationRecipe;
import mekanism.common.util.LangUtils;
import mekanism.common.util.MekanismUtils;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.TemplateRecipeHandler;
public class SolarEvaporationRecipeHandler extends BaseRecipeHandler
{
private int ticksPassed;
public static int xOffset = 5;
public static int yOffset = 12;
@Override
public String getRecipeName()
{
return MekanismUtils.localize("gui.solarEvaporationController.short");
}
@Override
public String getOverlayIdentifier()
{
return "solarevaporation";
}
@Override
public String getGuiTexture()
{
return "mekanism:gui/nei/GuiSolarEvaporationController.png";
}
@Override
public Class getGuiClass()
{
return GuiSolarEvaporationController.class;
}
public String getRecipeId()
{
return "mekanism.solarevaporation";
}
public Collection<SolarEvaporationRecipe> getRecipes()
{
return Recipe.SOLAR_EVAPORATION_PLANT.get().values();
}
@Override
public void loadTransferRects()
{
transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(49-xOffset, 20-yOffset, 78, 38), getRecipeId(), new Object[0]));
}
@Override
public void drawBackground(int i)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
changeTexture(getGuiTexture());
drawTexturedModalRect(-2, 0, 3, yOffset, 170, 62);
}
@Override
public void drawExtras(int i)
{
CachedIORecipe recipe = (CachedIORecipe)arecipes.get(i);
drawProgressBar(49-xOffset, 64-yOffset, 176, 59, 78, 8, ticksPassed < 20 ? ticksPassed % 20 / 20.0F : 1.0F, 0);
if(recipe.fluidInput != null)
{
displayGauge(58, 7-xOffset, 14-yOffset, 176, 0, 58, recipe.fluidInput, null);
}
if(recipe.fluidOutput != null)
{
displayGauge(58, 153-xOffset, 14-yOffset, 176, 0, 58, recipe.fluidOutput, null);
}
}
@Override
public void onUpdate()
{
super.onUpdate();
ticksPassed++;
}
@Override
public void loadCraftingRecipes(String outputId, Object... results)
{
if(outputId.equals(getRecipeId()))
{
for(SolarEvaporationRecipe irecipe : getRecipes())
{
arecipes.add(new CachedIORecipe(irecipe));
}
}
else if(outputId.equals("fluid") && results.length == 1 && results[0] instanceof FluidStack)
{
for(SolarEvaporationRecipe irecipe : getRecipes())
{
if(((FluidStack)results[0]).isFluidEqual(irecipe.recipeOutput.output))
{
arecipes.add(new CachedIORecipe(irecipe));
}
}
}
else {
super.loadCraftingRecipes(outputId, results);
}
}
@Override
public void loadUsageRecipes(String inputId, Object... ingredients)
{
if(inputId.equals("fluid") && ingredients.length == 1 && ingredients[0] instanceof FluidStack)
{
for(SolarEvaporationRecipe irecipe : getRecipes())
{
if(irecipe.recipeInput.ingredient.isFluidEqual((FluidStack)ingredients[0]))
{
arecipes.add(new CachedIORecipe(irecipe));
}
}
}
else {
super.loadUsageRecipes(inputId, ingredients);
}
}
@Override
public List<String> handleTooltip(GuiRecipe gui, List<String> currenttip, int recipe)
{
Point point = GuiDraw.getMousePosition();
int xAxis = point.x-(Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiLeft);
int yAxis = point.y-(Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiTop);
if(xAxis >= 7 && xAxis <= 23 && yAxis >= 14+4 && yAxis <= 72+4)
{
currenttip.add(LangUtils.localizeFluidStack(((CachedIORecipe) arecipes.get(recipe)).fluidInput));
}
else if(xAxis >= 153 && xAxis <= 169 && yAxis >= 14+4 && yAxis <= 72+4)
{
currenttip.add(LangUtils.localizeFluidStack(((CachedIORecipe) arecipes.get(recipe)).fluidOutput));
}
return super.handleTooltip(gui, currenttip, recipe);
}
@Override
public boolean keyTyped(GuiRecipe gui, char keyChar, int keyCode, int recipe)
{
Point point = GuiDraw.getMousePosition();
int xAxis = point.x-(Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiLeft);
int yAxis = point.y-(Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiTop);
FluidStack stack = null;
if(xAxis >= 7 && xAxis <= 23 && yAxis >= 14+4 && yAxis <= 72+4)
{
stack = ((CachedIORecipe)arecipes.get(recipe)).fluidInput;
}
else if(xAxis >= 153 && xAxis <= 169 && yAxis >= 14+4 && yAxis <= 72+4)
{
stack = ((CachedIORecipe)arecipes.get(recipe)).fluidOutput;
}
if(stack != null)
{
if(keyCode == NEIClientConfig.getKeyBinding("gui.recipe"))
{
if(doFluidLookup(stack, false))
{
return true;
}
}
else if(keyCode == NEIClientConfig.getKeyBinding("gui.usage"))
{
if(doFluidLookup(stack, true))
{
return true;
}
}
}
return super.keyTyped(gui, keyChar, keyCode, recipe);
}
@Override
public boolean mouseClicked(GuiRecipe gui, int button, int recipe)
{
Point point = GuiDraw.getMousePosition();
int xAxis = point.x - (Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiLeft);
int yAxis = point.y - (Integer)MekanismUtils.getPrivateValue(gui, GuiContainer.class, ObfuscatedNames.GuiContainer_guiTop);
FluidStack stack = null;
if(xAxis >= 7 && xAxis <= 23 && yAxis >= 14+4 && yAxis <= 72+4)
{
stack = ((CachedIORecipe)arecipes.get(recipe)).fluidInput;
}
else if(xAxis >= 153 && xAxis <= 169 && yAxis >= 14+4 && yAxis <= 72+4)
{
stack = ((CachedIORecipe)arecipes.get(recipe)).fluidOutput;
}
if(stack != null)
{
if(button == 0)
{
if(doFluidLookup(stack, false))
{
return true;
}
}
else if(button == 1)
{
if(doFluidLookup(stack, true))
{
return true;
}
}
}
return super.mouseClicked(gui, button, recipe);
}
@Override
public int recipiesPerPage()
{
return 1;
}
@Override
public void addGuiElements()
{
}
public class CachedIORecipe extends TemplateRecipeHandler.CachedRecipe
{
public FluidStack fluidInput;
public FluidStack fluidOutput;
@Override
public PositionedStack getResult()
{
return null;
}
public CachedIORecipe(FluidStack input, FluidStack output)
{
fluidInput = input;
fluidOutput = output;
}
public CachedIORecipe(SolarEvaporationRecipe recipe)
{
this((FluidStack)recipe.recipeInput.ingredient, (FluidStack)recipe.recipeOutput.output);
}
}
}
| |
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
/*
* Filename : PreparedStatementManager.java
*/
/*
* Method Changed : addPreparedStatement & getPreparedStatement
*/
package org.trafodion.jdbc.t2;
import java.sql.*;
import javax.sql.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Iterator;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
class PreparedStatementManager extends SQLMXHandle {
boolean isStatementCachingEnabled() {
if (JdbcDebugCfg.entryActive)
debug[methodId_isStatementCachingEnabled].methodEntry();
try {
if (maxStatements_ < 1)
return false;
else
return true;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_isStatementCachingEnabled].methodExit();
}
}
boolean makeRoom() throws SQLException {
if (JdbcDebugCfg.entryActive)
debug[methodId_makeRoom].methodEntry();
try {
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "makeRoom() - maxStatements = "
+ maxStatements_);
}
Iterator i;
SQLMXPreparedStatement pStmt;
CachedPreparedStatement cs;
long oldest = 0;
long stmtTime;
String key = null;
i = (prepStmtsInCache_.values()).iterator();
List<CachedPreparedStatement> listOfNotInUse = new ArrayList<CachedPreparedStatement>();
// Get the all cached statement that is not in use
for (; i.hasNext();) {
cs = (CachedPreparedStatement) i.next();
if (!cs.inUse_) {
oldest = cs.getLastUsedTime();
key = cs.getLookUpKey();
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "makeroom() "
+ "Found unused cached statement - " + "\""
+ key + "\"");
}
listOfNotInUse.add(cs);
}
}
// Try to remove the oldest/unused statement only if found one above
if (!listOfNotInUse.isEmpty()) {
Collections.sort(listOfNotInUse);
CachedPreparedStatement csForRemoval = listOfNotInUse.get(0);
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL)) {
out_.println(getTraceId() + "makeroom() "
+ "Found older unused cached statement - " + "\""
+ csForRemoval.getLookUpKey() + "\"");
}
prepStmtsInCache_.remove(csForRemoval.getLookUpKey());
((SQLMXPreparedStatement) csForRemoval.getPreparedStatement())
.close(true);
count_--;
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL)) {
out_.println(getTraceId() + "makeroom() "
+ "Removed cached stmt - " + "\""
+ csForRemoval.getLookUpKey() + "\"");
}
listOfNotInUse.clear();
return true;
}
return false;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_makeRoom].methodExit();
}
}
void closePreparedStatementsAll() throws SQLException {
if (JdbcDebugCfg.entryActive)
debug[methodId_closePreparedStatementsAll].methodEntry();
try {
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "closePreparedStatementsAll()");
}
Object[] csArray;
CachedPreparedStatement cs;
int i = 0;
csArray = (prepStmtsInCache_.values()).toArray();
for (i = 0; i < csArray.length; i++) {
cs = (CachedPreparedStatement) csArray[i];
if (cs != null){
cs.close(false);
}
}
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_closePreparedStatementsAll].methodExit();
}
}
/*
* Description : Identify and close the duplicate statement. Additional
* argument origPStmt introduced.
*/
// void closePreparedStatement(SQLMXConnection connect,
void closePreparedStatement(SQLMXPreparedStatement origPStmt,
SQLMXConnection connect, String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
if (JdbcDebugCfg.entryActive)
debug[methodId_closePreparedStatement].methodEntry();
try {
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "closePreparedStatement(" + connect
+ ",\"" + sql + "\"," + resultSetType + ","
+ resultSetConcurrency + "," + resultSetHoldability
+ ")");
}
SQLMXPreparedStatement pStmt = null;
CachedPreparedStatement cs = null;
;
String lookupKey;
Object csArray[];
// lookupKey = sql;
// if (connect.catalog_ != null)
// lookupKey = lookupKey.concat(connect.catalog_);
// if (connect.schema_ != null)
// lookupKey = lookupKey.concat(connect.schema_);
// lookupKey = lookupKey.concat(String.valueOf(connect.transactionIsolation_))
// .concat(String.valueOf(resultSetHoldability));
// if (connect.getMD5HashCode() != null)
// lookupKey = lookupKey.concat(connect.getMD5HashCode());
//
// lookupKey = sql;
// if (connect.catalog_ != null)
// lookupKey.concat(connect.catalog_);
// if (connect.schema_ != null)
// lookupKey.concat(connect.schema_);
// lookupKey.concat(String.valueOf(connect.transactionIsolation_))
// .concat(String.valueOf(resultSetHoldability));
// cs = (CachedPreparedStatement) prepStmtsInCache_.get(lookupKey);
csArray = (prepStmtsInCache_.values()).toArray();
boolean foundFlag = false;
for(int i=0;i<csArray.length;i++){
cs = (CachedPreparedStatement)csArray[i];
if(cs != null){
pStmt = (SQLMXPreparedStatement) cs.getPreparedStatement();
if (pStmt == origPStmt){
cs.inUse_ = false;
cs.setLastUsedInfo();
foundFlag=true;
break;
// origPStmt.close(true);
}
}
}
if(!foundFlag){
origPStmt.close(true);
if (out_ != null) {
if (traceFlag_ >= 1)
out_.println(getTraceId() + "closePreparedStatement()["
+origPStmt.getStmtLabel()+ "]: Hard closed duplicate statement - " + "\""
+ origPStmt + "\"");
}
}
/*
* Description : Identify and close the duplicate statement.
*/
// if (cs != null) {
// pStmt = (SQLMXPreparedStatement) cs.getPreparedStatement();
// if (pStmt != origPStmt)
// cs = null;
//
// }
//
// if (cs == null) {
// origPStmt.close(true);
// if (out_ != null) {
// if (traceFlag_ >= 1)
// out_.println(getTraceId() + "closePreparedStatement() "
// + "Hard closed duplicate statement - " + "\""
// + lookupKey + "\"");
// }
// }
// // If the number of cached statements exceeds maxStatements,
// // perform a hard close
// if (cs != null) {
// if (count_ > maxStatements_) {
// // Remove it from cache
// cs = (CachedPreparedStatement) prepStmtsInCache_
// .remove(lookupKey);
// pStmt = (SQLMXPreparedStatement) cs.getPreparedStatement();
// pStmt.close(true);
// count_--;
// if (out_ != null) {
// if ((traceFlag_ == T2Driver.POOLING_LVL)
// || (traceFlag_ == T2Driver.ENTRY_LVL))
// out_.println(getTraceId() + "closePreparedStatement() "
// + "Hard closed cached statement - " + "\""
// + lookupKey + "\"");
// }
// } else {
// cs.inUse_ = false;
// cs.setLastUsedInfo();
// if (out_ != null) {
// if ((traceFlag_ == T2Driver.POOLING_LVL)
// || (traceFlag_ == T2Driver.ENTRY_LVL))
// out_.println(getTraceId() + "closePreparedStatement() "
// + "Logical closed cached statement - "
// + "\"" + lookupKey + "\"");
// }
// }
// }
// return;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_closePreparedStatement].methodExit();
}
}
void clearPreparedStatementsAll() {
if (JdbcDebugCfg.entryActive)
debug[methodId_clearPreparedStatementsAll].methodEntry();
try {
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "clearPreparedStatementsAll()");
}
if (prepStmtsInCache_ != null)
prepStmtsInCache_.clear();
count_ = 0;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_clearPreparedStatementsAll].methodExit();
}
}
void addPreparedStatement(SQLMXConnection connect, String sql,
PreparedStatement pStmt, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
if (JdbcDebugCfg.entryActive)
debug[methodId_addPreparedStatement].methodEntry();
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "addPreparedStatement(" + connect
+ ",\"" + sql + "\"," + pStmt + "," + resultSetType
+ "," + resultSetConcurrency + ","
+ resultSetHoldability + ")");
}
try {
CachedPreparedStatement cachedStmt;
String lookupKey;
lookupKey = sql;
if (connect.catalog_ != null)
lookupKey = lookupKey.concat(connect.catalog_);
if (connect.schema_ != null)
lookupKey = lookupKey.concat(connect.schema_);
lookupKey = lookupKey.concat(String.valueOf(connect.transactionIsolation_))
.concat(String.valueOf(resultSetHoldability));
if (connect.getMD5HashCode() != null)
lookupKey = lookupKey.concat(connect.getMD5HashCode());
// lookupKey = sql;
// if (connect.catalog_ != null)
// lookupKey.concat(connect.catalog_);
// if (connect.schema_ != null)
// lookupKey.concat(connect.schema_);
// lookupKey.concat(String.valueOf(connect.transactionIsolation_))
// .concat(String.valueOf(resultSetHoldability));
boolean hasRoom = true;
if (count_ >= maxStatements_) {
hasRoom = makeRoom();
if (!hasRoom) {
// Cached statement count has reached maxStatements AND they
// are all in use
Object[] warnMsg = new Object[1];
warnMsg[0] = new Integer(maxStatements_);
// Set a warning indicating maxStatements have been exceeded
connect.setSQLWarning(connect.locale_,
"exceeded_maxStatements", warnMsg);
return;
}
}
if (count_ < maxStatements_ || hasRoom) {
if (!prepStmtsInCache_.containsKey(lookupKey)) {
cachedStmt = new CachedPreparedStatement(pStmt, lookupKey);
prepStmtsInCache_.put(lookupKey, cachedStmt);
count_++;
if (out_ != null
&& ((traceFlag_ == T2Driver.POOLING_LVL) || (traceFlag_ == T2Driver.ENTRY_LVL))) {
//R3.2 changes -- start
out_.println(getTraceId()
+ "addPreparedStatement() Added stmt to cache "
+ "\"" + cachedStmt.getPstmt_().stmtId_ + "\" ; "
+ "cached stmt cnt = " + count_);
//R3.2 changes -- end
}
}
}
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_addPreparedStatement].methodExit();
}
}
PreparedStatement getPreparedStatement(SQLMXConnection connect, String sql,
int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
if (JdbcDebugCfg.entryActive)
debug[methodId_getPreparedStatement].methodEntry();
try {
if (out_ != null) {
if ((traceFlag_ == T2Driver.POOLING_LVL)
|| (traceFlag_ == T2Driver.ENTRY_LVL))
out_.println(getTraceId() + "getPreparedStatement(" + connect
+ ",\"" + sql + "\"," + resultSetType + ","
+ resultSetConcurrency + "," + resultSetHoldability
+ ")");
}
PreparedStatement pStmt = null;
CachedPreparedStatement cachedStmt;
String lookupKey;
lookupKey = sql;
if (connect.catalog_ != null)
lookupKey = lookupKey.concat(connect.catalog_);
if (connect.schema_ != null)
lookupKey = lookupKey.concat(connect.schema_);
lookupKey = lookupKey.concat(String.valueOf(connect.transactionIsolation_))
.concat(String.valueOf(resultSetHoldability));
if (connect.getMD5HashCode() != null)
lookupKey = lookupKey.concat(connect.getMD5HashCode());
// lookupKey = sql;
// if (connect.catalog_ != null)
// lookupKey.concat(connect.catalog_);
// if (connect.schema_ != null)
// lookupKey.concat(connect.schema_);
// lookupKey.concat(String.valueOf(connect.transactionIsolation_))
// .concat(String.valueOf(resultSetHoldability));
if (prepStmtsInCache_ != null) {
cachedStmt = (CachedPreparedStatement) prepStmtsInCache_
.get(lookupKey);
if (cachedStmt != null) {
if (!cachedStmt.inUse_) {
pStmt = cachedStmt.getPreparedStatement();
((org.trafodion.jdbc.t2.SQLMXPreparedStatement) pStmt)
.reuse(connect, resultSetType,
resultSetConcurrency,
resultSetHoldability);
cachedStmt.inUse_ = true;
cachedStmt.setLastUsedInfo();
} else
pStmt = null;
}
}
return pStmt;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_getPreparedStatement].methodExit();
}
}
void setLogInfo(int traceFlag, PrintWriter out) {
if (JdbcDebugCfg.entryActive)
debug[methodId_setLogInfo].methodEntry();
try {
traceFlag_ = traceFlag;
out_ = out;
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_setLogInfo].methodExit();
}
}
PreparedStatementManager() {
super();
if (JdbcDebugCfg.entryActive)
debug[methodId_PreparedStatementManager_V].methodEntry();
try {
String className = getClass().getName();
// Build up template portion of jdbcTrace output. Pre-appended to
// jdbcTrace entries.
// jdbcTrace:[XXXX]:[Thread[X,X,X]]:[XXXXXXXX]:ClassName.
setTraceId(T2Driver.traceText
+ T2Driver.dateFormat.format(new Date())
+ "]:["
+ Thread.currentThread()
+ "]:["
+ hashCode()
+ "]:"
+ className.substring(T2Driver.REMOVE_PKG_NAME,
className.length()) + ".");
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_PreparedStatementManager_V].methodExit();
}
}
PreparedStatementManager(T2Properties info) {
super();
if (JdbcDebugCfg.entryActive)
debug[methodId_PreparedStatementManager_L].methodEntry();
try {
// String tmp;
if (info != null) {
// tmp = info.getProperty("maxStatements");
maxStatements_ = info.getMaxStatements();
// if (tmp != null)
// maxStatements_ = Integer.parseInt(tmp);
if (maxStatements_ < 1)
maxStatements_ = 0;
}
if (maxStatements_ > 0) {
prepStmtsInCache_ = new HashMap<String, CachedPreparedStatement>();
}
// Build up template portion of jdbcTrace output. Pre-appended to
// jdbcTrace entries.
// jdbcTrace:[XXXX]:[Thread[X,X,X]]:[XXXXXXXX]:ClassName.
} finally {
if (JdbcDebugCfg.entryActive)
debug[methodId_PreparedStatementManager_L].methodExit();
}
}
public void setTraceId(String traceId_) {
this.traceId_ = traceId_;
}
public String getTraceId() {
String className = getClass().getName();
setTraceId(T2Driver.traceText
+ T2Driver.dateFormat.format(new Date())
+ "]:["
+ Thread.currentThread()
+ "]:["
+ this.toString()
+ "]:"
+ className.substring(T2Driver.REMOVE_PKG_NAME,
className.length()) + ".");
return traceId_;
}
protected HashMap<String, CachedPreparedStatement> prepStmtsInCache_;
private int maxStatements_;
private int count_;
int traceFlag_;
PrintWriter out_;
private String traceId_;
private static int methodId_isStatementCachingEnabled = 0;
private static int methodId_makeRoom = 1;
private static int methodId_closePreparedStatementsAll = 2;
private static int methodId_closePreparedStatement = 3;
private static int methodId_clearPreparedStatementsAll = 4;
private static int methodId_addPreparedStatement = 5;
private static int methodId_getPreparedStatement = 6;
private static int methodId_setLogInfo = 7;
private static int methodId_PreparedStatementManager_V = 8;
private static int methodId_PreparedStatementManager_L = 9;
private static int totalMethodIds = 10;
private static JdbcDebug[] debug;
static {
String className = "PreparedStatementManager";
if (JdbcDebugCfg.entryActive) {
debug = new JdbcDebug[totalMethodIds];
debug[methodId_isStatementCachingEnabled] = new JdbcDebug(
className, "isStatementCachingEnabled");
debug[methodId_makeRoom] = new JdbcDebug(className, "makeRoom");
debug[methodId_closePreparedStatementsAll] = new JdbcDebug(
className, "closePreparedStatementsAll");
debug[methodId_closePreparedStatement] = new JdbcDebug(className,
"closePreparedStatement");
debug[methodId_clearPreparedStatementsAll] = new JdbcDebug(
className, "clearPreparedStatementsAll");
debug[methodId_addPreparedStatement] = new JdbcDebug(className,
"addPreparedStatement");
debug[methodId_getPreparedStatement] = new JdbcDebug(className,
"getPreparedStatement");
debug[methodId_setLogInfo] = new JdbcDebug(className, "setLogInfo");
debug[methodId_PreparedStatementManager_V] = new JdbcDebug(
className, "PreparedStatementManager_V");
debug[methodId_PreparedStatementManager_L] = new JdbcDebug(
className, "PreparedStatementManager_L");
}
}
}
| |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFMeterFeaturesStatsRequestVer15 implements OFMeterFeaturesStatsRequest {
private static final Logger logger = LoggerFactory.getLogger(OFMeterFeaturesStatsRequestVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 16;
private final static long DEFAULT_XID = 0x0L;
private final static Set<OFStatsRequestFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsRequestFlags>of();
// OF message fields
private final long xid;
private final Set<OFStatsRequestFlags> flags;
//
// Immutable default instance
final static OFMeterFeaturesStatsRequestVer15 DEFAULT = new OFMeterFeaturesStatsRequestVer15(
DEFAULT_XID, DEFAULT_FLAGS
);
// package private constructor - used by readers, builders, and factory
OFMeterFeaturesStatsRequestVer15(long xid, Set<OFStatsRequestFlags> flags) {
if(flags == null) {
throw new NullPointerException("OFMeterFeaturesStatsRequestVer15: property flags cannot be null");
}
this.xid = xid;
this.flags = flags;
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
public OFMeterFeaturesStatsRequest.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFMeterFeaturesStatsRequest.Builder {
final OFMeterFeaturesStatsRequestVer15 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
BuilderWithParent(OFMeterFeaturesStatsRequestVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFMeterFeaturesStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFMeterFeaturesStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public OFMeterFeaturesStatsRequest build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : parentMessage.flags;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
//
return new OFMeterFeaturesStatsRequestVer15(
xid,
flags
);
}
}
static class Builder implements OFMeterFeaturesStatsRequest.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFMeterFeaturesStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.METER_FEATURES;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFMeterFeaturesStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
//
@Override
public OFMeterFeaturesStatsRequest build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
return new OFMeterFeaturesStatsRequestVer15(
xid,
flags
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFMeterFeaturesStatsRequest> {
@Override
public OFMeterFeaturesStatsRequest readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 6
byte version = bb.readByte();
if(version != (byte) 0x6)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version);
// fixed value property type == 18
byte type = bb.readByte();
if(type != (byte) 0x12)
throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got="+type);
int length = U16.f(bb.readShort());
if(length != 16)
throw new OFParseError("Wrong length: Expected=16(16), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property statsType == 11
short statsType = bb.readShort();
if(statsType != (short) 0xb)
throw new OFParseError("Wrong statsType: Expected=OFStatsType.METER_FEATURES(11), got="+statsType);
Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer15.readFrom(bb);
// pad: 4 bytes
bb.skipBytes(4);
OFMeterFeaturesStatsRequestVer15 meterFeaturesStatsRequestVer15 = new OFMeterFeaturesStatsRequestVer15(
xid,
flags
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", meterFeaturesStatsRequestVer15);
return meterFeaturesStatsRequestVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFMeterFeaturesStatsRequestVer15Funnel FUNNEL = new OFMeterFeaturesStatsRequestVer15Funnel();
static class OFMeterFeaturesStatsRequestVer15Funnel implements Funnel<OFMeterFeaturesStatsRequestVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFMeterFeaturesStatsRequestVer15 message, PrimitiveSink sink) {
// fixed value property version = 6
sink.putByte((byte) 0x6);
// fixed value property type = 18
sink.putByte((byte) 0x12);
// fixed value property length = 16
sink.putShort((short) 0x10);
sink.putLong(message.xid);
// fixed value property statsType = 11
sink.putShort((short) 0xb);
OFStatsRequestFlagsSerializerVer15.putTo(message.flags, sink);
// skip pad (4 bytes)
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFMeterFeaturesStatsRequestVer15> {
@Override
public void write(ByteBuf bb, OFMeterFeaturesStatsRequestVer15 message) {
// fixed value property version = 6
bb.writeByte((byte) 0x6);
// fixed value property type = 18
bb.writeByte((byte) 0x12);
// fixed value property length = 16
bb.writeShort((short) 0x10);
bb.writeInt(U32.t(message.xid));
// fixed value property statsType = 11
bb.writeShort((short) 0xb);
OFStatsRequestFlagsSerializerVer15.writeTo(bb, message.flags);
// pad: 4 bytes
bb.writeZero(4);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFMeterFeaturesStatsRequestVer15(");
b.append("xid=").append(xid);
b.append(", ");
b.append("flags=").append(flags);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFMeterFeaturesStatsRequestVer15 other = (OFMeterFeaturesStatsRequestVer15) obj;
if( xid != other.xid)
return false;
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
return result;
}
}
| |
/*
* 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.reef.tang.util;
import org.apache.reef.tang.annotations.Name;
import org.apache.reef.tang.annotations.NamedParameter;
import org.apache.reef.tang.exceptions.ClassHierarchyException;
import javax.inject.Inject;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
public final class ReflectionUtilities {
/**
* This is used to split Java classnames. Currently, we split on . and on $
*/
public static final String regexp = "[\\.\\$]";
/**
* A map from numeric classes to the number of bits used by their representations.
*/
private static final Map<Class<?>, Integer> SIZEOF = new HashMap<>();
static {
SIZEOF.put(Byte.class, Byte.SIZE);
SIZEOF.put(Short.class, Short.SIZE);
SIZEOF.put(Integer.class, Integer.SIZE);
SIZEOF.put(Long.class, Long.SIZE);
SIZEOF.put(Float.class, Float.SIZE);
SIZEOF.put(Double.class, Double.SIZE);
}
/**
* Given a primitive type, return its boxed representation.
* <p/>
* Examples:
* boxClass(int.class) -> Integer.class
* boxClass(String.class) -> String.class
*
* @param c The class to be boxed.
* @return The boxed version of c, or c if it is not a primitive type.
*/
public static Class<?> boxClass(Class<?> c) {
if (c.isPrimitive() && c != Class.class) {
if (c == boolean.class) {
return Boolean.class;
} else if (c == byte.class) {
return Byte.class;
} else if (c == char.class) {
return Character.class;
} else if (c == short.class) {
return Short.class;
} else if (c == int.class) {
return Integer.class;
} else if (c == long.class) {
return Long.class;
} else if (c == float.class) {
return Float.class;
} else if (c == double.class) {
return Double.class;
} else if (c == void.class) {
return Void.class;
} else {
throw new UnsupportedOperationException(
"Encountered unknown primitive type!");
}
} else {
return c;
}
}
/**
* Given a Type, return all of the classes it extends and interfaces it implements (including the class itself).
* <p/>
* Examples:
* Integer.class -> {Integer.class, Number.class, Object.class}
* T -> Object
* ? -> Object
* HashSet<T> -> {HashSet<T>, Set<T>, Collection<T>, Object}
* FooEventHandler -> {FooEventHandler, EventHandler<Foo>, Object}
*/
public static Iterable<Type> classAndAncestors(Type c) {
List<Type> workQueue = new ArrayList<>();
workQueue.add(c);
if (getRawClass(c).isInterface()) {
workQueue.add(Object.class);
}
for (int i = 0; i < workQueue.size(); i++) {
c = workQueue.get(i);
if (c instanceof Class) {
Class<?> clz = (Class<?>) c;
final Type sc = clz.getSuperclass();
if (sc != null) {
workQueue.add(sc); //c.getSuperclass());
}
workQueue.addAll(Arrays.asList(clz.getGenericInterfaces()));
} else if (c instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) c;
Class<?> rawPt = (Class<?>) pt.getRawType();
final Type sc = rawPt.getSuperclass();
// workQueue.add(pt);
// workQueue.add(rawPt);
if (sc != null) {
workQueue.add(sc);
}
workQueue.addAll(Arrays.asList(rawPt.getGenericInterfaces()));
} else if (c instanceof WildcardType) {
workQueue.add(Object.class); // XXX not really correct, but close enough?
} else if (c instanceof TypeVariable) {
workQueue.add(Object.class); // XXX not really correct, but close enough?
} else {
throw new RuntimeException(c.getClass() + " " + c + " is of unknown type!");
}
}
return workQueue;
}
/**
* Check to see if one class can be coerced into another. A class is
* coercable to another if, once both are boxed, the target class is a
* superclass or implemented interface of the source class.
* <p/>
* If both classes are numeric types, then this method returns true iff
* the conversion will not result in a loss of precision.
* <p/>
* TODO: Float and double are currently coercible to int and long. This is a bug.
*/
public static boolean isCoercable(Class<?> to, Class<?> from) {
to = boxClass(to);
from = boxClass(from);
if (Number.class.isAssignableFrom(to)
&& Number.class.isAssignableFrom(from)) {
return SIZEOF.get(from) <= SIZEOF.get(to);
}
return to.isAssignableFrom(from);
}
/**
* Lookup the provided name using the provided classloader. This method
* includes special handling for primitive types, which can be looked up
* by short name (all other types need to be looked up by long name).
*
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String name, ClassLoader loader)
throws ClassNotFoundException {
if (name.startsWith("[")) {
throw new UnsupportedOperationException("No support for arrays, etc. Name was: " + name);
} else if (name.equals("boolean")) {
return boolean.class;
} else if (name.equals("byte")) {
return byte.class;
} else if (name.equals("char")) {
return char.class;
} else if (name.equals("short")) {
return short.class;
} else if (name.equals("int")) {
return int.class;
} else if (name.equals("long")) {
return long.class;
} else if (name.equals("float")) {
return float.class;
} else if (name.equals("double")) {
return double.class;
} else if (name.equals("void")) {
return void.class;
} else {
return loader.loadClass(name);
}
}
/**
* Get the simple name of the class. This varies from the one in Class, in
* that it returns "1" for Classes like java.lang.String$1 In contrast,
* String.class.getSimpleName() returns "", which is not unique if
* java.lang.String$2 exists, causing all sorts of strange bugs.
*
* @param name
* @return
*/
public static String getSimpleName(Type name) {
final Class<?> clazz = getRawClass(name);
final String[] nameArray = clazz.getName().split(regexp);
final String ret = nameArray[nameArray.length - 1];
if (ret.length() == 0) {
throw new IllegalArgumentException("Class " + name + " has zero-length simple name. Can't happen?!?");
}
return ret;
}
/**
* Return the full name of the raw type of the provided Type.
* <p/>
* Examples:
* <p/>
* java.lang.String.class -> "java.lang.String"
* Set<String> -> "java.util.Set" // such types can occur as constructor arguments, for example
*
* @param name
* @return
*/
public static String getFullName(Type name) {
return getRawClass(name).getName();
}
/**
* Return the full name of the provided field. This will be globally
* unique. Following Java semantics, the full name will have all the
* generic parameters stripped out of it.
* <p/>
* Example:
* <p/>
* Set<X> { int size; } -> java.util.Set.size
*/
public static String getFullName(Field f) {
return getFullName(f.getDeclaringClass()) + "." + f.getName();
}
/**
* This method takes a class called clazz that *directly* implements a generic interface or generic class, iface.
* Iface should take a single parameter, which this method will return.
* <p/>
* TODO This is only tested for interfaces, and the type parameters associated with method arguments.
* TODO Not sure what we should do in the face of deeply nested generics (eg: Set<Set<String>)
* TODO Recurse up the class hierarchy in case there are intermediate interfaces
*
* @param iface A generic interface; we're looking up it's first (and only) parameter.
* @param type A type that is more specific than clazz, or clazz if no such type is available.
* @return The class implemented by the interface, or null(?) if the instantiation was not generic.
* @throws IllegalArgumentException if clazz does not directly implement iface.
*/
public static Type getInterfaceTarget(final Class<?> iface, final Type type) throws IllegalArgumentException {
if (type instanceof ParameterizedType) {
final ParameterizedType pt = (ParameterizedType) type;
if (iface.isAssignableFrom((Class<?>) pt.getRawType())) {
Type t = pt.getActualTypeArguments()[0];
return t;
} else {
throw new IllegalArgumentException("Parameterized type " + type + " does not extend " + iface);
}
} else if (type instanceof Class) {
final Class<?> clazz = (Class<?>) type;
if (!clazz.equals(type)) {
throw new IllegalArgumentException();
}
ArrayList<Type> al = new ArrayList<>();
al.addAll(Arrays.asList(clazz.getGenericInterfaces()));
Type sc = clazz.getGenericSuperclass();
if (sc != null) {
al.add(sc);
}
final Type[] interfaces = al.toArray(new Type[0]);
for (Type genericNameType : interfaces) {
if (genericNameType instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) genericNameType;
if (ptype.getRawType().equals(iface)) {
Type t = ptype.getActualTypeArguments()[0];
return t;
}
}
}
throw new IllegalArgumentException(clazz + " does not directly implement " + iface);
} else {
throw new UnsupportedOperationException("Do not know how to get interface target of " + type);
}
}
/**
* @param clazz
* @return T if clazz implements Name<T>, null otherwise
* @throws org.apache.reef.tang.exceptions.BindException
* If clazz's definition incorrectly uses Name or @NamedParameter
*/
public static Type getNamedParameterTargetOrNull(Class<?> clazz)
throws ClassHierarchyException {
Annotation npAnnotation = clazz.getAnnotation(NamedParameter.class);
boolean hasSuperClass = (clazz.getSuperclass() != Object.class);
boolean isInjectable = false;
boolean hasConstructor = false;
// TODO Figure out how to properly differentiate between default and
// non-default zero-arg constructors?
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
if (constructors.length > 1) {
hasConstructor = true;
}
if (constructors.length == 1) {
Constructor<?> c = constructors[0];
Class<?>[] p = c.getParameterTypes();
if (p.length > 1) {
// Multiple args. Definitely not implicit.
hasConstructor = true;
} else if (p.length == 1) {
// One arg. Could be an inner class, in which case the compiler
// included an implicit one parameter constructor that takes the
// enclosing type.
if (p[0] != clazz.getEnclosingClass()) {
hasConstructor = true;
}
}
}
for (Constructor<?> c : constructors) {
for (Annotation a : c.getDeclaredAnnotations()) {
if (a instanceof Inject) {
isInjectable = true;
}
}
}
Class<?>[] allInterfaces = clazz.getInterfaces();
boolean hasMultipleInterfaces = (allInterfaces.length > 1);
boolean implementsName;
Type parameterClass = null;
try {
parameterClass = getInterfaceTarget(Name.class, clazz);
implementsName = true;
} catch (IllegalArgumentException e) {
implementsName = false;
}
if (npAnnotation == null) {
if (implementsName) {
throw new ClassHierarchyException("Named parameter " + getFullName(clazz)
+ " is missing its @NamedParameter annotation.");
} else {
return null;
}
} else {
if (!implementsName) {
throw new ClassHierarchyException("Found illegal @NamedParameter " + getFullName(clazz)
+ " does not implement Name<?>");
}
if (hasSuperClass) {
throw new ClassHierarchyException("Named parameter " + getFullName(clazz)
+ " has a superclass other than Object.");
}
if (hasConstructor || isInjectable) {
throw new ClassHierarchyException("Named parameter " + getFullName(clazz) + " has "
+ (isInjectable ? "an injectable" : "a") + " constructor. "
+ " Named parameters must not declare any constructors.");
}
if (hasMultipleInterfaces) {
throw new ClassHierarchyException("Named parameter " + getFullName(clazz) + " implements "
+ "multiple interfaces. It is only allowed to implement Name<T>");
}
if (parameterClass == null) {
throw new ClassHierarchyException(
"Missing type parameter in named parameter declaration. " + getFullName(clazz)
+ " implements raw type Name, but must implement"
+ " generic type Name<T>.");
}
return parameterClass;
}
}
/**
* Coerce a Type into a Class. This strips out any generic paramters, and
* resolves wildcards and free parameters to Object.
* <p/>
* Examples:
* java.util.Set<String> -> java.util.Set
* ? extends T -> Object
* T -> Object
* ? -> Object
*/
public static Class<?> getRawClass(Type clazz) {
if (clazz instanceof Class) {
return (Class<?>) clazz;
} else if (clazz instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) clazz).getRawType();
} else if (clazz instanceof WildcardType) {
return Object.class; // XXX not really correct, but close enough?
} else if (clazz instanceof TypeVariable) {
return Object.class; // XXX not really correct, but close enough?
} else {
System.err.println("Can't getRawClass for " + clazz + " of unknown type " + clazz.getClass());
throw new IllegalArgumentException("Can't getRawClass for " + clazz + " of unknown type " + clazz.getClass());
}
}
/**
* Empty private constructor to prohibit instantiation of utility class.
*/
private ReflectionUtilities() {
}
}
| |
// 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.refactoring.makeStatic;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.TestFrameworks;
import com.intellij.java.JavaBundle;
import com.intellij.model.BranchableUsageInfo;
import com.intellij.model.ModelBranch;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.changeSignature.JavaChangeInfoImpl;
import com.intellij.refactoring.changeSignature.JavaChangeSignatureUsageProcessor;
import com.intellij.refactoring.changeSignature.ParameterInfoImpl;
import com.intellij.refactoring.changeSignature.ThrownExceptionInfo;
import com.intellij.refactoring.changeSignature.inCallers.JavaCallerChooser;
import com.intellij.refactoring.util.CanonicalTypes;
import com.intellij.refactoring.util.LambdaRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.javadoc.MethodJavaDocHelper;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author dsl
*/
public class MakeMethodStaticProcessor extends MakeMethodOrClassStaticProcessor<PsiMethod> {
private static final Logger LOG = Logger.getInstance(MakeMethodStaticProcessor.class);
private @Nullable List<PsiMethod> myAdditionalMethods;
public MakeMethodStaticProcessor(final Project project, final PsiMethod method, final Settings settings) {
super(project, method, settings);
}
@Override
protected boolean findAdditionalMembers(final Set<UsageInfo> toMakeStatic) {
if (!toMakeStatic.isEmpty()) {
myAdditionalMethods = new ArrayList<>();
if (ApplicationManager.getApplication().isUnitTestMode()) {
for (UsageInfo usageInfo : toMakeStatic) {
myAdditionalMethods.add((PsiMethod)usageInfo.getElement());
}
}
else {
final JavaCallerChooser chooser = new MakeStaticJavaCallerChooser(myMember, myProject,
methods -> myAdditionalMethods.addAll(methods)) {
@Override
protected ArrayList<UsageInfo> getTopLevelItems() {
return new ArrayList<>(toMakeStatic);
}
};
TreeUtil.expand(chooser.getTree(), 2);
if (!chooser.showAndGet()) {
return false;
}
}
}
return true;
}
@Override
protected MultiMap<PsiElement, String> getConflictDescriptions(UsageInfo[] usages) {
MultiMap<PsiElement, String> descriptions = super.getConflictDescriptions(usages);
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element instanceof PsiMethodReferenceExpression && needLambdaConversion((PsiMethodReferenceExpression)element)) {
descriptions.putValue(element, JavaBundle.message("refactoring.method.reference.to.lambda.conflict"));
}
}
return descriptions;
}
@Override
protected void changeSelfUsage(SelfUsageInfo usageInfo) throws IncorrectOperationException {
PsiElement element = usageInfo.getElement();
PsiElement parent = element.getParent();
if (element instanceof PsiMethodReferenceExpression) {
if (needLambdaConversion((PsiMethodReferenceExpression)element)) {
PsiMethodCallExpression methodCallExpression = getMethodCallExpression((PsiMethodReferenceExpression)element);
if (methodCallExpression == null) return;
parent = methodCallExpression;
}
else {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(parent.getProject());
PsiClass memberClass = myMember.getContainingClass();
LOG.assertTrue(memberClass != null);
PsiElement qualifier = ((PsiMethodReferenceExpression)element).getQualifier();
LOG.assertTrue(qualifier != null);
qualifier.replace(factory.createReferenceExpression(memberClass));
return;
}
}
LOG.assertTrue(parent instanceof PsiMethodCallExpression, parent);
PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parent;
final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression();
if (qualifier != null) qualifier.delete();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(methodCall.getProject());
PsiExpressionList args = methodCall.getArgumentList();
PsiElement addParameterAfter = null;
if(mySettings.isMakeClassParameter()) {
PsiElement arg = factory.createExpressionFromText(mySettings.getClassParameterName(), null);
addParameterAfter = args.addAfter(arg, null);
}
if(mySettings.isMakeFieldParameters()) {
List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList();
for (Settings.FieldParameter fieldParameter : parameters) {
PsiElement arg = factory.createExpressionFromText(fieldParameter.name, null);
if (addParameterAfter == null) {
addParameterAfter = args.addAfter(arg, null);
}
else {
addParameterAfter = args.addAfter(arg, addParameterAfter);
}
}
}
}
@Override
protected void changeSelf(PsiElementFactory factory, UsageInfo[] usages)
throws IncorrectOperationException {
final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(myMember);
PsiParameterList paramList = myMember.getParameterList();
PsiElement addParameterAfter = null;
PsiDocTag anchor = null;
final PsiClass containingClass = myMember.getContainingClass();
LOG.assertTrue(containingClass != null);
if (mySettings.isDelegate()) {
List<ParameterInfoImpl> params = new ArrayList<>();
PsiParameter[] parameters = myMember.getParameterList().getParameters();
if (mySettings.isMakeClassParameter()) {
params.add(ParameterInfoImpl.createNew()
.withName(mySettings.getClassParameterName())
.withType(factory.createType(containingClass, PsiSubstitutor.EMPTY))
.withDefaultValue("this"));
}
if (mySettings.isMakeFieldParameters()) {
for (Settings.FieldParameter parameter : mySettings.getParameterOrderList()) {
params.add(ParameterInfoImpl.createNew()
.withName(mySettings.getClassParameterName())
.withType(parameter.type)
.withDefaultValue(parameter.field.getName()));
}
}
for (int i = 0; i < parameters.length; i++) {
params.add(ParameterInfoImpl.create(i));
}
final PsiType returnType = myMember.getReturnType();
LOG.assertTrue(returnType != null);
JavaChangeSignatureUsageProcessor.generateDelegate(new JavaChangeInfoImpl(VisibilityUtil.getVisibilityModifier(myMember.getModifierList()),
myMember,
myMember.getName(),
CanonicalTypes.createTypeWrapper(returnType),
params.toArray(new ParameterInfoImpl[0]),
new ThrownExceptionInfo[0],
false,
Collections.emptySet(),
Collections.emptySet()));
}
if (mySettings.isMakeClassParameter()) {
// Add parameter for object
PsiType parameterType = factory.createType(containingClass, PsiSubstitutor.EMPTY);
final String classParameterName = mySettings.getClassParameterName();
PsiParameter parameter = factory.createParameter(classParameterName, parameterType);
if(makeClassParameterFinal(usages)) {
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, true);
}
addParameterAfter = paramList.addAfter(parameter, null);
anchor = javaDocHelper.addParameterAfter(classParameterName, null);
}
if (mySettings.isMakeFieldParameters()) {
List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList();
for (Settings.FieldParameter fieldParameter : parameters) {
final PsiType fieldParameterType = fieldParameter.field.getType();
final PsiParameter parameter = factory.createParameter(fieldParameter.name, fieldParameterType);
if (makeFieldParameterFinal(fieldParameter.field, usages)) {
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, true);
}
addParameterAfter = paramList.addAfter(parameter, addParameterAfter);
anchor = javaDocHelper.addParameterAfter(fieldParameter.name, anchor);
}
}
makeStatic(myMember);
if (myAdditionalMethods != null) {
for (PsiMethod method : myAdditionalMethods) {
makeStatic(method);
}
}
}
private void makeStatic(PsiMethod member) {
final PsiAnnotation overrideAnnotation = AnnotationUtil.findAnnotation(member, CommonClassNames.JAVA_LANG_OVERRIDE);
if (overrideAnnotation != null) {
overrideAnnotation.delete();
}
setupTypeParameterList(member);
// Add static modifier
final PsiModifierList modifierList = member.getModifierList();
modifierList.setModifierProperty(PsiModifier.STATIC, true);
modifierList.setModifierProperty(PsiModifier.FINAL, false);
modifierList.setModifierProperty(PsiModifier.DEFAULT, false);
PsiReceiverParameter receiverParameter = PsiTreeUtil.getChildOfType(member.getParameterList(), PsiReceiverParameter.class);
if (receiverParameter != null) {
receiverParameter.delete();
}
}
@Override
protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory)
throws IncorrectOperationException {
if (!mySettings.isChangeSignature()) return;
PsiElement element = usage.getElement();
if (element instanceof PsiReferenceExpression) {
PsiReferenceExpression newRef = null;
if (mySettings.isMakeFieldParameters()) {
PsiElement resolved = ((PsiReferenceExpression) element).resolve();
if (resolved instanceof PsiField) {
String name = mySettings.getNameForField((PsiField) resolved);
if (name != null) {
newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null);
}
}
}
if (newRef == null && mySettings.isMakeClassParameter()) {
newRef =
(PsiReferenceExpression) factory.createExpressionFromText(
mySettings.getClassParameterName() + "." + element.getText(), null);
}
if (newRef != null) {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
newRef = (PsiReferenceExpression) codeStyleManager.reformat(newRef);
element.replace(newRef);
}
}
else if (element instanceof PsiThisExpression && mySettings.isMakeClassParameter()) {
element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
}
else if (element instanceof PsiSuperExpression && mySettings.isMakeClassParameter()) {
element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
}
else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter()) {
final PsiNewExpression newExpression = ((PsiNewExpression)element);
LOG.assertTrue(newExpression.getQualifier() == null);
final String newText = mySettings.getClassParameterName() + "." + newExpression.getText();
final PsiExpression expr = factory.createExpressionFromText(newText, null);
element.replace(expr);
}
}
@Override
protected void changeExternalUsage(UsageInfo usage, PsiElementFactory factory)
throws IncorrectOperationException {
final PsiElement element = usage.getElement();
if (!(element instanceof PsiReferenceExpression)) return;
PsiReferenceExpression methodRef = (PsiReferenceExpression) element;
if (methodRef instanceof PsiMethodReferenceExpression && needLambdaConversion((PsiMethodReferenceExpression)methodRef)) {
PsiMethodCallExpression expression = getMethodCallExpression((PsiMethodReferenceExpression)methodRef);
if (expression == null) return;
methodRef = expression.getMethodExpression();
}
PsiElement parent = methodRef.getParent();
PsiExpression instanceRef;
instanceRef = methodRef.getQualifierExpression();
PsiElement newQualifier;
final PsiClass memberClass = myMember.getContainingClass();
if (instanceRef == null || instanceRef instanceof PsiSuperExpression) {
PsiClass contextClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (!InheritanceUtil.isInheritorOrSelf(contextClass, memberClass, true)) {
instanceRef = factory.createExpressionFromText(memberClass.getQualifiedName() + ".this", null);
} else {
instanceRef = factory.createExpressionFromText("this", null);
}
newQualifier = null;
}
else {
newQualifier = factory.createReferenceExpression(memberClass);
}
if (mySettings.getNewParametersNumber() > 1) {
int copyingSafetyLevel = RefactoringUtil.verifySafeCopyExpression(instanceRef);
if (copyingSafetyLevel == RefactoringUtil.EXPR_COPY_PROHIBITED) {
String tempVar = RefactoringUtil.createTempVar(instanceRef, parent, true);
instanceRef = factory.createExpressionFromText(tempVar, null);
}
}
PsiElement anchor = null;
PsiExpressionList argList = null;
PsiExpression[] exprs = PsiExpression.EMPTY_ARRAY;
if (parent instanceof PsiMethodCallExpression) {
argList = ((PsiMethodCallExpression)parent).getArgumentList();
exprs = argList.getExpressions();
if (mySettings.isMakeClassParameter()) {
if (exprs.length > 0) {
anchor = argList.addBefore(instanceRef, exprs[0]);
}
else {
anchor = argList.add(instanceRef);
}
}
}
if (mySettings.isMakeFieldParameters()) {
List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList();
for (Settings.FieldParameter fieldParameter : parameters) {
PsiReferenceExpression fieldRef;
if (newQualifier != null) {
fieldRef = (PsiReferenceExpression)factory.createExpressionFromText(
"a." + fieldParameter.field.getName(), null);
fieldRef.getQualifierExpression().replace(instanceRef);
}
else {
fieldRef = (PsiReferenceExpression)factory.createExpressionFromText(fieldParameter.field.getName(), null);
}
if (anchor != null) {
anchor = argList.addAfter(fieldRef, anchor);
}
else if (argList != null) {
if (exprs.length > 0) {
anchor = argList.addBefore(fieldRef, exprs[0]);
}
else {
anchor = argList.add(fieldRef);
}
}
}
}
if (newQualifier != null) {
methodRef.getQualifierExpression().replace(newQualifier);
}
}
private static PsiMethodCallExpression getMethodCallExpression(PsiMethodReferenceExpression methodRef) {
PsiLambdaExpression lambdaExpression =
LambdaRefactoringUtil.convertMethodReferenceToLambda(methodRef, true, true);
List<PsiExpression> returnExpressions = LambdaUtil.getReturnExpressions(lambdaExpression);
if (returnExpressions.size() != 1) return null;
PsiExpression expression = returnExpressions.get(0);
if (!(expression instanceof PsiMethodCallExpression)) return null;
return (PsiMethodCallExpression)expression;
}
private boolean needLambdaConversion(PsiMethodReferenceExpression methodRef) {
if (mySettings.isMakeFieldParameters()) {
return true;
}
if (PsiMethodReferenceUtil.isResolvedBySecondSearch(methodRef)) {
return myMember.getParameters().length != 0 || !mySettings.isMakeClassParameter();
}
return mySettings.isMakeClassParameter();
}
@Override
protected void findExternalUsages(final ArrayList<UsageInfo> result) {
if (mySettings.isDelegate()) return;
findExternalReferences(myMember, result);
}
@Override
protected void processExternalReference(PsiElement element, PsiMethod method, ArrayList<UsageInfo> result) {
if (!mySettings.isChangeSignature()) {
final PsiMethod containingMethod = MakeStaticJavaCallerChooser.isTheLastClassRef(element, method);
if (containingMethod != null && !TestFrameworks.getInstance().isTestMethod(containingMethod)) {
result.add(new ChainedCallUsageInfo(containingMethod));
}
}
}
@Override
protected void performRefactoringInBranch(UsageInfo @NotNull [] usages, ModelBranch branch) {
MakeMethodStaticProcessor processor = new MakeMethodStaticProcessor(
myProject, branch.obtainPsiCopy(myMember), mySettings.obtainBranchCopy(branch));
if (myAdditionalMethods != null) {
processor.myAdditionalMethods = ContainerUtil.map(myAdditionalMethods, branch::obtainPsiCopy);
}
UsageInfo[] convertedUsages = BranchableUsageInfo.convertUsages(usages, branch);
processor.performRefactoring(convertedUsages);
}
@Override
protected boolean canPerformRefactoringInBranch() {
return true;
}
}
| |
/*
* @(#)ReversiBoard.java 2005/11/02
*
* Part of the reversi common module that uses the strategy game framework.
* Copyright (c) Michael Patricios, lurgee.net.
*
*/
package net.lurgee.reversi;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.lurgee.sgf.AbstractBoard;
import net.lurgee.sgf.Move;
import net.lurgee.sgf.MoveList;
import net.lurgee.sgf.MoveRanker;
import net.lurgee.sgf.Player;
import net.lurgee.sgf.Position;
/**
* Reversi board. It is is a 8x8 square board; each square on the board may be empty, or may contain a black piece or a
* white piece. The class has been optimised for performance - a table of adjacent squares is kept to help quickly
* determine which squares represent valid moves for a particular colour.
* <p/>
* Squares on the board are identified by x and y co-ordinates, which are one-based (so each has the range 1 to 8).
* @author mpatric
*/
public class ReversiBoard extends AbstractBoard implements ReversiDifferenceBoard {
public static final int X_DIMENSION = 8;
public static final int Y_DIMENSION = 8;
private static final String MSG_PIECE_ALREADY_SET = "Piece already set";
private static final int INITIAL_MOVE_LIST_CAPACITY = 10;
/**
* A 1x8 array representing the state of the squares on the board. Each element in the array represents a row on
* the board, with each group of 2 bits in the element representing a square in that row, starting with the 2 least
* significant bits (first column). They are stored like this for performance reasons.
* <p/>
* The values are:
* <ul>
* <li>{@link Colour#NONE} - the square is empty;</li>
* <li>{@link Colour#BLACK} - the square contains a black piece;</li>
* <li>{@link Colour#WHITE} - the square contains a white piece;</li>
* <li>{@link Colour#ANY} - undefined.</li>
* </ul>
*/
protected final int squares[] = new int[Y_DIMENSION];
private final int counts[] = {0, 0};
private final int validCounts[] = {-1, -1};
/**
* A 2x8 array representing the empty squares that are adjacent to black or white pieces. <i>Adjacent</i> means
* in a square next to that piece, vertically, horizontally or diagonally). The first array is for black pieces and
* the second for white. Each element in the array represents a row on the board, with each group of 8 bits
* representing a square in that row, starting with the 8 least significant bits (first column). Each set of bits
* represents the <u>directions</u> that the square is in with respect to the adjacent black or white piece using
* the direction constants defined in {@link Direction}.
*/
private final long adjacents[][] = {new long[Y_DIMENSION], new long[Y_DIMENSION]};
private final int adjacentCounts[] = {-1, -1};
/**
* @deprecated ReversiBoard instances should be obtained from a GameContext.
*/
@Deprecated
public ReversiBoard() {
super();
}
public void initialise() {
clear();
setPiece(4, 5, Colour.BLACK);
setPiece(5, 4, Colour.BLACK);
setPiece(4, 4, Colour.WHITE);
setPiece(5, 5, Colour.WHITE);
setCurrentPlayer(ReversiPlayer.getInstance(Colour.BLACK));
}
@Override
protected void clear() {
super.clear();
for (int i = 0; i <= 7; i++) {
squares[i] = 0;
adjacents[0][i] = 0;
adjacents[1][i] = 0;
}
counts[0] = 0;
counts[1] = 0;
validCounts[0] = -1;
validCounts[1] = -1;
adjacentCounts[0] = -1;
adjacentCounts[1] = -1;
}
public int getSquares(int y) {
return squares[y - 1];
}
public int getSquare(int x, int y) {
if (x < 1 || x > X_DIMENSION) {
throw new IndexOutOfBoundsException();
}
return (squares[y - 1] >> (2 * (x - 1))) & 3;
}
public int getCount(int colour) {
if (colour < Colour.NONE || colour > Colour.ANY) {
throw new IllegalArgumentException();
}
if (colour == Colour.ANY) {
return (counts[Colour.BLACK - 1] + counts[Colour.WHITE - 1]);
} else if (colour == Colour.NONE) {
return (64 - counts[Colour.BLACK - 1] - counts[Colour.WHITE - 1]);
} else {
return counts[colour - 1];
}
}
/**
* Counts how many empty squares there are on the board adjacent to the specified colour. Internally, the count is
* stored if it has been calculated and the stored value is returned for subsequent calls. The stored value needs
* to be recalculated when the board state changes.
* @param colour {@link Colour#BLACK} or {@link Colour#WHITE}.
* @return The count.
*/
public int getAdjacentCount(int colour) {
// see if we've already calculated it
if (adjacentCounts[colour - 1] >= 0) return adjacentCounts[colour - 1];
// calculate it
int adjcount = 0;
for (int y = 0; y <= 7; y++) {
if (adjacents[colour - 1][y] != 0) {
for (int x = 0; x <= 7; x++) {
if (((adjacents[colour - 1][y] >> (8 * (x))) & 255) != 0) {
adjcount++;
}
}
}
}
adjacentCounts[colour - 1] = adjcount;
return adjcount;
}
/**
* Compare this board and another board and generate a delta of the two, which is a board containing only the
* squares that are empty on one of the boards and not empty on the other - all other squares are set to empty on
* the delta board.
* @param reversiBoard The board to compare to.
* @param differenceBoard Object for storing the difference board.
* @return A differential board, which can be used to examine the differences between this board and the supplied board.
*/
public ReversiDifferenceBoard compare(ReversiBoard reversiBoard, ReversiBoard differenceBoard) {
differenceBoard.counts[0] = 0;
differenceBoard.counts[1] = 0;
differenceBoard.setCurrentPlayer(getCurrentPlayer());
for (int y = 0; y <= 7; y++) {
differenceBoard.squares[y] = (squares[y] ^ reversiBoard.squares[y]) & squares[y];
if (differenceBoard.squares[y] != 0) {
for (int x = 0; x <= 7; x++) {
int colr = (differenceBoard.squares[y] >> (2 * x)) & 3;
if (colr != 0) {
differenceBoard.counts[colr - 1]++;
}
}
}
}
return differenceBoard;
}
protected void setPiece(int x, int y, int colour) {
if (((squares[y - 1] >> (2 * (x - 1))) & 3) != Colour.NONE) {
throw new IllegalStateException(MSG_PIECE_ALREADY_SET);
}
//squares[y - 1] &= ~(3 << (2 * (x - 1))); // unset the bits
squares[y - 1] |= (colour << (2 * (x - 1))); // set the bits for the specified colour
counts[colour - 1]++;
setAdjacents(x, y, colour);
}
private int flipPiece(int x, int y) {
int colour = ((squares[y - 1] >> (2 * (x - 1))) & 3);
if (colour < Colour.BLACK || colour > Colour.WHITE) {
return Colour.NONE;
}
counts[colour - 1]--;
colour = 3 - colour;
// set piece
squares[y - 1] &= ~(3 << (2 * (x - 1))); // unset the bits
squares[y - 1] |= (colour << (2 * (x - 1))); // set the bits for the specified colour
counts[colour - 1]++;
// set adjacents for other colour as this piece has flipped!
updateAdjacents(x, y, colour);
return colour;
}
/**
* Update {@link #adjacents} for a newly placed piece. The specified square (which is now not empty) is cleared in
* {@link #adjacents} and each empty square around this square is updated to reflect it is adjacent to this newly
* placed piece.
* @param x X-coordinate of the square (1-8).
* @param y Y-coordinate of the square (1-8).
* @param colour {@link Colour#BLACK} or {@link Colour#WHITE}.
*/
protected void setAdjacents(int x, int y, int colour) {
// set adjacents for a newly placed piece
adjacents[0][y - 1] &= ~((long) (255) << (8 * (x - 1))); // unset the bits for (x,y) for black
adjacents[1][y - 1] &= ~((long) (255) << (8 * (x - 1))); // unset the bits for (x,y) for white
// look at squares around (x,y) and set those that are empty
if (x > 1 && x < X_DIMENSION) {
if (((squares[y - 1] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y - 1] |= ((long) (Direction.LEFT) << (8 * (x)));
}
if (((squares[y - 1] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y - 1] |= ((long) Direction.RIGHT << (8 * (x - 2)));
}
}
if (y > 1 && y < Y_DIMENSION) {
if (((squares[y] >> (2 * (x - 1))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP << (8 * (x - 1)));
}
if (((squares[y - 2] >> (2 * (x - 1))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN << (8 * (x - 1)));
}
}
if (x > 1 && x < X_DIMENSION && y > 1 && y < X_DIMENSION) {
if (((squares[y] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP_LEFT << (8 * (x)));
}
if (((squares[y] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP_RIGHT << (8 * (x - 2)));
}
if (((squares[y - 2] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN_RIGHT << (8 * (x - 2)));
}
if (((squares[y - 2] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN_LEFT << (8 * (x)));
}
}
}
/**
* Update {@link #adjacents} for a flipped piece. Each empty square around this square is cleared as an adjacent
* to the old colour and set to an adjacent to the new colour.
* @param x X-coordinate of the square (1-8).
* @param y Y-coordinate of the square (1-8).
* @param colour The new colour of the square ({@link Colour#BLACK} or {@link Colour#WHITE}).
*/
protected void updateAdjacents(int x, int y, int colour) {
// unset bits around (x,y) for square with old colour
if (x > 1 && x < X_DIMENSION) {
adjacents[2 - colour][y - 1] &= ~((long) (Direction.LEFT) << (8 * (x)));
adjacents[2 - colour][y - 1] &= ~((long) Direction.RIGHT << (8 * (x - 2)));
}
if (y > 1 && y < Y_DIMENSION) {
adjacents[2 - colour][y] &= ~((long) Direction.UP << (8 * (x - 1)));
adjacents[2 - colour][y - 2] &= ~((long) Direction.DOWN << (8 * (x - 1)));
}
if (x > 1 && x < X_DIMENSION && y > 1 && y < Y_DIMENSION) {
adjacents[2 - colour][y] &= ~((long) Direction.UP_LEFT << (8 * (x)));
adjacents[2 - colour][y] &= ~((long) Direction.UP_RIGHT << (8 * (x - 2)));
adjacents[2 - colour][y - 2] &= ~((long) Direction.DOWN_RIGHT << (8 * (x - 2)));
adjacents[2 - colour][y - 2] &= ~((long) Direction.DOWN_LEFT << (8 * (x)));
}
// look at squares around (x,y) and set those that are empty
if (x > 1 && x < X_DIMENSION) {
if (((squares[y - 1] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y - 1] |= ((long) (Direction.LEFT) << (8 * (x)));
}
if (((squares[y - 1] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y - 1] |= ((long) Direction.RIGHT << (8 * (x - 2)));
}
}
if (y > 1 && y < Y_DIMENSION) {
if (((squares[y] >> (2 * (x - 1))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP << (8 * (x - 1)));
}
if (((squares[y - 2] >> (2 * (x - 1))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN << (8 * (x - 1)));
}
}
if (x > 1 && x < X_DIMENSION && y > 1 && y < X_DIMENSION) {
if (((squares[y] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP_LEFT << (8 * (x)));
}
if (((squares[y] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y] |= ((long) Direction.UP_RIGHT << (8 * (x - 2)));
}
if (((squares[y - 2] >> (2 * (x - 2))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN_RIGHT << (8 * (x - 2)));
}
if (((squares[y - 2] >> (2 * (x))) & 3) == 0) {
adjacents[colour - 1][y - 2] |= ((long) Direction.DOWN_LEFT << (8 * (x)));
}
}
}
private boolean isValidMove(int x, int y, int colour) {
if (x < 1 || x > X_DIMENSION || y < 1 || y > Y_DIMENSION) {
throw new IndexOutOfBoundsException();
}
if (colour != Colour.BLACK && colour != Colour.WHITE) {
throw new IndexOutOfBoundsException();
}
if (gameOver) {
return false;
}
long l = adjacents[2 - colour][y - 1] >> (8 * (x - 1));
if ((l & 255) == 0) {
return false; // not adjacent to opposite colour
}
if ((l & Direction.RIGHT) != 0 && traverseLine(x, y, colour, 1, 0, true, null) > 0) {
return true;
}
if ((l & Direction.DOWN) != 0 && traverseLine(x, y, colour, 0, 1, true, null) > 0) {
return true;
}
if ((l & Direction.LEFT) != 0 && traverseLine(x, y, colour, -1, 0, true, null) > 0) {
return true;
}
if ((l & Direction.UP) != 0 && traverseLine(x, y, colour, 0, -1, true, null) > 0) {
return true;
}
if ((l & Direction.DOWN_RIGHT) != 0 && traverseLine(x, y, colour, 1, 1, true, null) > 0) {
return true;
}
if ((l & Direction.DOWN_LEFT) != 0 && traverseLine(x, y, colour, -1, 1, true, null) > 0) {
return true;
}
if ((l & Direction.UP_LEFT) != 0 && traverseLine(x, y, colour, -1, -1, true, null) > 0) {
return true;
}
if ((l & Direction.UP_RIGHT) != 0 && traverseLine(x, y, colour, 1, -1, true, null) > 0) {
return true;
}
return false;
}
public boolean isValidMove(int x, int y) {
return isValidMove(x, y, ((ReversiPlayer) getCurrentPlayer()).getColour());
}
/**
* Traverse a line in the direction specified by dx and dy, flipping the pieces if fakeIt is false. If the flipped
* parameter is not null, {@link ReversiMove} objects representing the pieces that were flipped are added to it.
* @param x X-coordinate of starting square (1-8).
* @param y Y-coordinate of starting square (1-8).
* @param colour The colour of the piece being placed ({@link Colour#BLACK} or {@link Colour#WHITE}).
* @param dx Delta for x traversal (-1, 0 or 1).
* @param dy Delta for y traversal (-1, 0 or 1).
* @param fakeIt If true, the pieces are not actually flipped.
* @param flipped A container for adding the pieces that were flipped by this move. May be null.
* @return The number of pieces flipped (or that would be flipped).
*/
private int traverseLine(int x, int y, int colour, int dx, int dy, boolean fakeIt, List<Position> flipped) {
int colr = (squares[y - 1] >> (2 * (x - 1))) & 3;
if (colr != Colour.NONE) {
return 0;
}
int ox = x + dx;
int oy = y + dy;
int state = 0; // 0 = started, 1 = on opponent colour, 2 = on own colour
while (ox >= 1 && ox <= X_DIMENSION && oy >= 1 && oy <= Y_DIMENSION) {
colr = (squares[oy - 1] >> (2 * (ox - 1))) & 3;
if (colr == Colour.NONE) {
break;
} else if (colr != colour) {
if (state == 0) {
state = 1;
}
} else {
if (state == 1) {
state = 2;
}
break;
}
ox += dx;
oy += dy;
}
if (state != 2) {
return 0;
}
ox = x + dx;
oy = y + dy;
int flips = 0;
while (ox >= 1 && ox <= X_DIMENSION && oy >= 1 && oy <= Y_DIMENSION) {
colr = (squares[oy - 1] >> (2 * (ox - 1))) & 3;
if (colr != colour) {
flips++;
if (flipped != null) {
flipped.add(new ReversiPosition(ox, oy));
}
if (!fakeIt) {
flipPiece(ox, oy);
}
} else {
break;
}
ox += dx;
oy += dy;
}
return flips;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(" a b c d e f g h\n");
ReversiPlayer player = (ReversiPlayer) getCurrentPlayer();
for (int y = 1; y <= Y_DIMENSION; y++) {
buffer.append(y).append(" ");
for (int x = 1; x <= X_DIMENSION; x++) {
int squareColour = getSquare(x, y);
if (squareColour != Colour.NONE) {
buffer.append(ReversiPlayer.getInstance(squareColour).getSymbol());
} else if (player != null && isValidMove(x, y, player.getColour())) {
buffer.append('+');
} else {
buffer.append("-");
}
buffer.append(' ');
}
if (y < Y_DIMENSION) {
buffer.append("\n");
}
}
return buffer.toString();
}
public void fromString(String boardAsString) {
clear();
int x = 1;
int y = 1;
String[] lines = boardAsString.split("\n");
for (int i = 1; i < lines.length; i++) {
for (int j = 2; j < lines[i].length(); j += 2) {
String piece = lines[i].substring(j, j + 2);
if (ReversiPlayer.getInstance(Colour.BLACK).getSymbol() == piece.charAt(0)) {
setPiece(x, y, Colour.BLACK);
} else if (ReversiPlayer.getInstance(Colour.WHITE).getSymbol() == piece.charAt(0)) {
setPiece(x, y, Colour.WHITE);
}
x++;
if (x > X_DIMENSION) {
x = 1;
y++;
}
}
}
}
@Override
public void copy(AbstractBoard board) {
if (! (board instanceof ReversiBoard)) {
throw new IllegalArgumentException("Cannot copy " + board.getClass().getName() + " to " + getClass().getName());
}
super.copy(board);
ReversiBoard reversiBoard = (ReversiBoard) board;
for (int i = 0; i <= 7; i++) {
squares[i] = reversiBoard.squares[i];
adjacents[0][i] = reversiBoard.adjacents[0][i];
adjacents[1][i] = reversiBoard.adjacents[1][i];
}
counts[0] = reversiBoard.counts[0];
counts[1] = reversiBoard.counts[1];
validCounts[0] = reversiBoard.validCounts[0];
validCounts[1] = reversiBoard.validCounts[1];
adjacentCounts[0] = reversiBoard.adjacentCounts[0];
adjacentCounts[1] = reversiBoard.adjacentCounts[1];
}
public boolean canMove() {
int colour = ((ReversiPlayer) getCurrentPlayer()).getColour();
return canMove(colour);
}
private boolean canMove(int colour) {
if (gameOver) {
return false;
}
if (validCounts[colour - 1] == 0) {
return false;
}
for (int y = 0; y <= 7; y++) {
if (adjacents[2 - colour][y] != 0) {
for (int x = 0; x <= 7; x++) {
if (((adjacents[2 - colour][y] >> (8 * (x))) & 255) != 0) {
if (isValidMove(x + 1, y + 1, colour)) {
return true;
}
}
}
}
}
return false;
}
public int makeMove(Move move, List<Position> changes, boolean searching) {
int x = ((ReversiMove) move).getPosition().getX();
int y = ((ReversiMove) move).getPosition().getY();
int colour = ((ReversiPlayer) getCurrentPlayer()).getColour();
int flips = 0;
long l = adjacents[2 - colour][y - 1] >> (8 * (x - 1));
if ((l & Direction.RIGHT) != 0) {
flips += traverseLine(x, y, colour, 1, 0, false, changes);
}
if ((l & Direction.DOWN) != 0) {
flips += traverseLine(x, y, colour, 0, 1, false, changes);
}
if ((l & Direction.LEFT) != 0) {
flips += traverseLine(x, y, colour, -1, 0, false, changes);
}
if ((l & Direction.UP) != 0) {
flips += traverseLine(x, y, colour, 0, -1, false, changes);
}
if ((l & Direction.DOWN_RIGHT) != 0) {
flips += traverseLine(x, y, colour, 1, 1, false, changes);
}
if ((l & Direction.DOWN_LEFT) != 0) {
flips += traverseLine(x, y, colour, -1, 1, false, changes);
}
if ((l & Direction.UP_LEFT) != 0) {
flips += traverseLine(x, y, colour, -1, -1, false, changes);
}
if ((l & Direction.UP_RIGHT) != 0) {
flips += traverseLine(x, y, colour, 1, -1, false, changes);
}
if (flips == 0) {
return -1;
}
setPiece(x, y, colour);
validCounts[0] = -1; // validcounts for both colours is not valid any more
validCounts[1] = -1; // validcounts for both colours is not valid any more
adjacentCounts[0] = -1; // adjacentcounts for both colours is not valid any more
adjacentCounts[1] = -1; // adjacentcounts for both colours is not valid any more
if (!canMove(Colour.BLACK) && !canMove(Colour.WHITE)) {
gameOver = true;
}
return flips;
}
@Override
public List<Move> getValidMoves(MoveRanker moveRanker, int depth) {
int colour = ((ReversiPlayer) getCurrentPlayer()).getColour();
if (gameOver || validCounts[colour - 1] == 0) {
return Collections.emptyList();
} else {
MoveList moves = gameContext.createMoveList(INITIAL_MOVE_LIST_CAPACITY);
for (int y = 0; y <= 7; y++) {
if (adjacents[2 - colour][y] != 0) {
for (int x = 0; x <= 7; x++) {
if (((adjacents[2 - colour][y] >> (8 * (x))) & 255) != 0) {
if (isValidMove(x + 1, y + 1, colour)) {
//ReversiMove reversiMove = new ReversiMove(x + 1, y + 1);
ReversiMove reversiMove = ((ReversiMoveFactory) gameContext.getMoveFactory()).createMove(x + 1, y + 1);
moves.add(reversiMove, this, depth, moveRanker);
if (validCounts[colour - 1] >= 0 && moves.size() >= validCounts[colour - 1]) {
y = 7;
x = 7; // break out of both loops as there cannot be any further moves
}
}
}
}
}
}
validCounts[colour - 1] = moves.size();
return moves.getMoves();
}
}
public int countValidMoves() {
return countValidMoves(getCurrentPlayer());
}
public int countValidMoves(Player player) {
// see if we've already calculated it
int colour = ((ReversiPlayer) player).getColour();
if (validCounts[colour - 1] >= 0) return validCounts[colour - 1];
// calculate it
int movecount = 0;
for (int y = 0; y <= 7; y++) {
if (adjacents[2 - colour][y] != 0) {
for (int x = 0; x <= 7; x++) {
if (((adjacents[2 - colour][y] >> (8 * (x))) & 255) != 0) {
if (isValidMove(x + 1, y + 1, colour)) {
movecount++;
}
}
}
}
}
validCounts[colour - 1] = movecount;
return movecount;
}
public int countMaxMovesLeft() {
return getCount(Colour.NONE);
}
public int countMovesMade() {
return getCount(Colour.ANY) - 4;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
final ReversiBoard other = (ReversiBoard) obj;
if (!Arrays.equals(counts, other.counts)) return false;
if (!Arrays.equals(adjacentCounts, other.adjacentCounts)) return false;
if (!Arrays.equals(validCounts, other.validCounts)) return false;
if (!Arrays.equals(squares, other.squares)) return false;
if (!Arrays.equals(adjacents[0], other.adjacents[0])) return false;
if (!Arrays.equals(adjacents[1], other.adjacents[1])) return false;
return true;
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.eks;
import org.w3c.dom.*;
import java.net.*;
import java.util.*;
import javax.annotation.Generated;
import org.apache.commons.logging.*;
import com.amazonaws.*;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.internal.auth.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.protocol.json.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.annotation.ThreadSafe;
import com.amazonaws.client.AwsSyncClientParams;
import com.amazonaws.client.builder.AdvancedConfig;
import com.amazonaws.services.eks.AmazonEKSClientBuilder;
import com.amazonaws.services.eks.waiters.AmazonEKSWaiters;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.eks.model.*;
import com.amazonaws.services.eks.model.transform.*;
/**
* Client for accessing Amazon EKS. All service calls made using this client are blocking, and will not return until the
* service call completes.
* <p>
* <p>
* Amazon Elastic Kubernetes Service (Amazon EKS) is a managed service that makes it easy for you to run Kubernetes on
* AWS without needing to stand up or maintain your own Kubernetes control plane. Kubernetes is an open-source system
* for automating the deployment, scaling, and management of containerized applications.
* </p>
* <p>
* Amazon EKS runs up-to-date versions of the open-source Kubernetes software, so you can use all the existing plugins
* and tooling from the Kubernetes community. Applications running on Amazon EKS are fully compatible with applications
* running on any standard Kubernetes environment, whether running in on-premises data centers or public clouds. This
* means that you can easily migrate any standard Kubernetes application to Amazon EKS without any code modification
* required.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AmazonEKSClient extends AmazonWebServiceClient implements AmazonEKS {
/** Provider for AWS credentials. */
private final AWSCredentialsProvider awsCredentialsProvider;
private static final Log log = LogFactory.getLog(AmazonEKS.class);
/** Default signing name for the service. */
private static final String DEFAULT_SIGNING_NAME = "eks";
private volatile AmazonEKSWaiters waiters;
/** Client configuration factory providing ClientConfigurations tailored to this client */
protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory();
private final AdvancedConfig advancedConfig;
private static final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory = new com.amazonaws.protocol.json.SdkJsonProtocolFactory(
new JsonClientMetadata()
.withProtocolVersion("1.1")
.withSupportsCbor(false)
.withSupportsIon(false)
.withContentTypeOverride("")
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("UnsupportedAvailabilityZoneException").withModeledClass(
com.amazonaws.services.eks.model.UnsupportedAvailabilityZoneException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ServiceUnavailableException").withModeledClass(
com.amazonaws.services.eks.model.ServiceUnavailableException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidParameterException").withModeledClass(
com.amazonaws.services.eks.model.InvalidParameterException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceInUseException").withModeledClass(
com.amazonaws.services.eks.model.ResourceInUseException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidRequestException").withModeledClass(
com.amazonaws.services.eks.model.InvalidRequestException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceNotFoundException").withModeledClass(
com.amazonaws.services.eks.model.ResourceNotFoundException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ServerException").withModeledClass(
com.amazonaws.services.eks.model.ServerException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceLimitExceededException").withModeledClass(
com.amazonaws.services.eks.model.ResourceLimitExceededException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ClientException").withModeledClass(
com.amazonaws.services.eks.model.ClientException.class))
.withBaseServiceExceptionClass(com.amazonaws.services.eks.model.AmazonEKSException.class));
public static AmazonEKSClientBuilder builder() {
return AmazonEKSClientBuilder.standard();
}
/**
* Constructs a new client to invoke service methods on Amazon EKS using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AmazonEKSClient(AwsSyncClientParams clientParams) {
this(clientParams, false);
}
/**
* Constructs a new client to invoke service methods on Amazon EKS using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AmazonEKSClient(AwsSyncClientParams clientParams, boolean endpointDiscoveryEnabled) {
super(clientParams);
this.awsCredentialsProvider = clientParams.getCredentialsProvider();
this.advancedConfig = clientParams.getAdvancedConfig();
init();
}
private void init() {
setServiceNameIntern(DEFAULT_SIGNING_NAME);
setEndpointPrefix(ENDPOINT_PREFIX);
// calling this.setEndPoint(...) will also modify the signer accordingly
setEndpoint("eks.us-east-1.amazonaws.com");
HandlerChainFactory chainFactory = new HandlerChainFactory();
requestHandler2s.addAll(chainFactory.newRequestHandlerChain("/com/amazonaws/services/eks/request.handlers"));
requestHandler2s.addAll(chainFactory.newRequestHandler2Chain("/com/amazonaws/services/eks/request.handler2s"));
requestHandler2s.addAll(chainFactory.getGlobalHandlers());
}
/**
* <p>
* Creates an Amazon EKS control plane.
* </p>
* <p>
* The Amazon EKS control plane consists of control plane instances that run the Kubernetes software, such as
* <code>etcd</code> and the API server. The control plane runs in an account managed by AWS, and the Kubernetes API
* is exposed via the Amazon EKS API server endpoint. Each Amazon EKS cluster control plane is single-tenant and
* unique and runs on its own set of Amazon EC2 instances.
* </p>
* <p>
* The cluster control plane is provisioned across multiple Availability Zones and fronted by an Elastic Load
* Balancing Network Load Balancer. Amazon EKS also provisions elastic network interfaces in your VPC subnets to
* provide connectivity from the control plane instances to the worker nodes (for example, to support
* <code>kubectl exec</code>, <code>logs</code>, and <code>proxy</code> data flows).
* </p>
* <p>
* Amazon EKS worker nodes run in your AWS account and connect to your cluster's control plane via the Kubernetes
* API server endpoint and a certificate file that is created for your cluster.
* </p>
* <p>
* You can use the <code>endpointPublicAccess</code> and <code>endpointPrivateAccess</code> parameters to enable or
* disable public and private access to your cluster's Kubernetes API server endpoint. By default, public access is
* enabled, and private access is disabled. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html">Amazon EKS Cluster Endpoint Access
* Control</a> in the <i> <i>Amazon EKS User Guide</i> </i>.
* </p>
* <p>
* You can use the <code>logging</code> parameter to enable or disable exporting the Kubernetes control plane logs
* for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs.
* For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html">Amazon EKS Cluster Control Plane
* Logs</a> in the <i> <i>Amazon EKS User Guide</i> </i>.
* </p>
* <note>
* <p>
* CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For
* more information, see <a href="http://aws.amazon.com/cloudwatch/pricing/">Amazon CloudWatch Pricing</a>.
* </p>
* </note>
* <p>
* Cluster creation typically takes between 10 and 15 minutes. After you create an Amazon EKS cluster, you must
* configure your Kubernetes tooling to communicate with the API server and launch worker nodes into your cluster.
* For more information, see <a href="https://docs.aws.amazon.com/eks/latest/userguide/managing-auth.html">Managing
* Cluster Authentication</a> and <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html">Launching Amazon EKS Worker Nodes</a>
* in the <i>Amazon EKS User Guide</i>.
* </p>
*
* @param createClusterRequest
* @return Result of the CreateCluster operation returned by the service.
* @throws ResourceInUseException
* The specified resource is in use.
* @throws ResourceLimitExceededException
* You have encountered a service limit on the specified resource.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ServiceUnavailableException
* The service is unavailable. Back off and retry the operation.
* @throws UnsupportedAvailabilityZoneException
* At least one of your specified cluster subnets is in an Availability Zone that does not support Amazon
* EKS. The exception output specifies the supported Availability Zones for your account, from which you can
* choose subnets for your cluster.
* @sample AmazonEKS.CreateCluster
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/CreateCluster" target="_top">AWS API
* Documentation</a>
*/
@Override
public CreateClusterResult createCluster(CreateClusterRequest request) {
request = beforeClientExecution(request);
return executeCreateCluster(request);
}
@SdkInternalApi
final CreateClusterResult executeCreateCluster(CreateClusterRequest createClusterRequest) {
ExecutionContext executionContext = createExecutionContext(createClusterRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<CreateClusterRequest> request = null;
Response<CreateClusterResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new CreateClusterRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(createClusterRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CreateCluster");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<CreateClusterResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CreateClusterResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Deletes the Amazon EKS cluster control plane.
* </p>
* <note>
* <p>
* If you have active services in your cluster that are associated with a load balancer, you must delete those
* services before deleting the cluster so that the load balancers are deleted properly. Otherwise, you can have
* orphaned resources in your VPC that prevent you from being able to delete the VPC. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/delete-cluster.html">Deleting a Cluster</a> in the
* <i>Amazon EKS User Guide</i>.
* </p>
* </note>
*
* @param deleteClusterRequest
* @return Result of the DeleteCluster operation returned by the service.
* @throws ResourceInUseException
* The specified resource is in use.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ServiceUnavailableException
* The service is unavailable. Back off and retry the operation.
* @sample AmazonEKS.DeleteCluster
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/DeleteCluster" target="_top">AWS API
* Documentation</a>
*/
@Override
public DeleteClusterResult deleteCluster(DeleteClusterRequest request) {
request = beforeClientExecution(request);
return executeDeleteCluster(request);
}
@SdkInternalApi
final DeleteClusterResult executeDeleteCluster(DeleteClusterRequest deleteClusterRequest) {
ExecutionContext executionContext = createExecutionContext(deleteClusterRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteClusterRequest> request = null;
Response<DeleteClusterResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteClusterRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteClusterRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteCluster");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<DeleteClusterResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteClusterResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns descriptive information about an Amazon EKS cluster.
* </p>
* <p>
* The API server endpoint and certificate authority data returned by this operation are required for
* <code>kubelet</code> and <code>kubectl</code> to communicate with your Kubernetes API server. For more
* information, see <a href="https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html">Create a
* kubeconfig for Amazon EKS</a>.
* </p>
* <note>
* <p>
* The API server endpoint and certificate authority data aren't available until the cluster reaches the
* <code>ACTIVE</code> state.
* </p>
* </note>
*
* @param describeClusterRequest
* @return Result of the DescribeCluster operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ServiceUnavailableException
* The service is unavailable. Back off and retry the operation.
* @sample AmazonEKS.DescribeCluster
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/DescribeCluster" target="_top">AWS API
* Documentation</a>
*/
@Override
public DescribeClusterResult describeCluster(DescribeClusterRequest request) {
request = beforeClientExecution(request);
return executeDescribeCluster(request);
}
@SdkInternalApi
final DescribeClusterResult executeDescribeCluster(DescribeClusterRequest describeClusterRequest) {
ExecutionContext executionContext = createExecutionContext(describeClusterRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeClusterRequest> request = null;
Response<DescribeClusterResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeClusterRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(describeClusterRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DescribeCluster");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<DescribeClusterResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DescribeClusterResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns descriptive information about an update against your Amazon EKS cluster.
* </p>
* <p>
* When the status of the update is <code>Succeeded</code>, the update is complete. If an update fails, the status
* is <code>Failed</code>, and an error detail explains the reason for the failure.
* </p>
*
* @param describeUpdateRequest
* @return Result of the DescribeUpdate operation returned by the service.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @sample AmazonEKS.DescribeUpdate
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/DescribeUpdate" target="_top">AWS API
* Documentation</a>
*/
@Override
public DescribeUpdateResult describeUpdate(DescribeUpdateRequest request) {
request = beforeClientExecution(request);
return executeDescribeUpdate(request);
}
@SdkInternalApi
final DescribeUpdateResult executeDescribeUpdate(DescribeUpdateRequest describeUpdateRequest) {
ExecutionContext executionContext = createExecutionContext(describeUpdateRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeUpdateRequest> request = null;
Response<DescribeUpdateResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeUpdateRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(describeUpdateRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DescribeUpdate");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<DescribeUpdateResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DescribeUpdateResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Lists the Amazon EKS clusters in your AWS account in the specified Region.
* </p>
*
* @param listClustersRequest
* @return Result of the ListClusters operation returned by the service.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ServiceUnavailableException
* The service is unavailable. Back off and retry the operation.
* @sample AmazonEKS.ListClusters
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/ListClusters" target="_top">AWS API
* Documentation</a>
*/
@Override
public ListClustersResult listClusters(ListClustersRequest request) {
request = beforeClientExecution(request);
return executeListClusters(request);
}
@SdkInternalApi
final ListClustersResult executeListClusters(ListClustersRequest listClustersRequest) {
ExecutionContext executionContext = createExecutionContext(listClustersRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListClustersRequest> request = null;
Response<ListClustersResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListClustersRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listClustersRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListClusters");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<ListClustersResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListClustersResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Lists the updates associated with an Amazon EKS cluster in your AWS account, in the specified Region.
* </p>
*
* @param listUpdatesRequest
* @return Result of the ListUpdates operation returned by the service.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @sample AmazonEKS.ListUpdates
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/ListUpdates" target="_top">AWS API
* Documentation</a>
*/
@Override
public ListUpdatesResult listUpdates(ListUpdatesRequest request) {
request = beforeClientExecution(request);
return executeListUpdates(request);
}
@SdkInternalApi
final ListUpdatesResult executeListUpdates(ListUpdatesRequest listUpdatesRequest) {
ExecutionContext executionContext = createExecutionContext(listUpdatesRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListUpdatesRequest> request = null;
Response<ListUpdatesResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListUpdatesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listUpdatesRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListUpdates");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<ListUpdatesResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListUpdatesResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Updates an Amazon EKS cluster configuration. Your cluster continues to function during the update. The response
* output includes an update ID that you can use to track the status of your cluster update with the
* <a>DescribeUpdate</a> API operation.
* </p>
* <p>
* You can use this API operation to enable or disable exporting the Kubernetes control plane logs for your cluster
* to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more
* information, see <a href="https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html">Amazon EKS
* Cluster Control Plane Logs</a> in the <i> <i>Amazon EKS User Guide</i> </i>.
* </p>
* <note>
* <p>
* CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For
* more information, see <a href="http://aws.amazon.com/cloudwatch/pricing/">Amazon CloudWatch Pricing</a>.
* </p>
* </note>
* <p>
* You can also use this API operation to enable or disable public and private access to your cluster's Kubernetes
* API server endpoint. By default, public access is enabled, and private access is disabled. For more information,
* see <a href="https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html">Amazon EKS Cluster Endpoint
* Access Control</a> in the <i> <i>Amazon EKS User Guide</i> </i>.
* </p>
* <important>
* <p>
* At this time, you can not update the subnets or security group IDs for an existing cluster.
* </p>
* </important>
* <p>
* Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster
* status moves to <code>UPDATING</code> (this status transition is eventually consistent). When the update is
* complete (either <code>Failed</code> or <code>Successful</code>), the cluster status moves to <code>Active</code>
* .
* </p>
*
* @param updateClusterConfigRequest
* @return Result of the UpdateClusterConfig operation returned by the service.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ResourceInUseException
* The specified resource is in use.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @throws InvalidRequestException
* The request is invalid given the state of the cluster. Check the state of the cluster and the associated
* operations.
* @sample AmazonEKS.UpdateClusterConfig
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/UpdateClusterConfig" target="_top">AWS API
* Documentation</a>
*/
@Override
public UpdateClusterConfigResult updateClusterConfig(UpdateClusterConfigRequest request) {
request = beforeClientExecution(request);
return executeUpdateClusterConfig(request);
}
@SdkInternalApi
final UpdateClusterConfigResult executeUpdateClusterConfig(UpdateClusterConfigRequest updateClusterConfigRequest) {
ExecutionContext executionContext = createExecutionContext(updateClusterConfigRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UpdateClusterConfigRequest> request = null;
Response<UpdateClusterConfigResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UpdateClusterConfigRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateClusterConfigRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateClusterConfig");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<UpdateClusterConfigResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateClusterConfigResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Updates an Amazon EKS cluster to the specified Kubernetes version. Your cluster continues to function during the
* update. The response output includes an update ID that you can use to track the status of your cluster update
* with the <a>DescribeUpdate</a> API operation.
* </p>
* <p>
* Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster
* status moves to <code>UPDATING</code> (this status transition is eventually consistent). When the update is
* complete (either <code>Failed</code> or <code>Successful</code>), the cluster status moves to <code>Active</code>
* .
* </p>
*
* @param updateClusterVersionRequest
* @return Result of the UpdateClusterVersion operation returned by the service.
* @throws InvalidParameterException
* The specified parameter is invalid. Review the available parameters for the API request.
* @throws ClientException
* These errors are usually caused by a client action. Actions can include using an action or resource on
* behalf of a user that doesn't have permissions to use the action or resource or specifying an identifier
* that is not valid.
* @throws ServerException
* These errors are usually caused by a server-side issue.
* @throws ResourceInUseException
* The specified resource is in use.
* @throws ResourceNotFoundException
* The specified resource could not be found. You can view your available clusters with <a>ListClusters</a>.
* Amazon EKS clusters are Region-specific.
* @throws InvalidRequestException
* The request is invalid given the state of the cluster. Check the state of the cluster and the associated
* operations.
* @sample AmazonEKS.UpdateClusterVersion
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eks-2017-11-01/UpdateClusterVersion" target="_top">AWS API
* Documentation</a>
*/
@Override
public UpdateClusterVersionResult updateClusterVersion(UpdateClusterVersionRequest request) {
request = beforeClientExecution(request);
return executeUpdateClusterVersion(request);
}
@SdkInternalApi
final UpdateClusterVersionResult executeUpdateClusterVersion(UpdateClusterVersionRequest updateClusterVersionRequest) {
ExecutionContext executionContext = createExecutionContext(updateClusterVersionRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UpdateClusterVersionRequest> request = null;
Response<UpdateClusterVersionResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UpdateClusterVersionRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateClusterVersionRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EKS");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateClusterVersion");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<UpdateClusterVersionResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateClusterVersionResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* Returns additional metadata for a previously executed successful, request, typically used for debugging issues
* where a service isn't acting as expected. This data isn't considered part of the result data returned by an
* operation, so it's available through this separate, diagnostic interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic
* information for an executed request, you should use this method to retrieve it as soon as possible after
* executing the request.
*
* @param request
* The originally executed request
*
* @return The response metadata for the specified request, or null if none is available.
*/
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) {
return client.getResponseMetadataForRequest(request);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext) {
return invoke(request, responseHandler, executionContext, null, null);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI cachedEndpoint, URI uriFromEndpointTrait) {
executionContext.setCredentialsProvider(CredentialUtils.getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider));
return doInvoke(request, responseHandler, executionContext, cachedEndpoint, uriFromEndpointTrait);
}
/**
* Invoke with no authentication. Credentials are not required and any credentials set on the client or request will
* be ignored for this operation.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(Request<Y> request,
HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) {
return doInvoke(request, responseHandler, executionContext, null, null);
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been configured in the
* ExecutionContext beforehand.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI discoveredEndpoint, URI uriFromEndpointTrait) {
if (discoveredEndpoint != null) {
request.setEndpoint(discoveredEndpoint);
request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery");
} else if (uriFromEndpointTrait != null) {
request.setEndpoint(uriFromEndpointTrait);
} else {
request.setEndpoint(endpoint);
}
request.setTimeOffset(timeOffset);
HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata());
return client.execute(request, responseHandler, errorResponseHandler, executionContext);
}
@com.amazonaws.annotation.SdkInternalApi
static com.amazonaws.protocol.json.SdkJsonProtocolFactory getProtocolFactory() {
return protocolFactory;
}
@Override
public AmazonEKSWaiters waiters() {
if (waiters == null) {
synchronized (this) {
if (waiters == null) {
waiters = new AmazonEKSWaiters(this);
}
}
}
return waiters;
}
@Override
public void shutdown() {
super.shutdown();
if (waiters != null) {
waiters.shutdown();
}
}
}
| |
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.compiler.operator;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.asakusafw.compiler.operator.processor.UpdateOperatorProcessor;
/**
* Test for {@link OperatorClassCollector}.
*/
public class OperatorClassCollectorTest extends OperatorCompilerTestRoot {
/**
* simple case.
*/
@Test
public void simple() {
add("com.example.Simple");
start(new Collector(new MockOperatorProcessor()) {
@Override
protected void onCollected(List<OperatorClass> classes) {
assertThat(classes.size(), is(1));
OperatorClass aClass = classes.get(0);
assertThat(
aClass.getElement().getQualifiedName().toString(),
is("com.example.Simple"));
List<OperatorMethod> methods = aClass.getMethods();
assertThat(methods.size(), is(1));
OperatorMethod method = methods.get(0);
assertThat(
method.getElement().getSimpleName().toString(),
is("method"));
assertThat(
method.getProcessor().getTargetAnnotationType(),
is((Object) MockOperator.class));
}
});
}
/**
* w/ operator helper methods.
*/
@Test
public void withHelper() {
add("com.example.WithHelper");
start(new Collector(new MockOperatorProcessor()) {
@Override
protected void onCollected(List<OperatorClass> classes) {
assertThat(classes.size(), is(1));
}
});
}
/**
* Private methods can have a name as same as other operator methods.
*/
@Test
public void withPrivateOverload() {
add("com.example.PrivateOverload");
start(new Collector(new MockOperatorProcessor()) {
@Override
protected void onCollected(List<OperatorClass> classes) {
assertThat(classes.size(), is(1));
}
});
}
/**
* not a method.
*/
@Test
public void methodValidate_notMethod() {
add("com.example.NotMethod");
error(new Collector(new MockOperatorProcessor()));
}
/**
* not public method.
*/
@Test
public void methodValidate_notPublic() {
add("com.example.NotPublic");
error(new Collector(new MockOperatorProcessor()));
}
/**
* static method.
*/
@Test
public void methodValidate_Static() {
add("com.example.Static");
error(new Collector(new MockOperatorProcessor()));
}
/**
* conflict operator name.
*/
@Test
public void methodValidate_duplicateOperator() {
add("com.example.DuplicateOperator");
error(new Collector(new MockOperatorProcessor(), new UpdateOperatorProcessor()));
}
/**
* not a class.
*/
@Test
public void classValidate_notClass() {
add("com.example.NotClass");
error(new Collector(new MockOperatorProcessor()));
}
/**
* w/o simple constructor.
*/
@Test
public void classValidate_noSimpleConstructor() {
add("com.example.NoSimpleConstructor");
error(new Collector(new MockOperatorProcessor()));
}
/**
* not public class.
*/
@Test
public void classValidate_notPublic() {
add("com.example.NotPublicClass");
error(new Collector(new MockOperatorProcessor()));
}
/**
* not abstract class.
*/
@Test
public void classValidate_notAbstract() {
add("com.example.NotAbstractClass");
error(new Collector(new MockOperatorProcessor()));
}
/**
* generic class.
*/
@Test
public void classValidate_generic() {
add("com.example.GenericClass");
error(new Collector(new MockOperatorProcessor()));
}
/**
* not top-level class.
*/
@Test
public void classValidate_enclosing() {
add("com.example.Enclosing");
error(new Collector(new MockOperatorProcessor()));
}
/**
* public method w/o operator annotations.
*/
@Test
public void classValidate_notCovered() {
add("com.example.NotCovered");
error(new Collector(new MockOperatorProcessor()));
}
/**
* conflict method name.
*/
@Test
public void classValidate_methodConflicted() {
add("com.example.MethodConflicted");
error(new Collector(new MockOperatorProcessor(), new UpdateOperatorProcessor()));
}
/**
* conflict member name.
*/
@Test
public void classValidate_memberConflicted() {
add("com.example.MemberConflicted");
error(new Collector(new MockOperatorProcessor(), new UpdateOperatorProcessor()));
}
/**
* not public operator helper methods.
*/
@Test
public void classValidate_withHelper() {
add("com.example.NotPublicHelper");
error(new Collector(new MockOperatorProcessor(), new MockOperatorProcessor()));
}
private static class Collector extends Callback {
List<OperatorProcessor> processors;
Collector(OperatorProcessor...processors) {
this.processors = new ArrayList<>();
Collections.addAll(this.processors, processors);
}
@Override
protected final void test() {
if (round.getRootElements().isEmpty()) {
return;
}
try {
OperatorClassCollector collector = new OperatorClassCollector(env, round);
for (OperatorProcessor proc : processors) {
proc.initialize(env);
collector.add(proc);
}
List<OperatorClass> results = collector.collect();
onCollected(results);
} catch (OperatorCompilerException e) {
// ignore exception
}
}
/**
* invoked with the collected classes.
* @param classes the collected classes
*/
protected void onCollected(List<OperatorClass> classes) {
return;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.batchlog;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import com.google.common.collect.Lists;
import org.junit.*;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.Util.PartitionerSwitcher;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.RowUpdateBuilder;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.db.commitlog.CommitLogPosition;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.partitions.ImmutableBTreePartition;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.cassandra.cql3.QueryProcessor.executeInternal;
import static org.junit.Assert.*;
public class BatchlogManagerTest
{
private static final String KEYSPACE1 = "BatchlogManagerTest1";
private static final String CF_STANDARD1 = "Standard1";
private static final String CF_STANDARD2 = "Standard2";
private static final String CF_STANDARD3 = "Standard3";
private static final String CF_STANDARD4 = "Standard4";
private static final String CF_STANDARD5 = "Standard5";
static PartitionerSwitcher sw;
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
DatabaseDescriptor.daemonInitialization();
sw = Util.switchPartitioner(Murmur3Partitioner.instance);
SchemaLoader.prepareServer();
SchemaLoader.createKeyspace(KEYSPACE1,
KeyspaceParams.simple(1),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD1, 1, BytesType.instance),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD2, 1, BytesType.instance),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD3, 1, BytesType.instance),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD4, 1, BytesType.instance),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD5, 1, BytesType.instance));
}
@AfterClass
public static void cleanup()
{
sw.close();
}
@Before
@SuppressWarnings("deprecation")
public void setUp() throws Exception
{
TokenMetadata metadata = StorageService.instance.getTokenMetadata();
InetAddressAndPort localhost = InetAddressAndPort.getByName("127.0.0.1");
metadata.updateNormalToken(Util.token("A"), localhost);
metadata.updateHostId(UUIDGen.getTimeUUID(), localhost);
Keyspace.open(SchemaConstants.SYSTEM_KEYSPACE_NAME).getColumnFamilyStore(SystemKeyspace.BATCHES).truncateBlocking();
}
@Test
public void testDelete()
{
ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD1);
TableMetadata cfm = cfs.metadata();
new RowUpdateBuilder(cfm, FBUtilities.timestampMicros(), ByteBufferUtil.bytes("1234"))
.clustering("c")
.add("val", "val" + 1234)
.build()
.applyUnsafe();
DecoratedKey dk = cfs.decorateKey(ByteBufferUtil.bytes("1234"));
ImmutableBTreePartition results = Util.getOnlyPartitionUnfiltered(Util.cmd(cfs, dk).build());
Iterator<Row> iter = results.iterator();
assert iter.hasNext();
Mutation mutation = new Mutation(PartitionUpdate.fullPartitionDelete(cfm,
dk,
FBUtilities.timestampMicros(),
FBUtilities.nowInSeconds()));
mutation.applyUnsafe();
Util.assertEmpty(Util.cmd(cfs, dk).build());
}
@Test
@SuppressWarnings("deprecation")
public void testReplay() throws Exception
{
long initialAllBatches = BatchlogManager.instance.countAllBatches();
long initialReplayedBatches = BatchlogManager.instance.getTotalBatchesReplayed();
TableMetadata cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD1).metadata();
// Generate 1000 mutations (100 batches of 10 mutations each) and put them all into the batchlog.
// Half batches (50) ready to be replayed, half not.
for (int i = 0; i < 100; i++)
{
List<Mutation> mutations = new ArrayList<>(10);
for (int j = 0; j < 10; j++)
{
mutations.add(new RowUpdateBuilder(cfm, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(i))
.clustering("name" + j)
.add("val", "val" + j)
.build());
}
long timestamp = i < 50
? (System.currentTimeMillis() - BatchlogManager.getBatchlogTimeout())
: (System.currentTimeMillis() + BatchlogManager.getBatchlogTimeout());
BatchlogManager.store(Batch.createLocal(UUIDGen.getTimeUUID(timestamp, i), timestamp * 1000, mutations));
}
// Flush the batchlog to disk (see CASSANDRA-6822).
Keyspace.open(SchemaConstants.SYSTEM_KEYSPACE_NAME).getColumnFamilyStore(SystemKeyspace.BATCHES).forceBlockingFlush();
assertEquals(100, BatchlogManager.instance.countAllBatches() - initialAllBatches);
assertEquals(0, BatchlogManager.instance.getTotalBatchesReplayed() - initialReplayedBatches);
// Force batchlog replay and wait for it to complete.
BatchlogManager.instance.startBatchlogReplay().get();
// Ensure that the first half, and only the first half, got replayed.
assertEquals(50, BatchlogManager.instance.countAllBatches() - initialAllBatches);
assertEquals(50, BatchlogManager.instance.getTotalBatchesReplayed() - initialReplayedBatches);
for (int i = 0; i < 100; i++)
{
String query = String.format("SELECT * FROM \"%s\".\"%s\" WHERE key = intAsBlob(%d)", KEYSPACE1, CF_STANDARD1, i);
UntypedResultSet result = executeInternal(query);
assertNotNull(result);
if (i < 50)
{
Iterator<UntypedResultSet.Row> it = result.iterator();
assertNotNull(it);
for (int j = 0; j < 10; j++)
{
assertTrue(it.hasNext());
UntypedResultSet.Row row = it.next();
assertEquals(ByteBufferUtil.bytes(i), row.getBytes("key"));
assertEquals("name" + j, row.getString("name"));
assertEquals("val" + j, row.getString("val"));
}
assertFalse(it.hasNext());
}
else
{
assertTrue(result.isEmpty());
}
}
// Ensure that no stray mutations got somehow applied.
UntypedResultSet result = executeInternal(String.format("SELECT count(*) FROM \"%s\".\"%s\"", KEYSPACE1, CF_STANDARD1));
assertNotNull(result);
assertEquals(500, result.one().getLong("count"));
}
@Test
public void testTruncatedReplay() throws InterruptedException, ExecutionException
{
TableMetadata cf2 = Schema.instance.getTableMetadata(KEYSPACE1, CF_STANDARD2);
TableMetadata cf3 = Schema.instance.getTableMetadata(KEYSPACE1, CF_STANDARD3);
// Generate 2000 mutations (1000 batchlog entries) and put them all into the batchlog.
// Each batchlog entry with a mutation for Standard2 and Standard3.
// In the middle of the process, 'truncate' Standard2.
for (int i = 0; i < 1000; i++)
{
Mutation mutation1 = new RowUpdateBuilder(cf2, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(i))
.clustering("name" + i)
.add("val", "val" + i)
.build();
Mutation mutation2 = new RowUpdateBuilder(cf3, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(i))
.clustering("name" + i)
.add("val", "val" + i)
.build();
List<Mutation> mutations = Lists.newArrayList(mutation1, mutation2);
// Make sure it's ready to be replayed, so adjust the timestamp.
long timestamp = System.currentTimeMillis() - BatchlogManager.getBatchlogTimeout();
if (i == 500)
SystemKeyspace.saveTruncationRecord(Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD2),
timestamp,
CommitLogPosition.NONE);
// Adjust the timestamp (slightly) to make the test deterministic.
if (i >= 500)
timestamp++;
else
timestamp--;
BatchlogManager.store(Batch.createLocal(UUIDGen.getTimeUUID(timestamp, i), FBUtilities.timestampMicros(), mutations));
}
// Flush the batchlog to disk (see CASSANDRA-6822).
Keyspace.open(SchemaConstants.SYSTEM_KEYSPACE_NAME).getColumnFamilyStore(SystemKeyspace.BATCHES).forceBlockingFlush();
// Force batchlog replay and wait for it to complete.
BatchlogManager.instance.startBatchlogReplay().get();
// We should see half of Standard2-targeted mutations written after the replay and all of Standard3 mutations applied.
for (int i = 0; i < 1000; i++)
{
UntypedResultSet result = executeInternal(String.format("SELECT * FROM \"%s\".\"%s\" WHERE key = intAsBlob(%d)", KEYSPACE1, CF_STANDARD2,i));
assertNotNull(result);
if (i >= 500)
{
assertEquals(ByteBufferUtil.bytes(i), result.one().getBytes("key"));
assertEquals("name" + i, result.one().getString("name"));
assertEquals("val" + i, result.one().getString("val"));
}
else
{
assertTrue(result.isEmpty());
}
}
for (int i = 0; i < 1000; i++)
{
UntypedResultSet result = executeInternal(String.format("SELECT * FROM \"%s\".\"%s\" WHERE key = intAsBlob(%d)", KEYSPACE1, CF_STANDARD3, i));
assertNotNull(result);
assertEquals(ByteBufferUtil.bytes(i), result.one().getBytes("key"));
assertEquals("name" + i, result.one().getString("name"));
assertEquals("val" + i, result.one().getString("val"));
}
}
@Test
public void testAddBatch() throws IOException
{
long initialAllBatches = BatchlogManager.instance.countAllBatches();
TableMetadata cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD5).metadata();
long timestamp = (System.currentTimeMillis() - DatabaseDescriptor.getWriteRpcTimeout(MILLISECONDS) * 2) * 1000;
UUID uuid = UUIDGen.getTimeUUID();
// Add a batch with 10 mutations
List<Mutation> mutations = new ArrayList<>(10);
for (int j = 0; j < 10; j++)
{
mutations.add(new RowUpdateBuilder(cfm, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(j))
.clustering("name" + j)
.add("val", "val" + j)
.build());
}
BatchlogManager.store(Batch.createLocal(uuid, timestamp, mutations));
Assert.assertEquals(initialAllBatches + 1, BatchlogManager.instance.countAllBatches());
String query = String.format("SELECT count(*) FROM %s.%s where id = %s",
SchemaConstants.SYSTEM_KEYSPACE_NAME,
SystemKeyspace.BATCHES,
uuid);
UntypedResultSet result = executeInternal(query);
assertNotNull(result);
assertEquals(1L, result.one().getLong("count"));
}
@Test
public void testRemoveBatch()
{
long initialAllBatches = BatchlogManager.instance.countAllBatches();
TableMetadata cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD5).metadata();
long timestamp = (System.currentTimeMillis() - DatabaseDescriptor.getWriteRpcTimeout(MILLISECONDS) * 2) * 1000;
UUID uuid = UUIDGen.getTimeUUID();
// Add a batch with 10 mutations
List<Mutation> mutations = new ArrayList<>(10);
for (int j = 0; j < 10; j++)
{
mutations.add(new RowUpdateBuilder(cfm, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(j))
.clustering("name" + j)
.add("val", "val" + j)
.build());
}
// Store the batch
BatchlogManager.store(Batch.createLocal(uuid, timestamp, mutations));
Assert.assertEquals(initialAllBatches + 1, BatchlogManager.instance.countAllBatches());
// Remove the batch
BatchlogManager.remove(uuid);
assertEquals(initialAllBatches, BatchlogManager.instance.countAllBatches());
String query = String.format("SELECT count(*) FROM %s.%s where id = %s",
SchemaConstants.SYSTEM_KEYSPACE_NAME,
SystemKeyspace.BATCHES,
uuid);
UntypedResultSet result = executeInternal(query);
assertNotNull(result);
assertEquals(0L, result.one().getLong("count"));
}
// CASSANRDA-9223
@Test
public void testReplayWithNoPeers() throws Exception
{
StorageService.instance.getTokenMetadata().removeEndpoint(InetAddressAndPort.getByName("127.0.0.1"));
long initialAllBatches = BatchlogManager.instance.countAllBatches();
long initialReplayedBatches = BatchlogManager.instance.getTotalBatchesReplayed();
TableMetadata cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD1).metadata();
long timestamp = (System.currentTimeMillis() - DatabaseDescriptor.getWriteRpcTimeout(MILLISECONDS) * 2) * 1000;
UUID uuid = UUIDGen.getTimeUUID();
// Add a batch with 10 mutations
List<Mutation> mutations = new ArrayList<>(10);
for (int j = 0; j < 10; j++)
{
mutations.add(new RowUpdateBuilder(cfm, FBUtilities.timestampMicros(), ByteBufferUtil.bytes(j))
.clustering("name" + j)
.add("val", "val" + j)
.build());
}
BatchlogManager.store(Batch.createLocal(uuid, timestamp, mutations));
assertEquals(1, BatchlogManager.instance.countAllBatches() - initialAllBatches);
// Flush the batchlog to disk (see CASSANDRA-6822).
Keyspace.open(SchemaConstants.SYSTEM_KEYSPACE_NAME).getColumnFamilyStore(SystemKeyspace.BATCHES).forceBlockingFlush();
assertEquals(1, BatchlogManager.instance.countAllBatches() - initialAllBatches);
assertEquals(0, BatchlogManager.instance.getTotalBatchesReplayed() - initialReplayedBatches);
// Force batchlog replay and wait for it to complete.
BatchlogManager.instance.startBatchlogReplay().get();
// Replay should be cancelled as there are no peers in the ring.
assertEquals(1, BatchlogManager.instance.countAllBatches() - initialAllBatches);
}
}
| |
package com.androidbook.opengl;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.content.Context;
import android.opengl.GLDebugHelper;
import android.opengl.GLU;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SimpleLitGLCube extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAndroidSurface = new BasicGLSurfaceView(this);
setContentView(mAndroidSurface);
}
private class BasicGLSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
SurfaceHolder mAndroidHolder;
BasicGLSurfaceView(Context context) {
super(context);
mAndroidHolder = getHolder();
mAndroidHolder.addCallback(this);
mAndroidHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread = new BasicGLThread(this);
mGLThread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (mGLThread != null) {
mGLThread.requestStop();
}
}
}
BasicGLThread mGLThread;
private class BasicGLThread extends Thread {
SurfaceView sv;
BasicGLThread(SurfaceView view) {
sv = view;
}
private boolean mDone = false;
public void run() {
initEGL();
initGL();
CubeSmallGLUT cube = new CubeSmallGLUT(3);
mGL.glMatrixMode(GL10.GL_MODELVIEW);
mGL.glLoadIdentity();
GLU.gluLookAt(mGL, 0, 0, 8f, 0, 0, 0, 0, 1, 0f);
while (!mDone) {
mGL.glClear(GL10.GL_COLOR_BUFFER_BIT| GL10.GL_DEPTH_BUFFER_BIT);
mGL.glRotatef(1f, 1f, 1f, 1f);
mGL.glColor4f(1f, 0f, 0f, 1f);
cube.draw(mGL);
mGL.glFlush();
mEGL.eglSwapBuffers(mGLDisplay, mGLSurface);
}
}
public void requestStop() {
mDone = true;
try {
join();
} catch (InterruptedException e) {
Log.e("GL", "failed to stop gl thread", e);
}
cleanupGL();
}
private void cleanupGL() {
mEGL.eglMakeCurrent(mGLDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGL.eglDestroySurface(mGLDisplay, mGLSurface);
mEGL.eglDestroyContext(mGLDisplay, mGLContext);
mEGL.eglTerminate(mGLDisplay);
Log.i("GL", "GL Cleaned up");
}
public void initGL( ) {
int width = sv.getWidth();
int height = sv.getHeight();
mGL.glViewport(0, 0, width, height);
mGL.glMatrixMode(GL10.GL_PROJECTION);
mGL.glLoadIdentity();
float aspect = (float) width/height;
GLU.gluPerspective(mGL, 45.0f, aspect, 1.0f, 30.0f);
mGL.glClearColor(0.5f,0.5f,0.5f,1);
mGL.glClearDepthf(1.0f);
// light
mGL.glEnable(GL10.GL_LIGHTING);
// the first light
mGL.glEnable(GL10.GL_LIGHT0);
// ambient values
mGL.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, new float[] {0.1f, 0.1f, 0.1f, 1f}, 0);
// light that reflects in all directions
mGL.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, new float[] {1f, 1f, 1f, 1f}, 0);
// place it in projection space
mGL.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, new float[] {10f, 0f, 10f, 1}, 0);
// allow our object colors to create the diffuse/ambient material setting
mGL.glEnable(GL10.GL_COLOR_MATERIAL);
// some rendering options
mGL.glShadeModel(GL10.GL_SMOOTH);
mGL.glEnable(GL10.GL_DEPTH_TEST);
//mGL.glDepthFunc(GL10.GL_LEQUAL);
mGL.glEnable(GL10.GL_CULL_FACE);
mGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_NICEST);
// the only way to draw primitives with OpenGL ES
mGL.glEnableClientState(GL10.GL_VERTEX_ARRAY);
Log.i("GL", "GL initialized");
}
public void initEGL() {
mEGL = (EGL10) GLDebugHelper.wrap(EGLContext.getEGL(),
GLDebugHelper.CONFIG_CHECK_GL_ERROR
| GLDebugHelper.CONFIG_CHECK_THREAD, null);
mGLDisplay = mEGL.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] curGLVersion = new int[2];
mEGL.eglInitialize(mGLDisplay, curGLVersion);
Log.i("GL", "GL version = " + curGLVersion[0] + "."
+ curGLVersion[1]);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEGL.eglChooseConfig(mGLDisplay, mConfigSpec, configs, 1,
num_config);
mGLConfig = configs[0];
mGLSurface = mEGL.eglCreateWindowSurface(mGLDisplay, mGLConfig, sv
.getHolder(), null);
mGLContext = mEGL.eglCreateContext(mGLDisplay, mGLConfig,
EGL10.EGL_NO_CONTEXT, null);
mEGL.eglMakeCurrent(mGLDisplay, mGLSurface, mGLSurface, mGLContext);
mGL = (GL10) GLDebugHelper.wrap(mGLContext.getGL(),
GLDebugHelper.CONFIG_CHECK_GL_ERROR
| GLDebugHelper.CONFIG_CHECK_THREAD
| GLDebugHelper.CONFIG_LOG_ARGUMENT_NAMES, null);
}
// main OpenGL variables
GL10 mGL;
EGL10 mEGL;
EGLDisplay mGLDisplay;
EGLConfig mGLConfig;
EGLSurface mGLSurface;
EGLContext mGLContext;
int[] mConfigSpec = { EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE, 6, EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE };
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
SurfaceView mAndroidSurface;
}
| |
/*_############################################################################
_##
_## SNMP4J-Agent - CommandProcessor.java
_##
_## Copyright (C) 2005-2009 Frank Fock (SNMP4J.org)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
package org.snmp4j.agent;
import java.util.*;
import org.snmp4j.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.agent.security.*;
import org.snmp4j.event.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.util.*;
import org.snmp4j.agent.util.TemporaryList;
import org.snmp4j.agent.mo.snmp.CoexistenceInfo;
import org.snmp4j.agent.mo.snmp.CoexistenceInfoProvider;
import org.snmp4j.log.LogAdapter;
import org.snmp4j.log.LogFactory;
import org.snmp4j.agent.mo.snmp.NotificationLogListener;
import org.snmp4j.agent.mo.snmp.NotificationLogEvent;
/**
* The <code>CommandProcessor</code> is the central glue code that puts together
* the various sub-systems of a SNMP agent.
*
* @author Frank Fock
* @version 1.0
*/
public class CommandProcessor
implements CommandResponder, NotificationOriginator {
private static final LogAdapter logger =
LogFactory.getLogger(CommandProcessor.class);
/**
* The maximum request timeout supported by this command processor
* (by default 300.000 ms = 5 min).
*/
private static final int MAX_INTERNAL_REQUEST_TIMEOUT = 300000;
protected WorkerPool threadPool = null;
protected VACM vacm = null;
protected Vector moServers;
protected OctetString ownContextEngineID;
protected Vector pduHandler;
protected TemporaryList requestList;
protected RequestFactory requestFactory;
protected NotificationOriginator notificationOriginator;
protected ProxyMap proxyForwarder;
protected CoexistenceInfoProvider coexistenceProvider;
private transient Vector counterListeners;
public CommandProcessor(OctetString contextEngineID) {
this.ownContextEngineID = contextEngineID;
moServers = new Vector();
requestList = new TemporaryList(MAX_INTERNAL_REQUEST_TIMEOUT);
pduHandler = new Vector();
pduHandler.add(new GetHandler());
pduHandler.add(new GetNextHandler());
pduHandler.add(new SetHandler());
pduHandler.add(new GetBulkHandler());
requestFactory = new DefaultRequestFactory();
}
/**
* Sets the internal request timeout. Any request must return within this
* amount of milli-seconds. Default is five minutes.
* @param timeoutMillis
* the maximum number of milli-seconds a request can be processed.
* @since 1.3
*/
public void setInternalRequestTimeout(int timeoutMillis) {
requestList.setTimeout(timeoutMillis);
}
/**
* Gets the internal request timeout millis.
* @return
* the maximum number of milli-seconds a request can be processed.
* @since 1.3
*/
public int getInternalRequestTimeout() {
return requestList.getTimeout();
}
public void processPdu(CommandResponderEvent event) {
if (event.getPDU() != null) {
CoexistenceInfo cinfo = null;
OctetString sname = new OctetString(event.getSecurityName());
if (event.getPDU() instanceof ScopedPDU) {
ScopedPDU spdu = (ScopedPDU)event.getPDU();
cinfo = new CoexistenceInfo(sname,
spdu.getContextEngineID(),
spdu.getContextName());
}
else if (coexistenceProvider != null) {
CoexistenceInfo[] cinfos =
coexistenceProvider.getCoexistenceInfo(sname);
if ((cinfos != null) && (cinfos.length > 0)) {
for (int i=0; i<cinfos.length; i++) {
if (coexistenceProvider.passesFilter(event.getPeerAddress(),
cinfos[i])) {
cinfo = cinfos[i];
break;
}
}
if (cinfo == null) {
logger.warn("Access attempt from "+event.getPeerAddress()+
" denied because of source address filtering");
fireIncrementCounter(
new CounterEvent(this,
SnmpConstants.snmpInBadCommunityNames));
return;
}
event.setMaxSizeResponsePDU(cinfo.getMaxMessageSize());
}
else {
if (logger.isInfoEnabled()) {
logger.info("Community name '"+sname+
"' not found in SNMP-COMMUNITY-MIB");
}
fireIncrementCounter(
new CounterEvent(this,
SnmpConstants.snmpInBadCommunityNames));
return;
}
}
if ((cinfo == null) ||
(ownContextEngineID.equals(cinfo.getContextEngineID()))) {
event.setProcessed(true);
Command command = new Command(event, cinfo);
if (threadPool != null) {
threadPool.execute(command);
}
else {
command.run();
}
}
else if (proxyForwarder != null) {
ProxyForwardRequest request =
new ProxyForwardRequest(event, cinfo);
ProxyForwarder proxy =
proxyForwarder.get(cinfo.getContextEngineID(),
request.getProxyType());
ProxyCommand command = new ProxyCommand(proxy, request);
if (proxy != null) {
if (logger.isDebugEnabled()) {
logger.debug("Processsing proxy request with proxy forwarder "+
proxy);
}
if (threadPool != null) {
threadPool.execute(command);
}
else {
command.run();
}
}
else {
fireIncrementCounter(new CounterEvent(this,
SnmpConstants.snmpProxyDrops));
}
}
else {
fireIncrementCounter(new CounterEvent(this,
SnmpConstants.snmpSilentDrops));
}
}
}
/**
* Sets the internal thread pool for task execution.
*
* @param threadPool
* a pool of workers/threads which can execute tasks.
* @deprecated Use {@link #setWorkerPool} instead
*/
public void setThreadPool(WorkerPool threadPool) {
this.threadPool = threadPool;
}
/**
* Sets the internal thread pool for task execution.
*
* @param threadPool
* a pool of workers/threads which can execute tasks.
* @since 1.9
*/
public void setWorkerPool(WorkerPool threadPool) {
this.threadPool = threadPool;
}
public VACM getVacm() {
return vacm;
}
public void setVacm(VACM vacm) {
this.vacm = vacm;
}
public OctetString getContextEngineID() {
return ownContextEngineID;
}
public void setContextEngineID(OctetString contextEngineID) {
this.ownContextEngineID = contextEngineID;
}
/**
* Sends notification/inform messages to all registered targets. This method
* uses the internal {@link ThreadPool} to send the message(s) via the
* <code>NotificationOriginator</code>
* (see {@link #getNotificationOriginator}) to the targets specified by the
* SnmpTargetMIB and SnmpNotificationMIB instances supplied to the
* notification originator.
*
* @param context
* the context name of the context on whose behalf this notification has
* been generated.
* @param notificationID
* the object ID that uniquely identifies this notification. For SNMPv1
* traps, the notification ID has to be build using the rules provided
* by RFC 2576.
* @param vbs
* an array of <code>VariableBinding</code> instances representing the
* payload of the notification.
* @return
* an array of ResponseEvent instances or NotificationTask instance if
* the notification has been send asynchronously. Since the
* <code>NotificationOriginator</code> determines on behalf of the
* SNMP-NOTIFICTON-MIB contents whether a notification is sent as
* trap/notification or as inform request, the returned array will contain
* an element for each addressed target, but only a response PDU for
* inform targets.
* <p>
* <code>null</code> will be returned when sending the notification failed
* because there is no {@link NotificationOriginator} set.
* <p>
* NOTE: If this command processor is using a ThreadPool then the returned
* object will be {@link NotificationTask} instance. If all response have
* been received {@link Object#notify()} will be called on the returned
* <code>NotificationTask</code> object by the sending thread.
*/
public Object notify(final OctetString context,
final OID notificationID,
final VariableBinding[] vbs) {
return notify(context, notificationID, null, vbs);
}
public Object notify(OctetString context, OID notificationID,
TimeTicks sysUpTime, VariableBinding[] vbs) {
if (notificationOriginator != null) {
NotificationTask notifyTask =
new NotificationTask(notificationOriginator,
context, notificationID,
sysUpTime, vbs);
if (threadPool != null) {
threadPool.execute(notifyTask);
return notifyTask;
}
else {
notifyTask.run();
return notifyTask.getResponses();
}
}
else {
logger.warn("Could not sent notification '"+notificationID+"'="+
Arrays.asList(vbs)+" because NotificationOriginator not set");
}
return null;
}
public void setNotificationOriginator(NotificationOriginator
notificationOriginator) {
this.notificationOriginator = notificationOriginator;
}
public void setCoexistenceProvider(CoexistenceInfoProvider
coexistenceProvider) {
this.coexistenceProvider = coexistenceProvider;
}
public ProxyForwarder addProxyForwarder(ProxyForwarder proxyForwarder,
OctetString contextEngineID,
int proxyType) {
if (this.proxyForwarder == null) {
this.proxyForwarder = new ProxyMap();
}
return this.proxyForwarder.add(proxyForwarder, contextEngineID, proxyType);
}
public ProxyForwarder removeProxyForwarder(OctetString contextEngineID,
int proxyType) {
if (proxyForwarder != null) {
return proxyForwarder.remove(contextEngineID, proxyType);
}
return null;
}
protected RequestHandler getHandler(int pduType) {
synchronized (pduHandler) {
for (int i = 0; i < pduHandler.size(); i++) {
RequestHandler handler = (RequestHandler) pduHandler.get(i);
if (handler.isSupported(pduType)) {
return handler;
}
}
}
return null;
}
protected void dispatchCommand(CommandResponderEvent command,
CoexistenceInfo cinfo) {
RequestHandler handler = getHandler(command.getPDU().getType());
if (handler != null) {
processRequest(command, cinfo, handler);
}
else {
sendUnknownPDUHandlersReport(command);
}
}
private void sendUnknownPDUHandlersReport(CommandResponderEvent command) {
logger.info("No PDU handler found for request "+command);
CounterEvent counter =
new CounterEvent(this, SnmpConstants.snmpUnknownPDUHandlers);
fireIncrementCounter(counter);
if ((command.getMessageProcessingModel() == MessageProcessingModel.MPv3) &&
(command.getPDU() instanceof ScopedPDU)) {
ScopedPDU request = (ScopedPDU) command.getPDU();
ScopedPDU report = new ScopedPDU();
report.setContextEngineID(request.getContextEngineID());
report.setContextName(request.getContextName());
report.setType(PDU.REPORT);
report.add(new VariableBinding(counter.getOid(),
counter.getCurrentValue()));
sendResponse(command, report);
}
else {
PDU resp = (PDU) command.getPDU().clone();
resp.setErrorStatus(PDU.genErr);
sendResponse(command, resp);
}
}
protected void processRequest(CommandResponderEvent command,
CoexistenceInfo cinfo, RequestHandler handler) {
Request req = requestFactory.createRequest(command, cinfo);
requestList.add(req);
MOServer server = null;
OctetString context = req.getContext();
OctetString viewName = getViewName(command, cinfo, req.getViewType());
if (viewName == null) {
setAuthorizationError(req, VACM.VACM_NO_SUCH_VIEW);
}
else {
req.setViewName(viewName);
server = getServer(context);
processRequest(server, handler, req);
}
finalizeRequest(command, req, server);
}
protected void reprocessRequest(MOServer server, SnmpRequest req) {
RequestHandler handler =
getHandler(req.getInitiatingEvent().getPDU().getType());
if (handler != null) {
req.resetProcessedStatus();
req.incReprocessCounter();
processRequest(server, handler, req);
}
else {
sendUnknownPDUHandlersReport(req.getInitiatingEvent());
}
}
/**
* Processs (or re-process) a request and try to complete the request (thus
* to complete any incomplete subrequests).
*
* @param server
* the <code>MOServer</code> instance to use for accessing instrumentation.
* @param handler
* the <code>RequestHandler</code> to use to process the request.
* @param req
* the <code>Request</code>.
*/
protected void processRequest(MOServer server,
RequestHandler handler,
Request req) {
if (server == null) {
logger.error("No server for "+req.getContext()+
" found -> request cannot be processed");
req.setErrorStatus(SnmpConstants.SNMP_ERROR_GENERAL_ERROR);
}
else {
handler.processPdu(req, server);
}
}
protected void finalizeRequest(CommandResponderEvent command, Request req,
MOServer server) {
if (req.isComplete()) {
requestList.remove(req);
// send response
sendResponse(command, (PDU)req.getResponse());
if (server != null) {
release(server, req);
}
}
}
protected void release(MOServer server, Request req) {
for (Iterator it = req.iterator(); it.hasNext();) {
SubRequest sreq = (SubRequest)it.next();
if (sreq.getTargetMO() != null) {
server.unlock(req, sreq.getTargetMO());
}
}
}
protected void sendResponse(CommandResponderEvent requestEvent,
PDU response) {
MessageDispatcher disp = requestEvent.getMessageDispatcher();
try {
if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
// response is tooBig
if (response.getType() != PDU.REPORT) {
if (requestEvent.getPDU().getType() == PDU.GETBULK) {
while ((response.size() > 0) &&
(response.getBERLength() >
requestEvent.getMaxSizeResponsePDU())) {
response.trim();
}
}
else {
response.clear();
response.setRequestID(requestEvent.getPDU().getRequestID());
response.setErrorStatus(PDU.tooBig);
}
}
if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
fireIncrementCounter(new CounterEvent(this,
SnmpConstants.snmpSilentDrops));
return;
}
}
StatusInformation status = new StatusInformation();
StateReference stateRef = requestEvent.getStateReference();
if (stateRef == null) {
logger.warn("No state reference available for requestEvent="+
requestEvent+". Cannot return response="+response);
}
else {
stateRef.setTransportMapping(requestEvent.getTransportMapping());
disp.returnResponsePdu(requestEvent.getMessageProcessingModel(),
requestEvent.getSecurityModel(),
requestEvent.getSecurityName(),
requestEvent.getSecurityLevel(),
response,
requestEvent.getMaxSizeResponsePDU(),
requestEvent.getStateReference(),
status);
}
}
catch (MessageException ex) {
logger.error("Failed to send response to request "+requestEvent, ex);
}
}
protected void setAuthorizationError(Request req, int vacmStatus) {
if (req.size() > 0) {
SubRequest sreq = (SubRequest) req.iterator().next();
sreq.getStatus().setErrorStatus(PDU.authorizationError);
}
else {
req.setErrorStatus(PDU.authorizationError);
}
}
public void addPduHandler(RequestHandler handler) {
pduHandler.add(handler);
}
public void removePduHandler(RequestHandler handler) {
pduHandler.remove(handler);
}
public void addMOServer(MOServer server) {
moServers.add(server);
}
public void removeMOServer(MOServer server) {
moServers.remove(server);
}
public MOServer getServer(OctetString context) {
for (int i=0; i<moServers.size(); i++) {
MOServer s = (MOServer)moServers.get(i);
if (s.isContextSupported(context)) {
return s;
}
}
return null;
}
public TemporaryList getRequestList() {
return requestList;
}
public NotificationOriginator getNotificationOriginator() {
return notificationOriginator;
}
public ProxyMap getProxyForwarder() {
return proxyForwarder;
}
public CoexistenceInfoProvider getCoexistenceProvider() {
return coexistenceProvider;
}
class Command implements WorkerTask {
private CommandResponderEvent request;
private CoexistenceInfo cinfo;
public Command(CommandResponderEvent event, CoexistenceInfo cinfo) {
this.request = event;
this.cinfo = cinfo;
}
public void run() {
dispatchCommand(request, cinfo);
}
public void terminate() {
}
public void join() throws InterruptedException {
}
public void interrupt() {
}
}
class ProxyCommand implements WorkerTask {
private ProxyForwardRequest request;
private ProxyForwarder forwarder;
public ProxyCommand(ProxyForwarder forwarder, ProxyForwardRequest event) {
this.forwarder = forwarder;
this.request = event;
}
public void run() {
if (forwarder.forward(request)) {
PDU response = request.getResponsePDU();
if (response != null) {
sendResponse(request.getCommandEvent(), response);
}
}
else if (request.getProxyType() != ProxyForwarder.PROXY_TYPE_NOTIFY) {
// proxy drop
CounterEvent cevent = new CounterEvent(this,
SnmpConstants.snmpProxyDrops);
fireIncrementCounter(cevent);
CommandResponderEvent cre = request.getCommandEvent();
if ((cre.getMessageProcessingModel() == MPv3.ID) &&
(cre.getStateReference() != null)) {
ScopedPDU reportPDU = new ScopedPDU();
reportPDU.setType(PDU.REPORT);
reportPDU.setContextEngineID(request.getContextEngineID());
reportPDU.setContextName(request.getContext());
reportPDU.add(new VariableBinding(SnmpConstants.snmpProxyDrops,
cevent.getCurrentValue()));
sendResponse(request.getCommandEvent(), reportPDU);
}
}
}
public void terminate() {
// we cannot terminate (gracefully) this task while it is being executed
}
public void join() throws InterruptedException {
}
public void interrupt() {
}
}
protected OctetString getViewName(CommandResponderEvent req,
CoexistenceInfo cinfo,
int viewType) {
OctetString viewName =
vacm.getViewName(cinfo.getContextName(),
cinfo.getSecurityName(),
req.getSecurityModel(),
req.getSecurityLevel(),
viewType);
return viewName;
}
protected void processNextSubRequest(Request request, MOServer server,
OctetString context,
SubRequest sreq)
throws NoSuchElementException
{
// We can be sure to have a default context scope here because
// the inner class SnmpSubRequest creates it!
DefaultMOContextScope scope = (DefaultMOContextScope) sreq.getScope();
MOQuery query = sreq.getQuery();
if (query == null) {
query = new VACMQuery(context,
scope.getLowerBound(),
scope.isLowerIncluded(),
scope.getUpperBound(),
scope.isUpperIncluded(),
request.getViewName());
sreq.setQuery(query);
}
while (!sreq.getStatus().isProcessed()) {
ManagedObject mo = server.lookup(query);
if (mo == null) {
if (logger.isDebugEnabled()) {
logger.debug("EndOfMibView at scope="+scope+" and query "+query);
}
sreq.getVariableBinding().setVariable(Null.endOfMibView);
sreq.getStatus().setPhaseComplete(true);
continue;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("Processing NEXT query "+query+" with "+mo+
" sub-request with index "+sreq.getIndex());
}
boolean counter64Skip = false;
if ((!mo.next(sreq)) ||
(counter64Skip = ((request.getMessageProcessingModel() == MPv1.ID) &&
(sreq.getVariableBinding().getSyntax() ==
SMIConstants.SYNTAX_COUNTER64)))) {
sreq.getVariableBinding().setVariable(Null.instance);
if (counter64Skip) {
scope.lowerBound = sreq.getVariableBinding().getOid();
scope.lowerIncluded = false;
sreq.getStatus().setProcessed(false);
}
else {
scope.substractScope(mo.getScope());
// don't forget to update VACM query:
query.substractScope(mo.getScope());
}
}
}
catch (Exception moex) {
if (logger.isDebugEnabled()) {
moex.printStackTrace();
}
logger.error("Exception occurred while executing NEXT query: "+
moex.getMessage(), moex);
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.genErr);
}
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
}
public synchronized void addCounterListener(CounterListener l) {
if (counterListeners == null) {
counterListeners = new Vector(2);
}
counterListeners.add(l);
}
public synchronized void removeCounterListener(CounterListener l) {
if (counterListeners != null) {
counterListeners.remove(l);
}
}
protected void fireIncrementCounter(CounterEvent event) {
if (counterListeners != null) {
Vector listeners = counterListeners;
int count = listeners.size();
for (int i = 0; i < count; i++) {
((CounterListener) listeners.elementAt(i)).incrementCounter(event);
}
}
}
private static void initRequestPhase(Request request) {
if (request.getPhase() == Request.PHASE_INIT) {
request.nextPhase();
}
}
class GetNextHandler implements RequestHandler {
public void processPdu(Request request, MOServer server) {
initRequestPhase(request);
OctetString context = request.getContext();
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while (it.hasNext()) {
SubRequest sreq = it.nextSubRequest();
processNextSubRequest(request, server, context, sreq);
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
logger.error("SubRequest not found");
request.setErrorStatus(PDU.genErr);
}
}
public boolean isSupported(int pduType) {
return (pduType == PDU.GETNEXT);
}
}
class SetHandler implements RequestHandler {
public void prepare(OctetString context,
Request request, MOServer server) {
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while ((!request.isPhaseComplete()) && (it.hasNext())) {
SubRequest sreq = it.nextSubRequest();
if (sreq.isComplete()) {
continue;
}
MOScope scope = sreq.getScope();
MOQuery query = sreq.getQuery();
if (query == null) {
// create a query for write access
query = new VACMQuery(context,
scope.getLowerBound(),
scope.isLowerIncluded(),
scope.getUpperBound(),
scope.isUpperIncluded(),
request.getViewName());
sreq.setQuery(query);
}
if (!query.getScope().isCovered(
new DefaultMOContextScope(context, scope))) {
sreq.getStatus().setErrorStatus(PDU.noAccess);
}
else {
ManagedObject mo = server.lookup(query);
if (mo == null) {
if ((query instanceof VACMQuery) &&
(!((VACMQuery)query).isAccessAllowed(scope.getLowerBound()))){
sreq.getStatus().setErrorStatus(PDU.noAccess);
}
else {
sreq.getStatus().setErrorStatus(PDU.noCreation);
}
break;
}
sreq.setTargetMO(mo);
if (server.lock(sreq.getRequest(), mo, requestList.getTimeout())) {
try {
mo.prepare(sreq);
}
catch (Exception moex) {
logger.error("Set request " + request +
" failed with exception",
moex);
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.genErr);
}
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
else {
logger.warn("Set request " + request +
" failed because "+mo+" could not be locked");
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.genErr);
}
}
}
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
logger.error("Cannot find sub-request: ", nsex);
request.setErrorStatus(PDU.genErr);
}
}
public void processPdu(Request request, MOServer server) {
OctetString context = request.getContext();
try {
while (request.getPhase() < Request.PHASE_2PC_CLEANUP) {
int phase = request.nextPhase();
switch (phase) {
case Request.PHASE_2PC_PREPARE: {
prepare(context, request, server);
break;
}
case Request.PHASE_2PC_COMMIT: {
commit(context, request, server);
break;
}
case Request.PHASE_2PC_UNDO: {
undo(context, request, server);
break;
}
case Request.PHASE_2PC_CLEANUP: {
cleanup(context, request, server);
return;
}
}
if (!request.isPhaseComplete()) {
// request needs to be reprocessed later!
return;
}
}
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
ex.printStackTrace();
}
logger.error("Failed to process SET request, trying to clean it up...",
ex);
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(ex);
}
}
cleanup(context, request, server);
}
protected void undo(OctetString context, Request request,
MOServer server) {
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while (it.hasNext()) {
SubRequest sreq = it.nextSubRequest();
if (sreq.isComplete()) {
continue;
}
OID oid = sreq.getVariableBinding().getOid();
ManagedObject mo = sreq.getTargetMO();
if (mo == null) {
DefaultMOContextScope scope =
new DefaultMOContextScope(context, oid, true, oid, true);
mo = server.lookup(new DefaultMOQuery(scope, true, request));
}
if (mo == null) {
sreq.getStatus().setErrorStatus(PDU.undoFailed);
continue;
}
try {
mo.undo(sreq);
}
catch (Exception moex) {
if (logger.isDebugEnabled()) {
moex.printStackTrace();
}
logger.error(moex);
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.undoFailed);
}
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
logger.error("Cannot find sub-request: ", nsex);
request.setErrorStatus(PDU.genErr);
}
}
protected void commit(OctetString context, Request request,
MOServer server) {
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while ((request.getErrorStatus() == PDU.noError) && (it.hasNext())) {
SubRequest sreq = it.nextSubRequest();
if (sreq.isComplete()) {
continue;
}
OID oid = sreq.getVariableBinding().getOid();
ManagedObject mo = sreq.getTargetMO();
if (mo == null) {
DefaultMOContextScope scope =
new DefaultMOContextScope(context, oid, true, oid, true);
mo = server.lookup(new DefaultMOQuery(scope, true, request));
}
if (mo == null) {
sreq.getStatus().setErrorStatus(PDU.commitFailed);
continue;
}
try {
mo.commit(sreq);
}
catch (Exception moex) {
if (logger.isDebugEnabled()) {
moex.printStackTrace();
}
logger.error(moex);
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.commitFailed);
}
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
logger.error("Cannot find sub-request: ", nsex);
request.setErrorStatus(PDU.genErr);
}
}
protected void cleanup(OctetString context, Request request,
MOServer server) {
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while (it.hasNext()) {
SubRequest sreq = it.nextSubRequest();
if (sreq.isComplete()) {
continue;
}
OID oid = sreq.getVariableBinding().getOid();
ManagedObject mo = sreq.getTargetMO();
if (mo == null) {
DefaultMOContextScope scope =
new DefaultMOContextScope(context, oid, true, oid, true);
mo = server.lookup(new DefaultMOQuery(scope));
}
if (mo == null) {
sreq.completed();
continue;
}
server.unlock(sreq.getRequest(), mo);
try {
mo.cleanup(sreq);
sreq.getStatus().setPhaseComplete(true);
}
catch (Exception moex) {
if (logger.isDebugEnabled()) {
moex.printStackTrace();
}
logger.error(moex);
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
}
catch (NoSuchElementException nsex) {
logger.error("Cannot find sub-request: ", nsex);
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
}
}
public boolean isSupported(int pduType) {
return (pduType == PDU.SET);
}
}
class GetHandler implements RequestHandler {
public boolean isSupported(int pduType) {
return (pduType == PDU.GET);
}
public void processPdu(Request request, MOServer server) {
initRequestPhase(request);
OctetString context = request.getContext();
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
while (it.hasNext()) {
SubRequest sreq = it.nextSubRequest();
MOScope scope = sreq.getScope();
MOQuery query = sreq.getQuery();
if (query == null) {
query = new VACMQuery(context,
scope.getLowerBound(),
scope.isLowerIncluded(),
scope.getUpperBound(),
scope.isUpperIncluded(),
request.getViewName());
sreq.setQuery(query);
}
ManagedObject mo = server.lookup(query);
if (mo == null) {
sreq.getVariableBinding().setVariable(Null.noSuchObject);
sreq.getStatus().setPhaseComplete(true);
continue;
}
try {
mo.get(sreq);
if ((request.getMessageProcessingModel() == MPv1.ID) &&
(sreq.getVariableBinding().getSyntax() ==
SMIConstants.SYNTAX_COUNTER64)) {
sreq.getVariableBinding().setVariable(Null.noSuchInstance);
}
}
catch (Exception moex) {
if (logger.isDebugEnabled()) {
moex.printStackTrace();
}
logger.warn(moex);
if (sreq.getStatus().getErrorStatus() == PDU.noError) {
sreq.getStatus().setErrorStatus(PDU.genErr);
}
if (SNMP4JSettings.isFowardRuntimeExceptions()) {
throw new RuntimeException(moex);
}
}
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
nsex.printStackTrace();
}
logger.error("SubRequest not found");
request.setErrorStatus(PDU.genErr);
}
}
}
class GetBulkHandler implements RequestHandler {
public boolean isSupported(int pduType) {
return (pduType == PDU.GETBULK);
}
public void processPdu(Request request, MOServer server) {
initRequestPhase(request);
OctetString context = request.getContext();
SnmpRequest req = (SnmpRequest)request;
int nonRep = req.getNonRepeaters();
try {
SubRequestIterator it = (SubRequestIterator) request.iterator();
int i = 0;
// non repeaters
for (; ((i < nonRep) && it.hasNext()); i++) {
SubRequest sreq = it.nextSubRequest();
if (!sreq.isComplete()) {
processNextSubRequest(request, server, context, sreq);
}
}
// repetitions
for (; it.hasNext(); i++) {
SubRequest sreq = it.nextSubRequest();
if (!sreq.isComplete()) {
processNextSubRequest(request, server, context, sreq);
sreq.updateNextRepetition();
}
}
}
catch (NoSuchElementException nsex) {
if (logger.isDebugEnabled()) {
logger.debug("GETBULK request response PDU size limit reached");
}
}
}
}
class VACMQuery extends DefaultMOQuery {
private OctetString viewName;
/**
* Creates a VACMQuery for read-only access.
* @param context
* the context for the query, an empty OctetString denotes the default
* context.
* @param lowerBound
* the lower bound OID.
* @param isLowerIncluded
* indicates whether the lower bound should be included or not.
* @param upperBound
* the upper bound OID or <code>null</code> if no upper bound is
* specified.
* @param isUpperIncluded
* indicates whether the upper bound should be included or not.
* @param viewName
* the view name to use for the query.
* @deprecated
* Use a constructor with <code>source</code> reference parameter instead.
*/
public VACMQuery(OctetString context,
OID lowerBound, boolean isLowerIncluded,
OID upperBound, boolean isUpperIncluded,
OctetString viewName) {
super(new DefaultMOContextScope(context,
lowerBound, isLowerIncluded,
upperBound, isUpperIncluded));
this.viewName = viewName;
}
/**
* Creates a VACMQuery for read-only access.
* @param context
* the context for the query, an empty OctetString denotes the default
* context.
* @param lowerBound
* the lower bound OID.
* @param isLowerIncluded
* indicates whether the lower bound should be included or not.
* @param upperBound
* the upper bound OID or <code>null</code> if no upper bound is
* specified.
* @param isUpperIncluded
* indicates whether the upper bound should be included or not.
* @param viewName
* the view name to use for the query.
* @param isWriteAccessIntended
* indicates if this query is issued on behalf of a SNMP SET request
* or not.
* @param source
* the source ({@link Request}) object on whose behalf this query is
* executed.
* @since 1.1
*/
public VACMQuery(OctetString context,
OID lowerBound, boolean isLowerIncluded,
OID upperBound, boolean isUpperIncluded,
OctetString viewName,
boolean isWriteAccessIntended,
Object source) {
super(new DefaultMOContextScope(context,
lowerBound, isLowerIncluded,
upperBound, isUpperIncluded),
isWriteAccessIntended, source);
this.viewName = viewName;
}
public boolean isSearchQuery() {
MOContextScope scope = getScope();
return ((!scope.isLowerIncluded()) &&
((scope.getUpperBound() == null) ||
(!scope.getUpperBound().equals(scope.getLowerBound()))));
}
public boolean matchesQuery(ManagedObject managedObject) {
OID oid;
if (isSearchQuery()) {
oid = managedObject.find(getScope());
if (oid == null) {
return false;
}
}
else {
oid = getScope().getLowerBound();
}
return (vacm.isAccessAllowed(viewName, oid) == VACM.VACM_OK);
}
public boolean isAccessAllowed(OID oid) {
return (vacm.isAccessAllowed(viewName, oid) == VACM.VACM_OK);
}
public String toString() {
return super.toString()+
"[viewName="+viewName+"]";
}
}
static class DefaultRequestFactory implements RequestFactory {
public Request createRequest(EventObject initiatingEvent,
CoexistenceInfo cinfo) {
return new SnmpRequest((CommandResponderEvent)initiatingEvent, cinfo);
}
}
}
| |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio.tcp;
import com.hazelcast.internal.networking.Channel;
import com.hazelcast.internal.networking.nio.NioChannel;
import com.hazelcast.internal.networking.nio.NioInboundPipeline;
import com.hazelcast.nio.Packet;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.TestThread;
import org.junit.Before;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.junit.Assert.assertEquals;
/**
* This test will concurrently write to a single connection and check if all the data transmitted, is received
* on the other side.
* <p>
* In the past we had some issues with packet not getting written. So this test will write various size packets (from small
* to very large).
*/
@SuppressWarnings("WeakerAccess")
public abstract class TcpIpConnection_AbstractTransferStressTest extends TcpIpConnection_AbstractTest {
// total running time for writer threads
private static final long WRITER_THREAD_RUNNING_TIME_IN_SECONDS = MINUTES.toSeconds(2);
// maximum number of pending packets
private static final int maxPendingPacketCount = 10000;
// we create the payloads up front and select randomly from them. This is the number of payloads we are creating
private static final int payloadCount = 10000;
private final AtomicBoolean stop = new AtomicBoolean(false);
private DummyPayload[] payloads;
@Before
public void setup() throws Exception {
super.setup();
startAllConnectionManagers();
}
@Test
public void testTinyPackets() {
makePayloads(10);
testPackets();
}
@Test
public void testSmallPackets() {
makePayloads(100);
testPackets();
}
@Test
public void testMediumPackets() {
makePayloads(1000);
testPackets();
}
@Test(timeout = 10 * 60 * 1000)
public void testLargePackets() {
makePayloads(10000);
testPackets((10 * 60 * 1000) - (WRITER_THREAD_RUNNING_TIME_IN_SECONDS * 1000));
}
@Test
public void testSemiRealisticPackets() {
makeSemiRealisticPayloads();
testPackets();
}
private void testPackets() {
testPackets(ASSERT_TRUE_EVENTUALLY_TIMEOUT);
}
private void testPackets(long verifyTimeoutInMillis) {
TcpIpConnection c = connect(connManagerA, addressB);
WriteThread thread1 = new WriteThread(1, c);
WriteThread thread2 = new WriteThread(2, c);
logger.info("Starting");
thread1.start();
thread2.start();
sleepAndStop(stop, WRITER_THREAD_RUNNING_TIME_IN_SECONDS);
logger.info("Done");
thread1.assertSucceedsEventually();
thread2.assertSucceedsEventually();
// there is always one packet extra for the bind-request
final long expectedNormalPackets = thread1.normalPackets + thread2.normalPackets + 1;
final long expectedUrgentPackets = thread1.urgentPackets + thread2.urgentPackets;
logger.info("expected normal packets: " + expectedNormalPackets);
logger.info("expected priority packets: " + expectedUrgentPackets);
final TcpIpConnection connection = (TcpIpConnection) connManagerB.getConnection(addressA);
long start = System.currentTimeMillis();
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
logger.info("writer total frames pending : " + totalFramesPending(connection));
logger.info("writer last write time millis : " + connection.getChannel().lastWriteTimeMillis());
logger.info("reader total frames handled : " + framesRead(connection, false)
+ framesRead(connection, true));
logger.info("reader last read time millis : " + connection.getChannel().lastReadTimeMillis());
assertEquals(expectedNormalPackets, framesRead(connection, false));
assertEquals(expectedUrgentPackets, framesRead(connection, true));
}
}, verifyTimeoutInMillis);
logger.info("Waiting for pending packets to be sent and received finished in "
+ (System.currentTimeMillis() - start) + " milliseconds");
}
private int totalFramesPending(TcpIpConnection connection) {
Channel channel = connection.getChannel();
if (channel instanceof NioChannel) {
return ((NioChannel) channel).outboundPipeline().totalFramesPending();
} else {
throw new RuntimeException();
}
}
private long framesRead(TcpIpConnection connection, boolean priority) {
Channel channel = connection.getChannel();
if (channel instanceof NioChannel) {
NioInboundPipeline reader = ((NioChannel) channel).inboundPipeline();
return priority ? reader.priorityFramesRead() : reader.normalFramesRead();
} else {
throw new RuntimeException();
}
}
private void makePayloads(int maxSize) {
Random random = new Random();
payloads = new DummyPayload[payloadCount];
for (int k = 0; k < payloads.length; k++) {
final byte[] bytes = new byte[random.nextInt(maxSize)];
payloads[k] = new DummyPayload(bytes, false);
}
}
private void makeSemiRealisticPayloads() {
Random random = new Random();
payloads = new DummyPayload[payloadCount];
for (int k = 0; k < payloads.length; k++) {
// one in every 100 packet we make big
boolean largePacket = random.nextInt(100) == 1;
boolean ultraLarge = false;
if (largePacket) {
ultraLarge = random.nextInt(10) == 1;
}
int byteCount;
if (ultraLarge) {
byteCount = random.nextInt(100000);
} else if (largePacket) {
byteCount = random.nextInt(10000);
} else {
byteCount = random.nextInt(300);
}
// one in every 100 packet we make urgent
boolean urgentPacket = random.nextInt(100) == 1;
payloads[k] = new DummyPayload(new byte[byteCount], urgentPacket);
}
}
public class WriteThread extends TestThread {
private final Random random = new Random();
private final TcpIpConnection c;
private long normalPackets;
private long urgentPackets;
public WriteThread(int id, TcpIpConnection c) {
super("WriteThread-" + id);
this.c = c;
}
@Override
public void doRun() throws Throwable {
long prev = System.currentTimeMillis();
while (!stop.get()) {
Packet packet = nextPacket();
if (packet.isUrgent()) {
urgentPackets++;
} else {
normalPackets++;
}
c.getChannel().write(packet);
long now = System.currentTimeMillis();
if (now > prev + 2000) {
prev = now;
logger.info("At normal-packets:" + normalPackets + " priority-packets:" + urgentPackets);
}
double usage = getUsage();
if (usage < 90) {
continue;
}
for (; ; ) {
sleep(random.nextInt(5));
if (getUsage() < 10 || stop.get()) {
break;
}
}
}
logger.info("Finished, normal packets written: " + normalPackets
+ " urgent packets written:" + urgentPackets
+ " total frames pending:" + totalFramesPending(c));
}
private double getUsage() {
return 100d * totalFramesPending(c) / maxPendingPacketCount;
}
public Packet nextPacket() {
DummyPayload payload = payloads[random.nextInt(payloads.length)];
Packet packet = new Packet(serializationService.toBytes(payload));
if (payload.isUrgent()) {
packet.raiseFlags(Packet.FLAG_URGENT);
}
return packet;
}
}
}
| |
/*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* 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.hyracks.storage.am.lsm.common.impls;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.replication.IReplicationJob.ReplicationOperation;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.api.IIndexCursor;
import org.apache.hyracks.storage.am.common.api.ISearchPredicate;
import org.apache.hyracks.storage.am.common.api.IndexException;
import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperation;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallback;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexInternal;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import org.apache.hyracks.storage.am.lsm.common.api.ITwoPCIndex;
public class ExternalIndexHarness extends LSMHarness {
private static final Logger LOGGER = Logger.getLogger(ExternalIndexHarness.class.getName());
public ExternalIndexHarness(ILSMIndexInternal lsmIndex, ILSMMergePolicy mergePolicy, ILSMOperationTracker opTracker, boolean replicationEnabled) {
super(lsmIndex, mergePolicy, opTracker, replicationEnabled);
}
@Override
protected boolean getAndEnterComponents(ILSMIndexOperationContext ctx, LSMOperationType opType,
boolean isTryOperation) throws HyracksDataException {
synchronized (opTracker) {
while (true) {
lsmIndex.getOperationalComponents(ctx);
// Before entering the components, prune those corner cases that indeed should not proceed.
switch (opType) {
case MERGE:
if (ctx.getComponentHolder().size() < 2) {
// There is only a single component. There is nothing to merge.
return false;
}
default:
break;
}
if (enterComponents(ctx, opType)) {
return true;
} else if (isTryOperation) {
return false;
}
}
}
}
@Override
protected boolean enterComponents(ILSMIndexOperationContext ctx, LSMOperationType opType)
throws HyracksDataException {
List<ILSMComponent> components = ctx.getComponentHolder();
int numEntered = 0;
boolean entranceSuccessful = false;
try {
for (ILSMComponent c : components) {
if (!c.threadEnter(opType, false)) {
break;
}
numEntered++;
}
entranceSuccessful = numEntered == components.size();
} finally {
if (!entranceSuccessful) {
for (ILSMComponent c : components) {
if (numEntered == 0) {
break;
}
c.threadExit(opType, true, false);
numEntered--;
}
return false;
}
}
// Check if there is any action that is needed to be taken based on the operation type
switch (opType) {
case MERGE:
lsmIndex.getIOOperationCallback().beforeOperation(LSMOperationType.MERGE);
default:
break;
}
opTracker.beforeOperation(lsmIndex, opType, ctx.getSearchOperationCallback(), ctx.getModificationCallback());
return true;
}
private void exitComponents(ILSMIndexOperationContext ctx, LSMOperationType opType, ILSMComponent newComponent,
boolean failedOperation) throws HyracksDataException, IndexException {
synchronized (opTracker) {
try {
// First check if there is any action that is needed to be taken based on the state of each component.
for (ILSMComponent c : ctx.getComponentHolder()) {
c.threadExit(opType, failedOperation, false);
switch (c.getState()) {
case INACTIVE:
if (replicationEnabled) {
componentsToBeReplicated.clear();
componentsToBeReplicated.add(c);
lsmIndex.scheduleReplication(null, componentsToBeReplicated, false, ReplicationOperation.DELETE);
}
((AbstractDiskLSMComponent) c).destroy();
break;
default:
break;
}
}
// Then, perform any action that is needed to be taken based on the operation type.
switch (opType) {
case MERGE:
// newComponent is null if the merge op. was not performed.
if (newComponent != null) {
beforeSubsumeMergedComponents(newComponent, ctx.getComponentHolder());
lsmIndex.subsumeMergedComponents(newComponent, ctx.getComponentHolder());
if (replicationEnabled) {
componentsToBeReplicated.clear();
componentsToBeReplicated.add(newComponent);
triggerReplication(componentsToBeReplicated, false);
}
mergePolicy.diskComponentAdded(lsmIndex, fullMergeIsRequested.get());
}
break;
default:
break;
}
} finally {
opTracker.afterOperation(lsmIndex, opType, ctx.getSearchOperationCallback(),
ctx.getModificationCallback());
}
}
}
@Override
public void forceModify(ILSMIndexOperationContext ctx, ITupleReference tuple) throws HyracksDataException,
IndexException {
throw new IndexException("2PC LSM Inedx doesn't support modify");
}
@Override
public boolean modify(ILSMIndexOperationContext ctx, boolean tryOperation, ITupleReference tuple)
throws HyracksDataException, IndexException {
throw new IndexException("2PC LSM Inedx doesn't support modify");
}
@Override
public void search(ILSMIndexOperationContext ctx, IIndexCursor cursor, ISearchPredicate pred)
throws HyracksDataException, IndexException {
LSMOperationType opType = LSMOperationType.SEARCH;
getAndEnterComponents(ctx, opType, false);
try {
lsmIndex.search(ctx, cursor, pred);
} catch (HyracksDataException | IndexException e) {
exitComponents(ctx, opType, null, true);
throw e;
}
}
@Override
public void endSearch(ILSMIndexOperationContext ctx) throws HyracksDataException {
if (ctx.getOperation() == IndexOperation.SEARCH) {
try {
exitComponents(ctx, LSMOperationType.SEARCH, null, false);
} catch (IndexException e) {
throw new HyracksDataException(e);
}
}
}
@Override
public void scheduleMerge(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
throws HyracksDataException, IndexException {
if (!getAndEnterComponents(ctx, LSMOperationType.MERGE, true)) {
callback.afterFinalize(LSMOperationType.MERGE, null);
return;
}
lsmIndex.scheduleMerge(ctx, callback);
}
@Override
public void scheduleFullMerge(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
throws HyracksDataException, IndexException {
fullMergeIsRequested.set(true);
if (!getAndEnterComponents(ctx, LSMOperationType.MERGE, true)) {
// If the merge cannot be scheduled because there is already an ongoing merge on subset/all of the components, then
// whenever the current merge has finished, it will schedule the full merge again.
callback.afterFinalize(LSMOperationType.MERGE, null);
return;
}
fullMergeIsRequested.set(false);
lsmIndex.scheduleMerge(ctx, callback);
}
@Override
public void merge(ILSMIndexOperationContext ctx, ILSMIOOperation operation) throws HyracksDataException,
IndexException {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Started a merge operation for index: " + lsmIndex + " ...");
}
ILSMComponent newComponent = null;
try {
newComponent = lsmIndex.merge(operation);
operation.getCallback().afterOperation(LSMOperationType.MERGE, ctx.getComponentHolder(), newComponent);
lsmIndex.markAsValid(newComponent);
} finally {
exitComponents(ctx, LSMOperationType.MERGE, newComponent, false);
operation.getCallback().afterFinalize(LSMOperationType.MERGE, newComponent);
}
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Finished the merge operation for index: " + lsmIndex);
}
}
@Override
public void addBulkLoadedComponent(ILSMComponent c) throws HyracksDataException, IndexException {
lsmIndex.markAsValid(c);
synchronized (opTracker) {
lsmIndex.addComponent(c);
if (replicationEnabled) {
componentsToBeReplicated.clear();
componentsToBeReplicated.add(c);
triggerReplication(componentsToBeReplicated, true);
}
// Enter the component
enterComponent(c);
mergePolicy.diskComponentAdded(lsmIndex, false);
}
}
// Three differences from addBulkLoadedComponent
// 1. this needs synchronization since others might be accessing the index (specifically merge operations that might change the lists of components)
// 2. the actions taken by the index itself are different
// 3. the component has already been marked valid by the bulk update operation
public void addTransactionComponents(ILSMComponent newComponent) throws HyracksDataException, IndexException {
ITwoPCIndex index = (ITwoPCIndex) lsmIndex;
synchronized (opTracker) {
List<ILSMComponent> newerList;
List<ILSMComponent> olderList;
if (index.getCurrentVersion() == 0) {
newerList = index.getFirstComponentList();
olderList = index.getSecondComponentList();
} else {
newerList = index.getSecondComponentList();
olderList = index.getFirstComponentList();
}
// Exit components in old version of the index so they are ready to be
// deleted if they are not needed anymore
for (ILSMComponent c : olderList) {
exitComponent(c);
}
// Enter components in the newer list
for (ILSMComponent c : newerList) {
enterComponent(c);
}
if (newComponent != null) {
// Enter new component
enterComponent(newComponent);
}
index.commitTransactionDiskComponent(newComponent);
mergePolicy.diskComponentAdded(lsmIndex, fullMergeIsRequested.get());
}
}
@Override
public void scheduleFlush(ILSMIndexOperationContext ctx, ILSMIOOperationCallback callback)
throws HyracksDataException {
callback.afterFinalize(LSMOperationType.FLUSH, null);
}
@Override
public void flush(ILSMIndexOperationContext ctx, ILSMIOOperation operation) throws HyracksDataException,
IndexException {
}
@Override
public ILSMOperationTracker getOperationTracker() {
return opTracker;
}
public void beforeSubsumeMergedComponents(ILSMComponent newComponent, List<ILSMComponent> mergedComponents)
throws HyracksDataException {
ITwoPCIndex index = (ITwoPCIndex) lsmIndex;
// check if merge will affect the first list
if (index.getFirstComponentList().containsAll(mergedComponents)) {
// exit un-needed components
for (ILSMComponent c : mergedComponents) {
exitComponent(c);
}
// enter new component
enterComponent(newComponent);
}
// check if merge will affect the second list
if (index.getSecondComponentList().containsAll(mergedComponents)) {
// exit un-needed components
for (ILSMComponent c : mergedComponents) {
exitComponent(c);
}
// enter new component
enterComponent(newComponent);
}
}
// The two methods: enterComponent and exitComponent are used to control
// when components are to be deleted from disk
private void enterComponent(ILSMComponent diskComponent) throws HyracksDataException {
diskComponent.threadEnter(LSMOperationType.SEARCH, false);
}
private void exitComponent(ILSMComponent diskComponent) throws HyracksDataException {
diskComponent.threadExit(LSMOperationType.SEARCH, false, false);
if (diskComponent.getState() == ILSMComponent.ComponentState.INACTIVE) {
if (replicationEnabled) {
componentsToBeReplicated.clear();
componentsToBeReplicated.add(diskComponent);
lsmIndex.scheduleReplication(null, componentsToBeReplicated, false, ReplicationOperation.DELETE);
}
((AbstractDiskLSMComponent) diskComponent).destroy();
}
}
public void indexFirstTimeActivated() throws HyracksDataException {
ITwoPCIndex index = (ITwoPCIndex) lsmIndex;
// Enter disk components <-- To avoid deleting them when they are
// still needed-->
for (ILSMComponent c : index.getFirstComponentList()) {
enterComponent(c);
}
for (ILSMComponent c : index.getSecondComponentList()) {
enterComponent(c);
}
}
public void indexClear() throws HyracksDataException {
ITwoPCIndex index = (ITwoPCIndex) lsmIndex;
for (ILSMComponent c : index.getFirstComponentList()) {
exitComponent(c);
}
for (ILSMComponent c : index.getSecondComponentList()) {
exitComponent(c);
}
}
}
| |
package org.robolectric.shadows;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;
@RunWith(TestRunners.MultiApiSelfTest.class)
public class ShadowIntentTest {
private static final String TEST_ACTIVITY_CLASS_NAME = "org.robolectric.shadows.TestActivity";
@Test
@Config(manifest = "TestAndroidManifestForActivities.xml")
public void resolveActivityInfo_shouldReturnActivityInfoForExistingActivity() {
Context context = RuntimeEnvironment.application;
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent();
intent.setClassName(context, TEST_ACTIVITY_CLASS_NAME);
ActivityInfo activityInfo = intent.resolveActivityInfo(packageManager, PackageManager.GET_ACTIVITIES);
assertThat(activityInfo).isNotNull();
}
@Test
public void testGetExtraReturnsNull_whenThereAreNoExtrasAdded() throws Exception {
Intent intent = new Intent();
assertEquals(intent.getExtras(), null);
}
@Test
public void testStringExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", "bar"));
assertEquals("bar", intent.getExtras().get("foo"));
}
@Test
public void testCharSequenceExtra() throws Exception {
Intent intent = new Intent();
CharSequence cs = new TestCharSequence("bar");
assertSame(intent, intent.putExtra("foo", cs));
assertSame(cs, intent.getExtras().get("foo"));
}
@Test
public void testIntExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", 2));
assertEquals(2, intent.getExtras().get("foo"));
assertEquals(2, intent.getIntExtra("foo", -1));
}
@Test
public void testDoubleExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", 2d));
assertEquals(2d, intent.getExtras().get("foo"));
assertEquals(2d, intent.getDoubleExtra("foo", -1));
}
@Test
public void testFloatExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", 2f));
assertEquals(2f, intent.getExtras().get("foo"));
assertEquals(2f, intent.getFloatExtra("foo", -1));
}
@Test
public void testIntArrayExtra() throws Exception {
Intent intent = new Intent();
int[] array = new int[2];
array[0] = 1;
array[1] = 2;
assertSame(intent, intent.putExtra("foo", array));
assertEquals(1, intent.getIntArrayExtra("foo")[0]);
assertEquals(2, intent.getIntArrayExtra("foo")[1]);
}
@Test
public void testLongArrayExtra() throws Exception {
Intent intent = new Intent();
long[] array = new long[2];
array[0] = 1L;
array[1] = 2L;
assertSame(intent, intent.putExtra("foo", array));
assertEquals(1L, intent.getLongArrayExtra("foo")[0]);
assertEquals(2L, intent.getLongArrayExtra("foo")[1]);
}
@Test
public void testSerializableExtra() throws Exception {
Intent intent = new Intent();
TestSerializable serializable = new TestSerializable("some string");
assertSame(intent, intent.putExtra("foo", serializable));
assertEquals(serializable, intent.getExtras().get("foo"));
assertEquals(serializable, intent.getSerializableExtra("foo"));
}
@Test
public void testSerializableOfParcelableExtra() throws Exception {
Intent intent = new Intent();
ArrayList<Parcelable> serializable = new ArrayList<>();
serializable.add(new TestParcelable(12));
assertSame(intent, intent.putExtra("foo", serializable));
assertEquals(serializable, intent.getExtras().get("foo"));
assertEquals(serializable, intent.getSerializableExtra("foo"));
}
@Test
public void testParcelableExtra() throws Exception {
Intent intent = new Intent();
Parcelable parcelable = new TestParcelable(44);
assertSame(intent, intent.putExtra("foo", parcelable));
assertSame(parcelable, intent.getExtras().get("foo"));
assertSame(parcelable, intent.getParcelableExtra("foo"));
}
@Test
public void testParcelableArrayExtra() throws Exception {
Intent intent = new Intent();
Parcelable parcelable = new TestParcelable(11);
intent.putExtra("foo", parcelable);
assertSame(null, intent.getParcelableArrayExtra("foo"));
Parcelable[] parcelables = {new TestParcelable(12), new TestParcelable(13)};
assertSame(intent, intent.putExtra("bar", parcelables));
assertSame(parcelables, intent.getParcelableArrayExtra("bar"));
}
@Test
public void testParcelableArrayListExtra() {
Intent intent = new Intent();
Parcelable parcel1 = new TestParcelable(22);
Parcelable parcel2 = new TestParcelable(23);
ArrayList<Parcelable> parcels = new ArrayList<>();
parcels.add(parcel1);
parcels.add(parcel2);
assertSame(intent, intent.putParcelableArrayListExtra("foo", parcels));
assertSame(parcels, intent.getParcelableArrayListExtra("foo"));
assertSame(parcel1, intent.getParcelableArrayListExtra("foo").get(0));
assertSame(parcel2, intent.getParcelableArrayListExtra("foo").get(1));
assertSame(parcels, intent.getExtras().getParcelableArrayList("foo"));
}
@Test
public void testLongExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", 2L));
assertEquals(2L, intent.getExtras().get("foo"));
assertEquals(2L, intent.getLongExtra("foo", -1));
assertEquals(-1L, intent.getLongExtra("bar", -1));
}
@Test
public void testBundleExtra() throws Exception {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putInt("bar", 5);
assertSame(intent, intent.putExtra("foo", bundle));
assertEquals(5, intent.getBundleExtra("foo").getInt("bar"));
}
@Test
public void testHasExtra() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.putExtra("foo", ""));
assertTrue(intent.hasExtra("foo"));
assertFalse(intent.hasExtra("bar"));
}
@Test
public void testGetActionReturnsWhatWasSet() throws Exception {
Intent intent = new Intent();
assertSame(intent, intent.setAction("foo"));
assertEquals("foo", intent.getAction());
}
@Test
public void testSetData() throws Exception {
Intent intent = new Intent();
Uri uri = Uri.parse("content://this/and/that");
intent.setType("abc");
assertSame(intent, intent.setData(uri));
assertSame(uri, intent.getData());
assertNull(intent.getType());
}
@Test
public void testGetScheme() throws Exception {
Intent intent = new Intent();
Uri uri = Uri.parse("http://robolectric.org");
assertSame(intent, intent.setData(uri));
assertSame(uri, intent.getData());
assertEquals("http", intent.getScheme());
}
@Test
public void testSetType() throws Exception {
Intent intent = new Intent();
intent.setData(Uri.parse("content://this/and/that"));
assertSame(intent, intent.setType("def"));
assertNull(intent.getData());
assertEquals("def", intent.getType());
}
@Test
public void testSetDataAndType() throws Exception {
Intent intent = new Intent();
Uri uri = Uri.parse("content://this/and/that");
assertSame(intent, intent.setDataAndType(uri, "ghi"));
assertSame(uri, intent.getData());
assertEquals("ghi", intent.getType());
}
@Test
public void testSetClass() throws Exception {
Intent intent = new Intent();
Class<? extends ShadowIntentTest> thisClass = getClass();
Intent output = intent.setClass(RuntimeEnvironment.application, thisClass);
assertSame(output, intent);
assertThat(intent.getComponent().getClassName()).isEqualTo(thisClass.getName());
}
@Test
public void testSetClassName() throws Exception {
Intent intent = new Intent();
Class<? extends ShadowIntentTest> thisClass = getClass();
intent.setClassName("package.name", thisClass.getName());
assertSame(thisClass.getName(), intent.getComponent().getClassName());
assertEquals("package.name", intent.getComponent().getPackageName());
assertSame(intent.getComponent().getClassName(), thisClass.getName());
}
@Test
public void testSetClassThroughConstructor() throws Exception {
Intent intent = new Intent(RuntimeEnvironment.application, getClass());
assertThat(intent.getComponent().getClassName()).isEqualTo(getClass().getName());
}
@Test
public void shouldSetFlags() throws Exception {
Intent intent = new Intent();
Intent self = intent.setFlags(1234);
assertEquals(1234, intent.getFlags());
assertSame(self, intent);
}
@Test
public void shouldAddFlags() throws Exception {
Intent intent = new Intent();
Intent self = intent.addFlags(4);
self.addFlags(8);
assertEquals(12, intent.getFlags());
assertSame(self, intent);
}
@Test
public void shouldSupportCategories() throws Exception {
Intent intent = new Intent();
Intent self = intent.addCategory("category.name.1");
intent.addCategory("category.name.2");
assertTrue(intent.hasCategory("category.name.1"));
assertTrue(intent.hasCategory("category.name.2"));
Set<String> categories = intent.getCategories();
assertTrue(categories.contains("category.name.1"));
assertTrue(categories.contains("category.name.2"));
intent.removeCategory("category.name.1");
assertFalse(intent.hasCategory("category.name.1"));
assertTrue(intent.hasCategory("category.name.2"));
intent.removeCategory("category.name.2");
assertFalse(intent.hasCategory("category.name.2"));
assertThat(intent.getCategories()).isNull();
assertSame(self, intent);
}
@Test
public void shouldAddCategories() throws Exception {
Intent intent = new Intent();
Intent self = intent.addCategory("foo");
assertTrue(intent.getCategories().contains("foo"));
assertSame(self, intent);
}
@Test
public void shouldFillIn() throws Exception {
Intent intentA = new Intent();
Intent intentB = new Intent();
intentB.setAction("foo");
Uri uri = Uri.parse("http://www.foo.com");
intentB.setDataAndType(uri, "text/html");
String category = "category";
intentB.addCategory(category);
intentB.setPackage("com.foobar.app");
ComponentName cn = new ComponentName("com.foobar.app", "fragmentActivity");
intentB.setComponent(cn);
intentB.putExtra("FOO", 23);
int flags = Intent.FILL_IN_ACTION |
Intent.FILL_IN_DATA |
Intent.FILL_IN_CATEGORIES |
Intent.FILL_IN_PACKAGE |
Intent.FILL_IN_COMPONENT;
int result = intentA.fillIn(intentB, flags);
assertEquals("foo", intentA.getAction());
assertSame(uri, intentA.getData());
assertEquals("text/html", intentA.getType());
assertTrue(intentA.getCategories().contains(category));
assertEquals("com.foobar.app", intentA.getPackage());
assertSame(cn, intentA.getComponent());
assertEquals(23, intentA.getIntExtra("FOO", -1));
assertEquals(result, flags);
}
@Test
public void createChooser_shouldWrapIntent() throws Exception {
Intent originalIntent = new Intent(Intent.ACTION_BATTERY_CHANGED, Uri.parse("foo://blah"));
Intent chooserIntent = Intent.createChooser(originalIntent, "The title");
assertThat(chooserIntent.getAction()).isEqualTo(Intent.ACTION_CHOOSER);
assertThat(chooserIntent.getStringExtra(Intent.EXTRA_TITLE)).isEqualTo("The title");
assertThat((Intent) chooserIntent.getParcelableExtra(Intent.EXTRA_INTENT))
.isSameAs(originalIntent);
}
@Test
public void setUri_setsUri() throws Exception {
Intent intent = new Intent();
intent.setData(Uri.parse("http://foo"));
assertThat(intent.getData()).isEqualTo(Uri.parse("http://foo"));
}
@Test
public void setUri_shouldReturnUriString() throws Exception {
Intent intent = new Intent();
intent.setData(Uri.parse("http://foo"));
assertThat(intent.getDataString()).isEqualTo("http://foo");
}
@Test
public void setUri_shouldReturnNullUriString() throws Exception {
Intent intent = new Intent();
assertThat(intent.getDataString()).isNull();
}
@Test
public void putStringArrayListExtra_addsListToExtras() {
Intent intent = new Intent();
final ArrayList<String> strings = new ArrayList<>(Arrays.asList("hi", "there"));
intent.putStringArrayListExtra("KEY", strings);
assertThat(intent.getStringArrayListExtra("KEY")).isEqualTo(strings);
assertThat(intent.getExtras().getStringArrayList("KEY")).isEqualTo(strings);
}
@Test
public void putIntegerArrayListExtra_addsListToExtras() {
Intent intent = new Intent();
final ArrayList<Integer> integers = new ArrayList<>(Arrays.asList(100, 200, 300));
intent.putIntegerArrayListExtra("KEY", integers);
assertThat(intent.getIntegerArrayListExtra("KEY")).isEqualTo(integers);
assertThat(intent.getExtras().getIntegerArrayList("KEY")).isEqualTo(integers);
}
@Test
public void constructor_shouldSetComponentAndActionAndData() {
Intent intent = new Intent("roboaction", Uri.parse("http://www.robolectric.org"), RuntimeEnvironment.application, Activity.class);
assertThat(intent.getComponent()).isEqualTo(new ComponentName("org.robolectric", "android.app.Activity"));
assertThat(intent.getAction()).isEqualTo("roboaction");
assertThat(intent.getData()).isEqualTo(Uri.parse("http://www.robolectric.org"));
}
@Test
public void putExtra_shouldBeChainable() {
// Ensure that all putExtra methods return the Intent properly and can therefore be chained
// without causing NPE's
Intent intent = new Intent();
assertThat(intent.putExtra("double array", new double[] { 0.0 })).isEqualTo(intent);
assertThat(intent.putExtra("int", 0)).isEqualTo(intent);
assertThat(intent.putExtra("CharSequence", new TestCharSequence("test"))).isEqualTo(intent);
assertThat(intent.putExtra("char", 'a')).isEqualTo(intent);
assertThat(intent.putExtra("Bundle", new Bundle())).isEqualTo(intent);
assertThat(intent.putExtra("Parcelable array", new Parcelable[] { new TestParcelable(0) }))
.isEqualTo(intent);
assertThat(intent.putExtra("Serializable", new TestSerializable("test"))).isEqualTo(intent);
assertThat(intent.putExtra("int array", new int[] { 0 })).isEqualTo(intent);
assertThat(intent.putExtra("float", 0f)).isEqualTo(intent);
assertThat(intent.putExtra("byte array", new byte[] { 0 })).isEqualTo(intent);
assertThat(intent.putExtra("long array", new long[] { 0L })).isEqualTo(intent);
assertThat(intent.putExtra("Parcelable", new TestParcelable(0))).isEqualTo(intent);
assertThat(intent.putExtra("float array", new float[] { 0f })).isEqualTo(intent);
assertThat(intent.putExtra("long", 0L)).isEqualTo(intent);
assertThat(intent.putExtra("String array", new String[] { "test" })).isEqualTo(intent);
assertThat(intent.putExtra("boolean", true)).isEqualTo(intent);
assertThat(intent.putExtra("boolean array", new boolean[] { true })).isEqualTo(intent);
assertThat(intent.putExtra("short", (short) 0)).isEqualTo(intent);
assertThat(intent.putExtra("double", 0.0)).isEqualTo(intent);
assertThat(intent.putExtra("short array", new short[] { 0 })).isEqualTo(intent);
assertThat(intent.putExtra("String", "test")).isEqualTo(intent);
assertThat(intent.putExtra("byte", (byte) 0)).isEqualTo(intent);
assertThat(intent.putExtra("char array", new char[] { 'a' })).isEqualTo(intent);
assertThat(intent.putExtra("CharSequence array",
new CharSequence[] { new TestCharSequence("test") }))
.isEqualTo(intent);
}
@Test
public void equals_shouldOnlyBeIdentity() {
assertThat(new Intent()).isNotEqualTo(new Intent());
}
@Test
public void cloneFilter_shouldIncludeAction() {
Intent intent = new Intent("FOO");
intent.cloneFilter();
assertThat(intent.getAction()).isEqualTo("FOO");
}
@Test
public void getExtra_shouldWorkAfterParcel() {
ComponentName componentName = new ComponentName("barcomponent", "compclass");
Uri parsed = Uri.parse("https://foo.bar");
Intent intent = new Intent();
intent.putExtra("key", 123);
intent.setAction("Foo");
intent.setComponent(componentName);
intent.setData(parsed);
Parcel parcel = Parcel.obtain();
parcel.writeParcelable(intent, 0);
parcel.setDataPosition(0);
intent = parcel.readParcelable(getClass().getClassLoader());
assertThat(intent.getIntExtra("key", 0)).isEqualTo(123);
assertThat(intent.getAction()).isEqualTo("Foo");
assertThat(intent.getComponent()).isEqualTo(componentName);
assertThat(intent.getData()).isEqualTo(parsed);
}
private static class TestSerializable implements Serializable {
private String someValue;
public TestSerializable(String someValue) {
this.someValue = someValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestSerializable that = (TestSerializable) o;
if (someValue != null ? !someValue.equals(that.someValue) : that.someValue != null) return false;
return true;
}
@Override
public int hashCode() {
return someValue != null ? someValue.hashCode() : 0;
}
}
private class TestCharSequence implements CharSequence {
String s;
public TestCharSequence(String s) {
this.s = s;
}
@Override
public char charAt(int index) {
return s.charAt(index);
}
@Override
public int length() {
return s.length();
}
@Override
public CharSequence subSequence(int start, int end) {
return s.subSequence(start, end);
}
}
}
| |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents a Target VPN Gateway resource.
*
* The target VPN gateway resource represents a Classic Cloud VPN gateway. For more information,
* read the the Cloud VPN Overview. (== resource_for beta.targetVpnGateways ==) (== resource_for
* v1.targetVpnGateways ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class TargetVpnGateway extends com.google.api.client.json.GenericJson {
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* [Output Only] A list of URLs to the ForwardingRule resources. ForwardingRules are created using
* compute.forwardingRules.insert and associated with a VPN gateway.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> forwardingRules;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of resource. Always compute#targetVpnGateway for target VPN gateways.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
* gateway is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* [Output Only] URL of the region where the target VPN gateway resides. You must specify this
* field as part of the HTTP request URL. It is not settable as a field in the request body.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String region;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* [Output Only] The status of the VPN gateway, which can be one of the following: CREATING,
* READY, FAILED, or DELETING.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* [Output Only] A list of URLs to VpnTunnel resources. VpnTunnels are created using the
* compute.vpntunnels.insert method and associated with a VPN gateway.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> tunnels;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public TargetVpnGateway setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public TargetVpnGateway setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* [Output Only] A list of URLs to the ForwardingRule resources. ForwardingRules are created using
* compute.forwardingRules.insert and associated with a VPN gateway.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getForwardingRules() {
return forwardingRules;
}
/**
* [Output Only] A list of URLs to the ForwardingRule resources. ForwardingRules are created using
* compute.forwardingRules.insert and associated with a VPN gateway.
* @param forwardingRules forwardingRules or {@code null} for none
*/
public TargetVpnGateway setForwardingRules(java.util.List<java.lang.String> forwardingRules) {
this.forwardingRules = forwardingRules;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public TargetVpnGateway setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of resource. Always compute#targetVpnGateway for target VPN gateways.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of resource. Always compute#targetVpnGateway for target VPN gateways.
* @param kind kind or {@code null} for none
*/
public TargetVpnGateway setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public TargetVpnGateway setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
* gateway is created.
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
* gateway is created.
* @param network network or {@code null} for none
*/
public TargetVpnGateway setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* [Output Only] URL of the region where the target VPN gateway resides. You must specify this
* field as part of the HTTP request URL. It is not settable as a field in the request body.
* @return value or {@code null} for none
*/
public java.lang.String getRegion() {
return region;
}
/**
* [Output Only] URL of the region where the target VPN gateway resides. You must specify this
* field as part of the HTTP request URL. It is not settable as a field in the request body.
* @param region region or {@code null} for none
*/
public TargetVpnGateway setRegion(java.lang.String region) {
this.region = region;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public TargetVpnGateway setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* [Output Only] The status of the VPN gateway, which can be one of the following: CREATING,
* READY, FAILED, or DELETING.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the VPN gateway, which can be one of the following: CREATING,
* READY, FAILED, or DELETING.
* @param status status or {@code null} for none
*/
public TargetVpnGateway setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* [Output Only] A list of URLs to VpnTunnel resources. VpnTunnels are created using the
* compute.vpntunnels.insert method and associated with a VPN gateway.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTunnels() {
return tunnels;
}
/**
* [Output Only] A list of URLs to VpnTunnel resources. VpnTunnels are created using the
* compute.vpntunnels.insert method and associated with a VPN gateway.
* @param tunnels tunnels or {@code null} for none
*/
public TargetVpnGateway setTunnels(java.util.List<java.lang.String> tunnels) {
this.tunnels = tunnels;
return this;
}
@Override
public TargetVpnGateway set(String fieldName, Object value) {
return (TargetVpnGateway) super.set(fieldName, value);
}
@Override
public TargetVpnGateway clone() {
return (TargetVpnGateway) super.clone();
}
}
| |
package com.laegler.swagger.generator;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import config.Config;
import config.ConfigParser;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.Codegen;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.Generator;
import io.swagger.codegen.GlobalSupportingFile;
import io.swagger.codegen.InlineModelResolver;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
import io.swagger.models.ComposedModel;
import io.swagger.models.Contact;
import io.swagger.models.Info;
import io.swagger.models.License;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.SecurityRequirement;
import io.swagger.models.Swagger;
import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.parameters.Parameter;
import io.swagger.parser.SwaggerParser;
import io.swagger.util.Json;
public class ExampleMainGenerator extends Codegen {
protected static Logger LOGGER = LoggerFactory.getLogger(ExampleMainGenerator.class);
protected ExampleServerMainCodegen config;
protected ClientOptInput opts;
protected Swagger swagger;
protected CodegenIgnoreProcessor ignoreProcessor;
@Override
public Generator opts(ClientOptInput opts) {
this.opts = opts;
this.swagger = opts.getSwagger();
this.config = (ExampleServerMainCodegen) opts.getConfig();
this.config.additionalProperties().putAll(opts.getOpts().getProperties());
ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir());
return this;
}
@Override
public List<File> generate() {
Boolean generateApis = null;
Boolean generateModels = null;
Boolean generateSupportingFiles = null;
Boolean generateApiTests = null;
Boolean generateApiIntegrationTests = null;
Boolean generateApiFeatureSteps = null;
Boolean generateApiDocumentation = null;
Boolean generateModelTests = null;
Boolean generateModelDocumentation = null;
Set<String> modelsToGenerate = null;
Set<String> apisToGenerate = null;
Set<String> supportingFilesToGenerate = null;
// allows generating only models by specifying a CSV of models to
// generate, or empty for all
if (System.getProperty("models") != null) {
String modelNames = System.getProperty("models");
generateModels = true;
if (!modelNames.isEmpty()) {
modelsToGenerate = new HashSet<String>(Arrays.asList(modelNames.split(",")));
}
}
if (System.getProperty("apis") != null) {
String apiNames = System.getProperty("apis");
generateApis = true;
if (!apiNames.isEmpty()) {
apisToGenerate = new HashSet<String>(Arrays.asList(apiNames.split(",")));
}
}
if (System.getProperty("supportingFiles") != null) {
String supportingFiles = System.getProperty("supportingFiles");
generateSupportingFiles = true;
if (!supportingFiles.isEmpty()) {
supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
}
}
if (System.getProperty("modelTests") != null) {
generateModelTests = Boolean.valueOf(System.getProperty("modelTests"));
}
if (System.getProperty("modelDocs") != null) {
generateModelDocumentation = Boolean.valueOf(System.getProperty("modelDocs"));
}
if (System.getProperty("apiTests") != null) {
generateApiTests = Boolean.valueOf(System.getProperty("apiTests"));
}
if (System.getProperty("apiIntegrationTests") != null) {
generateApiTests = Boolean.valueOf(System.getProperty("apiIntegrationTests"));
}
if (System.getProperty("apiFeatureStepsTests") != null) {
generateApiTests = Boolean.valueOf(System.getProperty("apiFeatureStepsTests"));
}
if (System.getProperty("apiDocs") != null) {
generateApiDocumentation = Boolean.valueOf(System.getProperty("apiDocs"));
}
if (generateApis == null && generateModels == null && generateSupportingFiles == null) {
// no specifics are set, generate everything
generateApis = true;
generateModels = true;
generateSupportingFiles = true;
} else {
if (generateApis == null) {
generateApis = false;
}
if (generateModels == null) {
generateModels = false;
}
if (generateSupportingFiles == null) {
generateSupportingFiles = false;
}
}
// model/api tests and documentation options rely on parent generate
// options (api or model) and no other options.
// They default to true in all scenarios and can only be marked false
// explicitly
if (generateModelTests == null) {
generateModelTests = true;
}
if (generateModelDocumentation == null) {
generateModelDocumentation = true;
}
if (generateApiTests == null) {
generateApiTests = true;
}
if (generateApiIntegrationTests == null) {
generateApiIntegrationTests = true;
}
if (generateApiFeatureSteps == null) {
generateApiFeatureSteps = true;
}
if (generateApiDocumentation == null) {
generateApiDocumentation = true;
}
// Additional properties added for tests to exclude references in
// project related files
config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests);
config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests);
if (Boolean.FALSE.equals(generateApiTests) && Boolean.FALSE.equals(generateModelTests)) {
config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE);
}
if (swagger == null || config == null) {
throw new RuntimeException("missing swagger input or config!");
}
if (System.getProperty("debugSwagger") != null) {
Json.prettyPrint(swagger);
}
List<File> files = new ArrayList<File>();
config.processOpts();
config.preprocessSwagger(swagger);
config.additionalProperties().put("generatedDate", DateTime.now().toString());
config.additionalProperties().put("generatorClass", config.getClass().toString());
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (info.getTitle() != null) {
config.additionalProperties().put("appName", config.escapeText(info.getTitle()));
}
if (info.getVersion() != null) {
config.additionalProperties().put("appVersion", config.escapeText(info.getVersion()));
}
if (StringUtils.isEmpty(info.getDescription())) {
// set a default description if none if provided
config.additionalProperties().put("appDescription",
"No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)");
} else {
config.additionalProperties().put("appDescription", config.escapeText(info.getDescription()));
}
if (info.getContact() != null) {
Contact contact = info.getContact();
config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl()));
if (contact.getEmail() != null) {
config.additionalProperties().put("infoEmail", config.escapeText(contact.getEmail()));
}
}
if (info.getLicense() != null) {
License license = info.getLicense();
if (license.getName() != null) {
config.additionalProperties().put("licenseInfo", config.escapeText(license.getName()));
}
if (license.getUrl() != null) {
config.additionalProperties().put("licenseUrl", config.escapeText(license.getUrl()));
}
}
if (info.getVersion() != null) {
config.additionalProperties().put("version", config.escapeText(info.getVersion()));
}
if (info.getTermsOfService() != null) {
config.additionalProperties().put("termsOfService", config.escapeText(info.getTermsOfService()));
}
}
if (swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());
}
StringBuilder hostBuilder = new StringBuilder();
String scheme;
if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
scheme = config.escapeText(swagger.getSchemes().get(0).toValue());
} else {
scheme = "https";
}
scheme = config.escapeText(scheme);
hostBuilder.append(scheme);
hostBuilder.append("://");
if (swagger.getHost() != null) {
hostBuilder.append(swagger.getHost());
} else {
hostBuilder.append("localhost");
}
if (swagger.getBasePath() != null) {
hostBuilder.append(swagger.getBasePath());
}
String contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath());
String basePath = config.escapeText(hostBuilder.toString());
String basePathWithoutHost = config.escapeText(swagger.getBasePath());
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(swagger);
List<Object> allOperations = new ArrayList<Object>();
List<Object> allModels = new ArrayList<Object>();
// models
final Map<String, Model> definitions = swagger.getDefinitions();
if (definitions != null) {
Set<String> modelKeys = definitions.keySet();
if (generateModels) {
if (modelsToGenerate != null && modelsToGenerate.size() > 0) {
Set<String> updatedKeys = new HashSet<String>();
for (String m : modelKeys) {
if (modelsToGenerate.contains(m)) {
updatedKeys.add(m);
}
}
modelKeys = updatedKeys;
}
// store all processed models
Map<String, Object> allProcessedModels = new TreeMap<String, Object>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Model model1 = definitions.get(o1);
Model model2 = definitions.get(o2);
int model1InheritanceDepth = getInheritanceDepth(model1);
int model2InheritanceDepth = getInheritanceDepth(model2);
if (model1InheritanceDepth == model2InheritanceDepth) {
return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2));
} else if (model1InheritanceDepth > model2InheritanceDepth) {
return 1;
} else {
return -1;
}
}
private int getInheritanceDepth(Model model) {
int inheritanceDepth = 0;
Model parent = getParent(model);
while (parent != null) {
inheritanceDepth++;
parent = getParent(parent);
}
return inheritanceDepth;
}
private Model getParent(Model model) {
if (model instanceof ComposedModel) {
Model parent = ((ComposedModel) model).getParent();
if (parent != null) {
return definitions.get(parent.getReference());
}
}
return null;
}
});
// process models only
for (String name : modelKeys) {
try {
// don't generate models that have an import mapping
if (config.importMapping().containsKey(name)) {
LOGGER.info("Model " + name + " not imported due to import mapping");
continue;
}
Model model = definitions.get(name);
Map<String, Model> modelMap = new HashMap<String, Model>();
modelMap.put(name, model);
Map<String, Object> models = processModels(config, modelMap, definitions);
models.put("classname", config.toModelName(name));
models.putAll(config.additionalProperties());
allProcessedModels.put(name, models);
} catch (Exception e) {
throw new RuntimeException("Could not process model '" + name + "'"
+ ".Please make sure that your schema is correct!", e);
}
}
// post process all processed models
allProcessedModels = config.postProcessAllModels(allProcessedModels);
// generate files based on processed models
for (String name : allProcessedModels.keySet()) {
Map<String, Object> models = (Map<String, Object>) allProcessedModels.get(name);
try {
// don't generate models that have an import mapping
if (config.importMapping().containsKey(name)) {
continue;
}
allModels.add(((List<Object>) models.get("models")).get(0));
for (String templateName : config.modelTemplateFiles().keySet()) {
String suffix = config.modelTemplateFiles().get(templateName);
String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name)
+ suffix;
if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
if (generateModelTests) {
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator
+ config.toModelTestFilename(name) + suffix;
// do not overwrite test file that already
// exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
if (generateModelDocumentation) {
// to generate model documentation files
for (String templateName : config.modelDocTemplateFiles().keySet()) {
String suffix = config.modelDocTemplateFiles().get(templateName);
String filename = config.modelDocFileFolder() + File.separator
+ config.toModelDocFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(models, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
} catch (Exception e) {
throw new RuntimeException("Could not generate model '" + name + "'", e);
}
}
}
}
if (System.getProperty("debugModels") != null) {
LOGGER.info("############ Model info ############");
Json.prettyPrint(allModels);
}
// apis
Map<String, List<ExampleCodegenOperation>> paths = processPaths2(swagger.getPaths());
if (generateApis) {
if (apisToGenerate != null && apisToGenerate.size() > 0) {
Map<String, List<ExampleCodegenOperation>> updatedPaths = new TreeMap<String, List<ExampleCodegenOperation>>();
for (String m : paths.keySet()) {
if (apisToGenerate.contains(m)) {
updatedPaths.put(m, paths.get(m));
}
}
paths = updatedPaths;
}
for (String tag : paths.keySet()) {
try {
List<ExampleCodegenOperation> ops = paths.get(tag);
Collections.sort(ops, new Comparator<ExampleCodegenOperation>() {
@Override
public int compare(ExampleCodegenOperation one, ExampleCodegenOperation another) {
return ObjectUtils.compare(one.operationId, another.operationId);
}
});
Map<String, Object> operation = processOperations2(config, tag, ops);
operation.put("basePath", basePath);
operation.put("basePathWithoutHost", basePathWithoutHost);
operation.put("contextPath", contextPath);
operation.put("baseName", tag);
operation.put("modelPackage", config.modelPackage());
operation.putAll(config.additionalProperties());
operation.put("classname", config.toApiName(tag));
operation.put("classVarName", config.toApiVarName(tag));
operation.put("importPath", config.toApiImport(tag));
if (!config.vendorExtensions().isEmpty()) {
operation.put("vendorExtensions", config.vendorExtensions());
}
// Pass sortParamsByRequiredFlag through to the Mustache
// template...
boolean sortParamsByRequiredFlag = true;
if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) {
sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties()
.get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString());
}
operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag);
processMimeTypes(swagger.getConsumes(), operation, "consumes");
processMimeTypes(swagger.getProduces(), operation, "produces");
allOperations.add(new HashMap<String, Object>(operation));
for (int i = 0; i < allOperations.size(); i++) {
Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
if (i < (allOperations.size() - 1)) {
oo.put("hasMore", "true");
}
}
for (String templateName : config.apiTemplateFiles().keySet()) {
String filename = config.apiFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
if (generateApiTests) {
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
// Rest-assured Integration Test
if (generateApiIntegrationTests) {
for (String templateName : config.apiIntegrationTestTemplateFiles.keySet()) {
String filename = config.apiIntegrationTestFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
// Cucumber Feature Steps
if (generateApiFeatureSteps) {
for (String templateName : config.apiFeatureStepsTemplateFiles.keySet()) {
String filename = config.apiFeatureStepsFilename(templateName, tag);
// do not overwrite test file that already exists
if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
if (generateApiDocumentation) {
// to generate api documentation files
for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue;
}
File written = processTemplateToFile(operation, templateName, filename);
if (written != null) {
files.add(written);
}
}
}
} catch (Exception e) {
throw new RuntimeException("Could not generate api file for '" + tag + "'", e);
}
}
}
if (System.getProperty("debugOperations") != null) {
LOGGER.info("############ Operation info ############");
Json.prettyPrint(allOperations);
}
// supporting files
Map<String, Object> bundle = new HashMap<String, Object>();
bundle.putAll(config.additionalProperties());
bundle.put("apiPackage", config.apiPackage());
Map<String, Object> apis = new HashMap<String, Object>();
apis.put("apis", allOperations);
if (swagger.getHost() != null) {
bundle.put("host", swagger.getHost());
}
bundle.put("swagger", this.swagger);
bundle.put("basePath", basePath);
bundle.put("basePathWithoutHost", basePathWithoutHost);
bundle.put("scheme", scheme);
bundle.put("contextPath", contextPath);
bundle.put("apiInfo", apis);
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
List<CodegenSecurity> authMethods = config.fromSecurity(swagger.getSecurityDefinitions());
if (authMethods != null && !authMethods.isEmpty()) {
bundle.put("authMethods", authMethods);
bundle.put("hasAuthMethods", true);
}
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
}
for (int i = 0; i < allModels.size() - 1; i++) {
HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
CodegenModel m = cm.get("model");
m.hasMoreModels = true;
}
config.postProcessSupportingFileData(bundle);
if (System.getProperty("debugSupportingFiles") != null) {
LOGGER.info("############ Supporting file info ############");
Json.prettyPrint(bundle);
}
if (generateSupportingFiles) {
for (SupportingFile support : config.supportingFiles()) {
try {
String outputFolder = config.outputFolder();
if (StringUtils.isNotEmpty(support.folder)) {
outputFolder += File.separator + support.folder;
}
File of = new File(outputFolder);
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = outputFolder + File.separator + support.destinationFilename;
if (!config.shouldOverwrite(outputFilename)) {
LOGGER.info("Skipped overwriting " + outputFilename);
continue;
}
String templateFile;
if (support instanceof GlobalSupportingFile) {
templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile;
} else {
templateFile = getFullTemplateFile(config, support.templateFile);
}
boolean shouldGenerate = true;
if (supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) {
if (supportingFilesToGenerate.contains(support.destinationFilename)) {
shouldGenerate = true;
} else {
shouldGenerate = false;
}
}
if (shouldGenerate) {
if (ignoreProcessor.allowsFile(new File(outputFilename))) {
if (templateFile.endsWith("mustache")) {
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler().withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
}).defaultValue("").compile(template);
writeToFile(outputFilename, tmpl.execute(bundle));
files.add(new File(outputFilename));
} else {
InputStream in = null;
try {
in = new FileInputStream(templateFile);
} catch (Exception e) {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader()
.getResourceAsStream(getCPResourcePath(templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null) {
LOGGER.info("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
if (in == null) {
LOGGER.error("can't open " + templateFile + " for input");
}
}
files.add(outputFile);
}
} else {
LOGGER.info("Skipped generation of " + outputFilename
+ " due to rule in .swagger-codegen-ignore");
}
}
} catch (Exception e) {
throw new RuntimeException("Could not generate supporting file '" + support + "'", e);
}
}
// Consider .swagger-codegen-ignore a supporting file
// Output .swagger-codegen-ignore if it doesn't exist and wasn't
// explicitly created by a generator
final String swaggerCodegenIgnore = ".swagger-codegen-ignore";
String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore;
File ignoreFile = new File(ignoreFileNameTarget);
if (!ignoreFile.exists()) {
String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator
+ swaggerCodegenIgnore;
String ignoreFileContents = readResourceContents(ignoreFileNameSource);
try {
writeToFile(ignoreFileNameTarget, ignoreFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e);
}
files.add(ignoreFile);
}
// Add default LICENSE (Apache-2.0) for all generators
final String apache2License = "LICENSE";
String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License;
File licenseFile = new File(licenseFileNameTarget);
String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator
+ apache2License;
String licenseFileContents = readResourceContents(licenseFileNameSource);
try {
writeToFile(licenseFileNameTarget, licenseFileContents);
} catch (IOException e) {
throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e);
}
files.add(licenseFile);
}
config.processSwagger(swagger);
return files;
}
private File processTemplateToFile(Map<String, Object> templateData, String templateName, String outputFilename)
throws IOException {
if (ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) {
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler().withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
}).defaultValue("").compile(template);
writeToFile(outputFilename, tmpl.execute(templateData));
return new File(outputFilename);
}
LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore");
return null;
}
private static void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
if (mimeTypeList != null && mimeTypeList.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
for (String key : mimeTypeList) {
Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key);
count += 1;
if (count < mimeTypeList.size()) {
mediaType.put("hasMore", "true");
} else {
mediaType.put("hasMore", null);
}
c.add(mediaType);
}
operation.put(source, c);
String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1);
operation.put(flagFieldName, true);
}
}
public Map<String, List<ExampleCodegenOperation>> processPaths2(Map<String, Path> paths) {
Map<String, List<ExampleCodegenOperation>> ops = new TreeMap<String, List<ExampleCodegenOperation>>();
for (String resourcePath : paths.keySet()) {
Path path = paths.get(resourcePath);
processOperation2(resourcePath, "get", path.getGet(), ops, path);
processOperation2(resourcePath, "head", path.getHead(), ops, path);
processOperation2(resourcePath, "put", path.getPut(), ops, path);
processOperation2(resourcePath, "post", path.getPost(), ops, path);
processOperation2(resourcePath, "delete", path.getDelete(), ops, path);
processOperation2(resourcePath, "patch", path.getPatch(), ops, path);
processOperation2(resourcePath, "options", path.getOptions(), ops, path);
}
return ops;
}
@Override
public SecuritySchemeDefinition fromSecurity(String name) {
Map<String, SecuritySchemeDefinition> map = swagger.getSecurityDefinitions();
if (map == null) {
return null;
}
return map.get(name);
}
public void processOperation2(String resourcePath, String httpMethod, Operation operation,
Map<String, List<ExampleCodegenOperation>> operations, Path path) {
if (operation != null) {
if (System.getProperty("debugOperations") != null) {
LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation
+ "\n");
}
List<String> tags = operation.getTags();
if (tags == null) {
tags = new ArrayList<String>();
tags.add("default");
}
/*
* build up a set of parameter "ids" defined at the operation level
* per the swagger 2.0 spec
* "A unique parameter is defined by a combination of a name and location"
* i'm assuming "location" == "in"
*/
Set<String> operationParameters = new HashSet<String>();
if (operation.getParameters() != null) {
for (Parameter parameter : operation.getParameters()) {
operationParameters.add(generateParameterId(parameter));
}
}
// need to propagate path level down to the operation
if (path.getParameters() != null) {
for (Parameter parameter : path.getParameters()) {
// skip propagation if a parameter with the same name is
// already defined at the operation level
if (!operationParameters.contains(generateParameterId(parameter))) {
operation.addParameter(parameter);
}
}
}
for (String tag : tags) {
ExampleCodegenOperation co = null;
try {
co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger);
co.tags = new ArrayList<String>();
co.tags.add(config.sanitizeTag(tag));
config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, co, operations);
List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null && swagger.getSecurity() != null) {
securities = new ArrayList<Map<String, List<String>>>();
for (SecurityRequirement sr : swagger.getSecurity()) {
securities.add(sr.getRequirements());
}
}
if (securities == null || securities.isEmpty()) {
continue;
}
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
for (Map<String, List<String>> security : securities) {
for (String securityName : security.keySet()) {
SecuritySchemeDefinition securityDefinition = fromSecurity(securityName);
if (securityDefinition != null) {
if (securityDefinition instanceof OAuth2Definition) {
OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition;
OAuth2Definition oauth2Operation = new OAuth2Definition();
oauth2Operation.setType(oauth2Definition.getType());
oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl());
oauth2Operation.setFlow(oauth2Definition.getFlow());
oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
oauth2Operation.setScopes(new HashMap<String, String>());
for (String scope : security.get(securityName)) {
if (oauth2Definition.getScopes().containsKey(scope)) {
oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
}
}
authMethods.put(securityName, oauth2Operation);
} else {
authMethods.put(securityName, securityDefinition);
}
}
}
}
if (!authMethods.isEmpty()) {
co.authMethods = config.fromSecurity(authMethods);
co.hasAuthMethods = true;
}
} catch (Exception ex) {
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
+ " Operation: " + operation.getOperationId() + "\n" //
+ " Resource: " + httpMethod + " " + resourcePath + "\n"//
+ " Definitions: " + swagger.getDefinitions() + "\n" //
+ " Exception: " + ex.getMessage();
throw new RuntimeException(msg, ex);
}
}
}
}
private static String generateParameterId(Parameter parameter) {
return parameter.getName() + ":" + parameter.getIn();
}
@SuppressWarnings("static-method")
public Map<String, Object> processOperations2(CodegenConfig config, String tag, List<ExampleCodegenOperation> ops) {
Map<String, Object> operations = new HashMap<String, Object>();
Map<String, Object> objs = new HashMap<String, Object>();
objs.put("classname", config.toApiName(tag));
objs.put("pathPrefix", config.toApiVarName(tag));
// check for operationId uniqueness
Set<String> opIds = new HashSet<String>();
int counter = 0;
for (ExampleCodegenOperation op : ops) {
String opId = op.nickname;
if (opIds.contains(opId)) {
counter++;
op.nickname += "_" + counter;
}
opIds.add(opId);
}
objs.put("operation", ops);
operations.put("operations", objs);
operations.put("package", config.apiPackage());
Set<String> allImports = new LinkedHashSet<String>();
for (ExampleCodegenOperation op : ops) {
allImports.addAll(op.imports);
}
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String nextImport : allImports) {
Map<String, String> im = new LinkedHashMap<String, String>();
String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);
}
if (mapping != null) {
im.put("import", mapping);
imports.add(im);
}
}
operations.put("imports", imports);
// add a flag to indicate whether there's any {{import}}
if (imports.size() > 0) {
operations.put("hasImport", true);
}
config.postProcessOperations(operations);
if (objs.size() > 0) {
List<ExampleCodegenOperation> os = (List<ExampleCodegenOperation>) objs.get("operation");
if (os != null && os.size() > 0) {
ExampleCodegenOperation op = os.get(os.size() - 1);
op.hasMore = null;
}
}
return operations;
}
@Override
@SuppressWarnings("static-method")
public Map<String, Object> processModels(CodegenConfig config, Map<String, Model> definitions,
Map<String, Model> allDefinitions) {
Map<String, Object> objs = new HashMap<String, Object>();
objs.put("package", config.modelPackage());
List<Object> models = new ArrayList<Object>();
Set<String> allImports = new LinkedHashSet<String>();
for (String key : definitions.keySet()) {
Model mm = definitions.get(key);
CodegenModel cm = config.fromModel(key, mm, allDefinitions);
Map<String, Object> mo = new HashMap<String, Object>();
mo.put("model", cm);
mo.put("importPath", config.toModelImport(cm.classname));
models.add(mo);
allImports.addAll(cm.imports);
}
objs.put("models", models);
Set<String> importSet = new TreeSet<String>();
for (String nextImport : allImports) {
String mapping = config.importMapping().get(nextImport);
if (mapping == null) {
mapping = config.toModelImport(nextImport);
}
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
importSet.add(mapping);
}
// add instantiation types
mapping = config.instantiationTypes().get(nextImport);
if (mapping != null && !config.defaultIncludes().contains(mapping)) {
importSet.add(mapping);
}
}
List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
for (String s : importSet) {
Map<String, String> item = new HashMap<String, String>();
item.put("import", s);
imports.add(item);
}
objs.put("imports", imports);
config.postProcessModels(objs);
return objs;
}
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:"
+ "\n -DdebugSwagger prints the swagger specification as interpreted by the codegen"
+ "\n -DdebugModels prints models passed to the template engine"
+ "\n -DdebugOperations prints operations passed to the template engine"
+ "\n -DdebugSupportingFiles prints additional data passed to the template engine";
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Options options = new Options();
options.addOption("h", "help", false, "shows this message");
options.addOption("l", "lang", true,
"client language to generate.\nAvailable languages include:\n\t[" + configString + "]");
options.addOption("o", "output", true, "where to write the generated files");
options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file");
options.addOption("t", "template-dir", true, "folder containing the template files");
options.addOption("d", "debug-info", false, "prints additional info for debugging");
options.addOption("a", "auth", true,
"adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values");
options.addOption("c", "config", true, "location of the configuration file");
ClientOptInput clientOptInput = new ClientOptInput();
ClientOpts clientOpts = new ClientOpts();
Swagger swagger = null;
CommandLine cmd = null;
try {
CommandLineParser parser = new BasicParser();
CodegenConfig config = null;
cmd = parser.parse(options, args);
if (cmd.hasOption("d")) {
usage(options);
System.out.println(debugInfoOptions);
return;
}
if (cmd.hasOption("a")) {
clientOptInput.setAuth(cmd.getOptionValue("a"));
}
if (cmd.hasOption("l")) {
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
} else {
usage(options);
return;
}
if (cmd.hasOption("o")) {
clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
}
if (cmd.hasOption("h")) {
if (cmd.hasOption("l")) {
config = getConfig(String.valueOf(cmd.getOptionValue("l")));
if (config != null) {
options.addOption("h", "help", true, config.getHelp());
usage(options);
return;
}
}
usage(options);
return;
}
if (cmd.hasOption("i")) {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(),
true);
}
if (cmd.hasOption("c")) {
String configFile = cmd.getOptionValue("c");
Config genConfig = ConfigParser.read(configFile);
config = clientOptInput.getConfig();
if (null != genConfig && null != config) {
for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(),
genConfig.getOption(langCliOption.getOpt()));
}
}
}
}
if (cmd.hasOption("t")) {
clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, String.valueOf(cmd.getOptionValue("t")));
}
} catch (Exception e) {
usage(options);
return;
}
try {
clientOptInput.opts(clientOpts).swagger(swagger);
new Codegen().opts(clientOptInput).generate();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
public static List<CodegenConfig> getExtensions() {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator();
while (itr.hasNext()) {
output.add(itr.next());
}
return output;
}
static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Codegen", options);
}
public static CodegenConfig getConfig(String name) {
if (configs.containsKey(name)) {
return configs.get(name);
} else {
// see if it's a class
try {
LOGGER.debug("loading class " + name);
Class<?> customClass = Class.forName(name);
LOGGER.debug("loaded");
return (CodegenConfig) customClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("can't load class " + name);
}
}
}
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for (CodegenConfig config : extensions) {
if (sb.toString().length() != 0) {
sb.append(", ");
}
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
}
| |
/*
*
* * Copyright 2016 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.
*
*/
package uk.ac.ebi.eva.vcfdump;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeBuilder;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.VariantSource;
import org.opencb.biodata.models.variant.VariantSourceEntry;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class BiodataVariantToVariantContextConverter {
public static final String GENOTYPE_KEY = "GT";
private final VariantContextBuilder variantContextBuilder;
private List<VariantSource> sources;
private Set<String> studies;
private Map<String, Map<String, String>> filesSampleNamesEquivalences;
private static final int NO_CALL_ALLELE_INDEX = 2;
protected static final Pattern genotypePattern = Pattern.compile("/|\\|");
public BiodataVariantToVariantContextConverter(List<VariantSource> sources,
Map<String, Map<String, String>> filesSampleNamesEquivalences) {
this.sources = sources;
if (sources != null) {
this.studies = sources.stream().map(VariantSource::getStudyId).collect(Collectors.toSet());
}
this.filesSampleNamesEquivalences = filesSampleNamesEquivalences;
variantContextBuilder = new VariantContextBuilder();
}
public VariantContext transform(Variant variant) {
String[] allelesArray = getAllelesArray(variant);
Set<Genotype> genotypes = getGenotypes(variant, allelesArray);
VariantContext variantContext = variantContextBuilder
.chr(variant.getChromosome())
.start(variant.getStart())
.stop(getVariantContextStop(variant))
.noID()
.alleles(allelesArray)
.unfiltered()
.genotypes(genotypes).make();
return variantContext;
}
private String[] getAllelesArray(Variant variant) {
String[] allelesArray;
// if there are indels, we cannot use the normalized alleles (hts forbids empty alleles), so we have to extract a context allele
// from the VCF source line, add it to the variant and update the variant coordinates
if (variant.getReference().isEmpty() || variant.getAlternate().isEmpty()) {
variant = updateVariantAddingContextNucleotideFromSourceLine(variant);
}
allelesArray = new String[]{variant.getReference(), variant.getAlternate()};
return allelesArray;
}
private Variant updateVariantAddingContextNucleotideFromSourceLine(Variant variant) {
// get the original VCF line for the variant from the 'files.src' field
List<VariantSourceEntry> studiesEntries =
variant.getSourceEntries().values().stream().filter(s -> studies.contains(s.getStudyId()))
.collect(Collectors.toList());
Optional<String> srcLine = studiesEntries.stream().filter(s -> s.getAttribute("src") != null).findAny()
.map(s -> s.getAttribute("src"));
if (!srcLine.isPresent()) {
String prefix = studiesEntries.size() == 1 ? "study " : "studies ";
String studies = studiesEntries.stream().map(s -> s.getStudyId())
.collect(Collectors.joining(",", prefix, "."));
throw new NoSuchElementException("Source line not present for " + studies);
}
String[] srcLineFields = srcLine.get().split("\t", 5);
// get the relative position of the context nucleotide in the source line REF string
int positionInSrcLine = Integer.parseInt(srcLineFields[1]);
// the context nucleotide is generally the one preceding the variant
boolean prependContextNucleotideToVariant = true;
int relativePositionOfContextNucleotide = variant.getStart() - 1 - positionInSrcLine;
// if there is no preceding nucleotide in the source line, the context nucleotide will be "after" the variant
if (relativePositionOfContextNucleotide < 0) {
relativePositionOfContextNucleotide = variant.getStart() + variant.getReference()
.length() - positionInSrcLine;
prependContextNucleotideToVariant = false;
}
// get context nucleotide and add it to the variant
String contextNucleotide = getContextNucleotideFromSourceLine(srcLineFields,
relativePositionOfContextNucleotide);
variant = addContextNucleotideToVariant(variant, contextNucleotide, prependContextNucleotideToVariant);
return variant;
}
private String getContextNucleotideFromSourceLine(String[] srcLineFields, int relativePositionOfContextNucleotide) {
String referenceInSrcLine = srcLineFields[3];
return referenceInSrcLine
.substring(relativePositionOfContextNucleotide, relativePositionOfContextNucleotide + 1);
}
private Variant addContextNucleotideToVariant(Variant variant, String contextNucleotide,
boolean prependContextNucleotideToVariant) {
// prepend or append the context nucleotide to the reference and alternate alleles
if (prependContextNucleotideToVariant) {
variant.setReference(contextNucleotide + variant.getReference());
variant.setAlternate(contextNucleotide + variant.getAlternate());
// update variant start
variant.setStart(variant.getStart() - 1);
} else {
variant.setReference(variant.getReference() + contextNucleotide);
variant.setAlternate(variant.getAlternate() + contextNucleotide);
// update variant end
variant.setEnd(variant.getEnd() + 1);
}
return variant;
}
private Set<Genotype> getGenotypes(Variant variant, String[] allelesArray) {
Set<Genotype> genotypes = new HashSet<>();
Allele[] variantAlleles =
{Allele.create(allelesArray[0], true), Allele.create(allelesArray[1]), Allele.create(Allele.NO_CALL,
false)};
for (VariantSource source : sources) {
List<VariantSourceEntry> variantStudyEntries =
variant.getSourceEntries().values().stream().filter(s -> s.getStudyId().equals(source.getStudyId()))
.collect(Collectors.toList());
for (VariantSourceEntry variantStudyEntry : variantStudyEntries) {
genotypes = getStudyGenotypes(genotypes, variantAlleles, variantStudyEntry);
}
}
return genotypes;
}
private Set<Genotype> getStudyGenotypes(Set<Genotype> genotypes, Allele[] variantAlleles,
VariantSourceEntry variantStudyEntry) {
for (Map.Entry<String, Map<String, String>> sampleEntry : variantStudyEntry.getSamplesData().entrySet()) {
String sampleGenotypeString = sampleEntry.getValue().get(GENOTYPE_KEY);
Genotype sampleGenotype =
parseSampleGenotype(variantAlleles, variantStudyEntry.getFileId(), sampleEntry.getKey(),
sampleGenotypeString);
genotypes.add(sampleGenotype);
}
return genotypes;
}
private Genotype parseSampleGenotype(Allele[] variantAlleles, String fileId, String sampleName,
String sampleGenotypeString) {
String[] alleles = genotypePattern.split(sampleGenotypeString, -1);
boolean isPhased = sampleGenotypeString.contains("|");
List<Allele> genotypeAlleles = new ArrayList<>(2);
for (String allele : alleles) {
int index;
if (allele.equals(".")) {
index = -1;
} else {
index = Integer.valueOf(allele);
}
// every allele not 0 or 1 will be considered no call
if (index == -1 || index > NO_CALL_ALLELE_INDEX) {
index = NO_CALL_ALLELE_INDEX;
}
genotypeAlleles.add(variantAlleles[index]);
}
GenotypeBuilder builder = new GenotypeBuilder()
.name(getFixedSampleName(fileId, sampleName))
.phased(isPhased)
.alleles(genotypeAlleles);
return builder.make();
}
private String getFixedSampleName(String fileId, String sampleName) {
// this method returns the "studyId appended" sample name if there are sample name conflicts
if (filesSampleNamesEquivalences != null) {
return filesSampleNamesEquivalences.get(fileId).get(sampleName);
} else {
return sampleName;
}
}
private long getVariantContextStop(Variant variant) {
return variant.getStart() + variant.getReference().length() - 1;
}
}
| |
/*
* Xero Projects API
* This is the Xero Projects API
*
* Contact: api@xero.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.xero.models.project;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
import java.util.UUID;
import org.threeten.bp.OffsetDateTime;
/** TimeEntry */
public class TimeEntry {
StringUtil util = new StringUtil();
@JsonProperty("timeEntryId")
private UUID timeEntryId;
@JsonProperty("userId")
private UUID userId;
@JsonProperty("projectId")
private UUID projectId;
@JsonProperty("taskId")
private UUID taskId;
@JsonProperty("dateUtc")
private OffsetDateTime dateUtc;
@JsonProperty("dateEnteredUtc")
private OffsetDateTime dateEnteredUtc;
@JsonProperty("duration")
private Integer duration;
@JsonProperty("description")
private String description;
/**
* Status of the time entry. By default a time entry is created with status of `ACTIVE`.
* A `LOCKED` state indicates that the time entry is currently changing state (for
* example being invoiced). Updates are not allowed when in this state. It will have a status of
* INVOICED once it is invoiced.
*/
public enum StatusEnum {
/** ACTIVE */
ACTIVE("ACTIVE"),
/** LOCKED */
LOCKED("LOCKED"),
/** INVOICED */
INVOICED("INVOICED");
private String value;
StatusEnum(String value) {
this.value = value;
}
/**
* getValue
*
* @return String value
*/
@JsonValue
public String getValue() {
return value;
}
/**
* toString
*
* @return String value
*/
@Override
public String toString() {
return String.valueOf(value);
}
/**
* fromValue
*
* @param value String
*/
@JsonCreator
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
@JsonProperty("status")
private StatusEnum status;
/**
* Identifier of the time entry.
*
* @param timeEntryId UUID
* @return TimeEntry
*/
public TimeEntry timeEntryId(UUID timeEntryId) {
this.timeEntryId = timeEntryId;
return this;
}
/**
* Identifier of the time entry.
*
* @return timeEntryId
*/
@ApiModelProperty(
example = "00000000-0000-0000-0000-000000000000",
value = "Identifier of the time entry.")
/**
* Identifier of the time entry.
*
* @return timeEntryId UUID
*/
public UUID getTimeEntryId() {
return timeEntryId;
}
/**
* Identifier of the time entry.
*
* @param timeEntryId UUID
*/
public void setTimeEntryId(UUID timeEntryId) {
this.timeEntryId = timeEntryId;
}
/**
* The xero user identifier of the person who logged time.
*
* @param userId UUID
* @return TimeEntry
*/
public TimeEntry userId(UUID userId) {
this.userId = userId;
return this;
}
/**
* The xero user identifier of the person who logged time.
*
* @return userId
*/
@ApiModelProperty(
example = "00000000-0000-0000-0000-000000000000",
value = "The xero user identifier of the person who logged time.")
/**
* The xero user identifier of the person who logged time.
*
* @return userId UUID
*/
public UUID getUserId() {
return userId;
}
/**
* The xero user identifier of the person who logged time.
*
* @param userId UUID
*/
public void setUserId(UUID userId) {
this.userId = userId;
}
/**
* Identifier of the project, that the task (which the time entry is logged against) belongs to.
*
* @param projectId UUID
* @return TimeEntry
*/
public TimeEntry projectId(UUID projectId) {
this.projectId = projectId;
return this;
}
/**
* Identifier of the project, that the task (which the time entry is logged against) belongs to.
*
* @return projectId
*/
@ApiModelProperty(
example = "00000000-0000-0000-0000-000000000000",
value =
"Identifier of the project, that the task (which the time entry is logged against)"
+ " belongs to.")
/**
* Identifier of the project, that the task (which the time entry is logged against) belongs to.
*
* @return projectId UUID
*/
public UUID getProjectId() {
return projectId;
}
/**
* Identifier of the project, that the task (which the time entry is logged against) belongs to.
*
* @param projectId UUID
*/
public void setProjectId(UUID projectId) {
this.projectId = projectId;
}
/**
* Identifier of the task that time entry is logged against.
*
* @param taskId UUID
* @return TimeEntry
*/
public TimeEntry taskId(UUID taskId) {
this.taskId = taskId;
return this;
}
/**
* Identifier of the task that time entry is logged against.
*
* @return taskId
*/
@ApiModelProperty(
example = "00000000-0000-0000-0000-000000000000",
value = "Identifier of the task that time entry is logged against.")
/**
* Identifier of the task that time entry is logged against.
*
* @return taskId UUID
*/
public UUID getTaskId() {
return taskId;
}
/**
* Identifier of the task that time entry is logged against.
*
* @param taskId UUID
*/
public void setTaskId(UUID taskId) {
this.taskId = taskId;
}
/**
* The date time that time entry is logged on. UTC Date Time in ISO-8601 format.
*
* @param dateUtc OffsetDateTime
* @return TimeEntry
*/
public TimeEntry dateUtc(OffsetDateTime dateUtc) {
this.dateUtc = dateUtc;
return this;
}
/**
* The date time that time entry is logged on. UTC Date Time in ISO-8601 format.
*
* @return dateUtc
*/
@ApiModelProperty(
value = "The date time that time entry is logged on. UTC Date Time in ISO-8601 format.")
/**
* The date time that time entry is logged on. UTC Date Time in ISO-8601 format.
*
* @return dateUtc OffsetDateTime
*/
public OffsetDateTime getDateUtc() {
return dateUtc;
}
/**
* The date time that time entry is logged on. UTC Date Time in ISO-8601 format.
*
* @param dateUtc OffsetDateTime
*/
public void setDateUtc(OffsetDateTime dateUtc) {
this.dateUtc = dateUtc;
}
/**
* The date time that time entry is created. UTC Date Time in ISO-8601 format. By default it is
* set to server time.
*
* @param dateEnteredUtc OffsetDateTime
* @return TimeEntry
*/
public TimeEntry dateEnteredUtc(OffsetDateTime dateEnteredUtc) {
this.dateEnteredUtc = dateEnteredUtc;
return this;
}
/**
* The date time that time entry is created. UTC Date Time in ISO-8601 format. By default it is
* set to server time.
*
* @return dateEnteredUtc
*/
@ApiModelProperty(
value =
"The date time that time entry is created. UTC Date Time in ISO-8601 format. By default"
+ " it is set to server time.")
/**
* The date time that time entry is created. UTC Date Time in ISO-8601 format. By default it is
* set to server time.
*
* @return dateEnteredUtc OffsetDateTime
*/
public OffsetDateTime getDateEnteredUtc() {
return dateEnteredUtc;
}
/**
* The date time that time entry is created. UTC Date Time in ISO-8601 format. By default it is
* set to server time.
*
* @param dateEnteredUtc OffsetDateTime
*/
public void setDateEnteredUtc(OffsetDateTime dateEnteredUtc) {
this.dateEnteredUtc = dateEnteredUtc;
}
/**
* The duration of logged minutes.
*
* @param duration Integer
* @return TimeEntry
*/
public TimeEntry duration(Integer duration) {
this.duration = duration;
return this;
}
/**
* The duration of logged minutes.
*
* @return duration
*/
@ApiModelProperty(value = "The duration of logged minutes.")
/**
* The duration of logged minutes.
*
* @return duration Integer
*/
public Integer getDuration() {
return duration;
}
/**
* The duration of logged minutes.
*
* @param duration Integer
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
* A description of the time entry.
*
* @param description String
* @return TimeEntry
*/
public TimeEntry description(String description) {
this.description = description;
return this;
}
/**
* A description of the time entry.
*
* @return description
*/
@ApiModelProperty(value = "A description of the time entry.")
/**
* A description of the time entry.
*
* @return description String
*/
public String getDescription() {
return description;
}
/**
* A description of the time entry.
*
* @param description String
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Status of the time entry. By default a time entry is created with status of `ACTIVE`.
* A `LOCKED` state indicates that the time entry is currently changing state (for
* example being invoiced). Updates are not allowed when in this state. It will have a status of
* INVOICED once it is invoiced.
*
* @param status StatusEnum
* @return TimeEntry
*/
public TimeEntry status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Status of the time entry. By default a time entry is created with status of `ACTIVE`.
* A `LOCKED` state indicates that the time entry is currently changing state (for
* example being invoiced). Updates are not allowed when in this state. It will have a status of
* INVOICED once it is invoiced.
*
* @return status
*/
@ApiModelProperty(
value =
"Status of the time entry. By default a time entry is created with status of `ACTIVE`. A"
+ " `LOCKED` state indicates that the time entry is currently changing state (for"
+ " example being invoiced). Updates are not allowed when in this state. It will"
+ " have a status of INVOICED once it is invoiced.")
/**
* Status of the time entry. By default a time entry is created with status of `ACTIVE`.
* A `LOCKED` state indicates that the time entry is currently changing state (for
* example being invoiced). Updates are not allowed when in this state. It will have a status of
* INVOICED once it is invoiced.
*
* @return status StatusEnum
*/
public StatusEnum getStatus() {
return status;
}
/**
* Status of the time entry. By default a time entry is created with status of `ACTIVE`.
* A `LOCKED` state indicates that the time entry is currently changing state (for
* example being invoiced). Updates are not allowed when in this state. It will have a status of
* INVOICED once it is invoiced.
*
* @param status StatusEnum
*/
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimeEntry timeEntry = (TimeEntry) o;
return Objects.equals(this.timeEntryId, timeEntry.timeEntryId)
&& Objects.equals(this.userId, timeEntry.userId)
&& Objects.equals(this.projectId, timeEntry.projectId)
&& Objects.equals(this.taskId, timeEntry.taskId)
&& Objects.equals(this.dateUtc, timeEntry.dateUtc)
&& Objects.equals(this.dateEnteredUtc, timeEntry.dateEnteredUtc)
&& Objects.equals(this.duration, timeEntry.duration)
&& Objects.equals(this.description, timeEntry.description)
&& Objects.equals(this.status, timeEntry.status);
}
@Override
public int hashCode() {
return Objects.hash(
timeEntryId,
userId,
projectId,
taskId,
dateUtc,
dateEnteredUtc,
duration,
description,
status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TimeEntry {\n");
sb.append(" timeEntryId: ").append(toIndentedString(timeEntryId)).append("\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append(" projectId: ").append(toIndentedString(projectId)).append("\n");
sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n");
sb.append(" dateUtc: ").append(toIndentedString(dateUtc)).append("\n");
sb.append(" dateEnteredUtc: ").append(toIndentedString(dateEnteredUtc)).append("\n");
sb.append(" duration: ").append(toIndentedString(duration)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| |
package org.hisp.dhis.webapi.controller;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.render.RenderService;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.userkeyjsonvalue.UserKeyJsonValue;
import org.hisp.dhis.userkeyjsonvalue.UserKeyJsonValueService;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.hisp.dhis.webapi.service.WebMessageService;
import org.hisp.dhis.dxf2.webmessage.WebMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* @author Stian Sandvold
*/
@Controller
@RequestMapping( "/userDataStore" )
@ApiVersion( { ApiVersion.Version.DEFAULT, ApiVersion.Version.ALL } )
public class UserKeyJsonValueController
{
@Autowired
private UserKeyJsonValueService userKeyJsonValueService;
@Autowired
private RenderService renderService;
@Autowired
private WebMessageService messageService;
@Autowired
private CurrentUserService currentUserService;
/**
* Returns a JSON array of strings representing the different namespaces used.
* If no namespaces exist, an empty array is returned.
*/
@RequestMapping( value = "", method = RequestMethod.GET, produces = "application/json" )
public @ResponseBody List<String> getNamespaces( HttpServletResponse response )
throws IOException
{
return userKeyJsonValueService.getNamespacesByUser( currentUserService.getCurrentUser() );
}
/**
* Returns a JSON array of strings representing the different keys used in a given namespace.
* If no namespaces exist, an empty array is returned.
*/
@RequestMapping( value = "/{namespace}", method = RequestMethod.GET, produces = "application/json" )
public @ResponseBody List<String> getKeys( @PathVariable String namespace, HttpServletResponse response )
throws IOException
{
return userKeyJsonValueService.getKeysByUserAndNamespace( currentUserService.getCurrentUser(), namespace );
}
/**
* Deletes all keys with the given user and namespace.
*/
@RequestMapping( value = "/{namespace}", method = RequestMethod.DELETE )
public void deleteKeys(
@PathVariable String namespace,
HttpServletResponse response )
throws WebMessageException
{
userKeyJsonValueService.deleteNamespaceFromUser( currentUserService.getCurrentUser(), namespace );
messageService.sendJson( WebMessageUtils.ok( "All keys from namespace '" + namespace + "' deleted." ), response );
}
/**
* Retrieves the value of the KeyJsonValue represented by the given key and namespace from
* the current user.
*/
@RequestMapping( value = "/{namespace}/{key}", method = RequestMethod.GET, produces = "application/json" )
public @ResponseBody String getUserKeyJsonValue(
@PathVariable String namespace,
@PathVariable String key )
throws IOException, WebMessageException
{
UserKeyJsonValue userKeyJsonValue = userKeyJsonValueService.getUserKeyJsonValue(
currentUserService.getCurrentUser(), namespace, key );
if ( userKeyJsonValue == null )
{
throw new WebMessageException( WebMessageUtils
.notFound( "The key '" + key + "' was not found in the namespace '" + namespace + "'." ) );
}
return userKeyJsonValue.getValue();
}
/**
* Creates a new KeyJsonValue Object on the current user with the key, namespace and value supplied.
*/
@RequestMapping( value = "/{namespace}/{key}", method = RequestMethod.POST, produces = "application/json", consumes = "application/json" )
public void addUserKeyJsonValue(
@PathVariable String namespace,
@PathVariable String key,
@RequestBody String body,
@RequestParam( defaultValue = "false" ) boolean encrypt,
HttpServletResponse response )
throws IOException, WebMessageException
{
if ( userKeyJsonValueService.getUserKeyJsonValue( currentUserService.getCurrentUser(), namespace, key ) !=
null )
{
throw new WebMessageException( WebMessageUtils
.conflict( "The key '" + key + "' already exists in the namespace '" + namespace + "'." ) );
}
if ( !renderService.isValidJson( body ) )
{
throw new WebMessageException( WebMessageUtils.badRequest( "The data is not valid JSON." ) );
}
UserKeyJsonValue userKeyJsonValue = new UserKeyJsonValue();
userKeyJsonValue.setKey( key );
userKeyJsonValue.setUser( currentUserService.getCurrentUser() );
userKeyJsonValue.setNamespace( namespace );
userKeyJsonValue.setValue( body );
userKeyJsonValue.setEncrypted( encrypt );
userKeyJsonValueService.addUserKeyJsonValue( userKeyJsonValue );
response.setStatus( HttpServletResponse.SC_CREATED );
messageService.sendJson( WebMessageUtils.created( "Key '" + key + "' in namespace '" + namespace + "' created." ), response );
}
/**
* Update a key.
*/
@RequestMapping( value = "/{namespace}/{key}", method = RequestMethod.PUT, produces = "application/json", consumes = "application/json" )
public void updateUserKeyJsonValue(
@PathVariable String namespace,
@PathVariable String key,
@RequestBody String body,
HttpServletResponse response )
throws WebMessageException, IOException
{
UserKeyJsonValue userKeyJsonValue = userKeyJsonValueService.getUserKeyJsonValue(
currentUserService.getCurrentUser(), namespace, key );
if ( userKeyJsonValue == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "The key '" + key + "' was not found in the namespace '" + namespace + "'." ) );
}
if ( !renderService.isValidJson( body ) )
{
throw new WebMessageException( WebMessageUtils.badRequest( "The data is not valid JSON." ) );
}
userKeyJsonValue.setValue( body );
userKeyJsonValueService.updateUserKeyJsonValue( userKeyJsonValue );
response.setStatus( HttpServletResponse.SC_OK );
messageService.sendJson( WebMessageUtils.created( "Key '" + key + "' in namespace '" + namespace + "' updated." ), response );
}
/**
* Delete a key.
*/
@RequestMapping( value = "/{namespace}/{key}", method = RequestMethod.DELETE, produces = "application/json" )
public void deleteUserKeyJsonValue(
@PathVariable String namespace,
@PathVariable String key,
HttpServletResponse response )
throws WebMessageException
{
UserKeyJsonValue userKeyJsonValue = userKeyJsonValueService.getUserKeyJsonValue(
currentUserService.getCurrentUser(), namespace, key );
if ( userKeyJsonValue == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "The key '" + key + "' was not found in the namespace '" + namespace + "'." ) );
}
userKeyJsonValueService.deleteUserKeyJsonValue( userKeyJsonValue );
messageService.sendJson( WebMessageUtils.ok( "Key '" + key + "' deleted from the namespace '" + namespace + "'." ), response );
}
}
| |
/*
* Copyright (c) 2014.
* Main Method Incorporated.
*/
package com.mainmethod.premofm.ui.activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.mainmethod.premofm.R;
import com.mainmethod.premofm.data.model.EpisodeModel;
import com.mainmethod.premofm.helper.AppPrefHelper;
import com.mainmethod.premofm.helper.BroadcastHelper;
import com.mainmethod.premofm.helper.ColorHelper;
import com.mainmethod.premofm.helper.DatetimeHelper;
import com.mainmethod.premofm.helper.ImageLoadHelper;
import com.mainmethod.premofm.helper.MediaHelper;
import com.mainmethod.premofm.helper.NotificationHelper;
import com.mainmethod.premofm.helper.PaletteHelper;
import com.mainmethod.premofm.helper.PlaybackButtonHelper;
import com.mainmethod.premofm.helper.ShowcaseHelper;
import com.mainmethod.premofm.helper.SleepTimerHelper;
import com.mainmethod.premofm.object.Episode;
import com.mainmethod.premofm.service.PodcastPlayerService;
import com.mainmethod.premofm.ui.dialog.PlaybackSpeedDialog;
import com.mainmethod.premofm.ui.view.BlurTransformation;
import java.lang.ref.WeakReference;
import java.util.Calendar;
/**
* Shows the user the now playing user experience
* Created by evan on 12/16/14.
*/
public class NowPlayingActivity extends PlayableActivity implements
View.OnClickListener,
EpisodeModel.OnToggleFavoriteEpisodeListener,
OnSeekBarChangeListener {
public static final String PARAM_EPISODE_ID = "episodeId";
public static final String PARAM_PRIMARY_COLOR = "primaryColor";
public static final String PARAM_TEXT_COLOR = "textColor";
private static final float DEGREES_IN_CIRCLE = 360.0f;
private static final float MS_IN_RECORD_ROTATION = 1800.0f;
private SeekBar mSeekBar;
private TextView mEpisodeTitle;
private TextView mChannelTitle;
private TextView mTimeElapsed;
private TextView mTimeLeft;
private ImageButton mPlayButton;
private ImageButton mFavoriteButton;
private ImageButton mSeekBackward;
private ImageButton mSeekForward;
private ImageButton mInfo;
private ImageView mStreaming;
private ImageView mChannelArt;
private ImageView mBackground;
private MenuItem mSleepMenuItem;
private MenuItem mSleepTimerMenuItem;
private MenuItem mPlaybackSpeedItem;
private int mPrimaryColor = -1;
private int mTextColor = -1;
private Episode mEpisode;
private ProgressUpdateReceiver mProgressUpdateReceiver;
private CountDownTimer mCountDownTimer;
public static void start(BaseActivity activity, int primaryColor, int textColor) {
Bundle args = new Bundle();
args.putInt(PARAM_PRIMARY_COLOR, primaryColor);
args.putInt(PARAM_TEXT_COLOR, textColor);
activity.startSlideUpPremoActivity(NowPlayingActivity.class, -1, args);
}
private final PaletteHelper.OnPaletteLoaded mOnPaletteLoaded = this::themeUI;
@Override
protected int getHomeContentDescriptionResId() {
return R.string.back;
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_now_playing;
}
@Override
protected int getMenuResourceId() {
return R.menu.now_playing_activity;
}
@Override
public void onCreateBase(Bundle savedInstanceState) {
setHomeAsUpEnabled(true);
mEpisodeTitle = ((TextView) findViewById(R.id.episode_title));
mChannelTitle = ((TextView) findViewById(R.id.channel_title));
mTimeLeft = (TextView) findViewById(R.id.time_left);
mTimeElapsed = (TextView) findViewById(R.id.time_elapsed);
mChannelArt = (ImageView) findViewById(R.id.channel_art);
mChannelArt.setOnClickListener(this);
mPlayButton = (ImageButton) findViewById(R.id.play);
mPlayButton.setOnClickListener(this);
mFavoriteButton = (ImageButton) findViewById(R.id.favorite);
mFavoriteButton.setOnClickListener(this);
mBackground = (ImageView) findViewById(R.id.play_background);
mSeekBackward = (ImageButton) findViewById(R.id.seek_backward);
mSeekBackward.setOnClickListener(this);
mSeekForward = (ImageButton) findViewById(R.id.seek_forward);
mSeekForward.setOnClickListener(this);
mInfo = (ImageButton) findViewById(R.id.episode_info);
mInfo.setOnClickListener(this);
mStreaming = (ImageView) findViewById(R.id.streaming);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mSeekBar.setOnSeekBarChangeListener(this);
if (getIntent().getIntExtra(PARAM_EPISODE_ID, -1) != -1) {
PodcastPlayerService.sendIntent(this, PodcastPlayerService.ACTION_PLAY_EPISODE,
getIntent().getExtras().getInt(PARAM_EPISODE_ID));
NotificationHelper.dismissNotification(this,
NotificationHelper.NOTIFICATION_ID_NEW_EPISODES);
}
mPrimaryColor = getIntent().getIntExtra(PARAM_PRIMARY_COLOR, -1);
mTextColor = getIntent().getIntExtra(PARAM_TEXT_COLOR, -1);
if (mPrimaryColor != -1 && mTextColor != -1) {
themeUI(mPrimaryColor, mTextColor);
}
mProgressUpdateReceiver = new ProgressUpdateReceiver(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
onSeekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.channel_art:
case R.id.play:
switch (getState()) {
case PlaybackState.STATE_PLAYING:
onPauseEpisode();
break;
case PlaybackState.STATE_STOPPED:
case PlaybackState.STATE_NONE:
onPlayEpisode();
break;
case PlaybackState.STATE_PAUSED:
onResumePlayback();
break;
}
break;
case R.id.seek_backward:
onSeekBackward();
break;
case R.id.seek_forward:
onSeekForward();
break;
case R.id.episode_info:
showEpisodeInformation();
break;
case R.id.favorite:
favoriteEpisode(this);
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean hasMenu = super.onCreateOptionsMenu(menu);
mSleepMenuItem = menu.findItem(R.id.action_sleep);
mSleepTimerMenuItem = menu.findItem(R.id.action_sleep_timer);
mPlaybackSpeedItem = menu.findItem(R.id.action_playback_speed);
updatePlaybackSpeed();
initSleepTimerUi();
return hasMenu;
}
@Override
public void onBackPressed() {
super.onBackPressed();
animateExit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
animateExit();
return true;
case R.id.action_sleep_timer:
SleepTimerHelper.cancelTimer(this);
initSleepTimerUi();
endTimer();
return true;
case R.id.action_sleep:
showSleepTimerDialog();
return true;
case R.id.action_share_episode:
if (mEpisode != null) {
startEpisodeShare(mEpisode);
}
return true;
case R.id.action_play_queue:
showPlayQueue();
return true;
case R.id.action_playback_speed:
if (mEpisode != null) {
PlaybackSpeedDialog.show(this, mEpisode.getChannelGeneratedId());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onFavoriteToggled(boolean isFavorite) {
mFavoriteButton.setImageResource(isFavorite ? R.drawable.ic_favorite :
R.drawable.ic_favorite_outline);
}
private void animateExit() {
overridePendingTransition(R.anim.do_nothing, R.anim.slide_down);
}
protected void showSleepTimerDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.sleep_timer_title)
.setSingleChoiceItems(R.array.sleep_timer_labels, -1, (dialog, which) -> {
dialog.dismiss();
SleepTimerHelper.setTimerChoice(NowPlayingActivity.this, which);
initSleepTimerUi();
startTimer();
})
.setNegativeButton(R.string.dialog_cancel_timer, (dialog, which) -> {
SleepTimerHelper.cancelTimer(NowPlayingActivity.this);
initSleepTimerUi();
endTimer();
})
.setNeutralButton(R.string.dialog_close, null)
.show();
}
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mProgressUpdateReceiver,
new IntentFilter(BroadcastHelper.INTENT_PROGRESS_UPDATE));
initSleepTimerUi();
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mProgressUpdateReceiver);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu.findItem(R.string.action_cast).isVisible()) {
ShowcaseHelper.showNowPlayingShowcase(this);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onPodcastPlayerServiceBound() {}
@Override
public void onStateChanged(int state, Episode episode) {
if (mStreaming != null) {
mStreaming.setVisibility(isStreaming() ? View.VISIBLE : View.INVISIBLE);
}
if (episode == null) {
int episodeId = AppPrefHelper.getInstance(this).getLastPlayedEpisodeId();
if (episodeId > -1) {
episode = EpisodeModel.getEpisodeById(this, episodeId);
}
}
if (episode != null && state != PlaybackState.STATE_STOPPED) {
if (!episode.equals(mEpisode)) {
// a new episode has started
mEpisode = episode;
mPrimaryColor = -1;
mTextColor = -1;
}
if (mPrimaryColor == -1 && mTextColor == -1) {
String channelServerId = episode.getChannelGeneratedId();
ImageLoadHelper.loadImageAsync(this, episode.getChannelArtworkUrl(), new ImageLoadHelper.OnImageLoaded() {
@Override
public void imageLoaded(Bitmap bitmap) {
if (bitmap != null) {
mChannelArt.setImageBitmap(bitmap);
PaletteHelper.get(NowPlayingActivity.this)
.getChannelColors(channelServerId, bitmap, mOnPaletteLoaded);
}
}
@Override
public void imageFailed() {
mChannelArt.setImageDrawable(
new BitmapDrawable(NowPlayingActivity.this.getResources(), BitmapFactory.decodeResource(
NowPlayingActivity.this.getResources(), R.drawable.default_channel_art)));
}
});
} else {
ImageLoadHelper.loadImageIntoView(this, episode.getChannelArtworkUrl(), mChannelArt);
}
ImageLoadHelper.loadImageIntoView(this, episode.getChannelArtworkUrl(), mBackground,
new BlurTransformation(this));
// set the channel and episode titles
mEpisodeTitle.setText(episode.getTitle());
mChannelTitle.setText(episode.getChannelTitle());
updatePlaybackStats(episode.getProgress(), episode.getDuration());
updatePlaybackSpeed();
onFavoriteToggled(episode.isFavorite());
} else {
resetUI();
}
mPlayButton.setImageResource(PlaybackButtonHelper.getPlayerPlaybackButtonResId(state));
}
private void updatePlaybackSpeed() {
if (mPlaybackSpeedItem != null) {
String title;
if (mEpisode != null) {
title = AppPrefHelper.getInstance(this).getPlaybackSpeedLabel(
mEpisode.getChannelGeneratedId());
} else {
title = MediaHelper.formatSpeed(MediaHelper.DEFAULT_PLAYBACK_SPEED);
}
mPlaybackSpeedItem.setTitle(title);
}
}
private void initSleepTimerUi() {
if (mSleepMenuItem == null || mSleepTimerMenuItem == null) {
return;
}
if (SleepTimerHelper.timerIsActive(this)) {
mSleepTimerMenuItem.setVisible(true);
mSleepMenuItem.setVisible(false);
startTimer();
} else {
mSleepTimerMenuItem.setVisible(false);
mSleepMenuItem.setVisible(true);
endTimer();
}
}
private void startTimer() {
long timeToAlarm = AppPrefHelper.getInstance(this).getSleepTimer();
mCountDownTimer = new CountDownTimer(timeToAlarm, 1_000) {
@Override
public void onTick(long millisUntilFinished) {
updateSleepTimer();
}
@Override
public void onFinish() {
endTimer();
}
}.start();
}
private void endTimer() {
if (mCountDownTimer == null) {
return;
}
mCountDownTimer.cancel();
mCountDownTimer = null;
}
/**
* Updates the sleep timer
*/
private void updateSleepTimer() {
if (mSleepMenuItem == null || mSleepTimerMenuItem == null) {
return;
}
long now = Calendar.getInstance().getTimeInMillis();
long timeToAlarm = AppPrefHelper.getInstance(this).getSleepTimer();
mSleepTimerMenuItem.setTitle(DatetimeHelper.convertSecondsToDuration(timeToAlarm - now));
}
/**
* Themes the Now Playing UI with the appropriate colors
*/
private void themeUI(int primaryColor, int seekBarColor) {
findViewById(R.id.media_controls).setBackgroundColor(primaryColor);
getWindow().setStatusBarColor(ColorHelper.getStatusBarColor(primaryColor));
mToolbar.setBackgroundColor(primaryColor);
int textColor = ColorHelper.getTextColor(primaryColor);
mSeekBackward.setImageTintList(ColorStateList.valueOf(textColor));
mSeekForward.setImageTintList(ColorStateList.valueOf(textColor));
mPlayButton.setImageTintList(ColorStateList.valueOf(textColor));
mInfo.setImageTintList(ColorStateList.valueOf(textColor));
mFavoriteButton.setImageTintList(ColorStateList.valueOf(textColor));
mSeekBar.setProgressBackgroundTintList(ColorStateList.valueOf(seekBarColor));
mSeekBar.setBackgroundTintList(ColorStateList.valueOf(seekBarColor));
mSeekBar.setProgressTintList(ColorStateList.valueOf(primaryColor));
mSeekBar.setSecondaryProgressTintList(ColorStateList.valueOf(ColorHelper.darkenColor(primaryColor)));
mSeekBar.setThumbTintList(ColorStateList.valueOf(primaryColor));
}
/**
* Resets the user interface
*/
private void resetUI() {
mSeekBar.setEnabled(false);
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
mSeekBar.setSecondaryProgress(0);
mEpisodeTitle.setText("");
mChannelTitle.setText("");
mTimeElapsed.setText(R.string.empty_time);
mTimeLeft.setText(R.string.empty_time);
mBackground.setImageDrawable(null);
mChannelArt.setImageResource(R.drawable.default_channel_art);
themeUI(getResources().getColor(R.color.primary),
getResources().getColor(R.color.primary));
}
private void updatePlaybackStats(long progress, long duration) {
mChannelArt.setRotation(((progress / MS_IN_RECORD_ROTATION) * DEGREES_IN_CIRCLE)
% DEGREES_IN_CIRCLE);
mSeekBar.setProgress((int) progress);
mSeekBar.setMax((int) duration);
long left = duration - progress;
if (left == 0 && duration == 0) {
mTimeElapsed.setText(R.string.empty_time);
mTimeLeft.setText(R.string.empty_time);
} else {
mTimeElapsed.setText(DatetimeHelper.convertSecondsToDuration(progress));
mTimeLeft.setText(getString(R.string.time_left, DatetimeHelper.convertSecondsToDuration(left)));
}
}
private static class ProgressUpdateReceiver extends BroadcastReceiver {
private final WeakReference<NowPlayingActivity> mActivity;
public ProgressUpdateReceiver(NowPlayingActivity context) {
mActivity = new WeakReference<>(context);
}
@Override
public void onReceive(Context context, Intent intent) {
NowPlayingActivity activity = mActivity.get();
if (activity == null) {
return;
}
long progress = intent.getLongExtra(BroadcastHelper.EXTRA_PROGRESS, 0L);
long bufferedProgress = intent.getLongExtra(BroadcastHelper.EXTRA_BUFFERED_PROGRESS, 0L);
long duration = intent.getLongExtra(BroadcastHelper.EXTRA_DURATION, 0L);
activity.mSeekBar.setSecondaryProgress((int) bufferedProgress);
activity.updatePlaybackStats(progress, duration);
}
}
}
| |
/*
* 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.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.model.util.MapModel;
import org.apache.wicket.model.util.WildcardCollectionModel;
import org.apache.wicket.model.util.WildcardListModel;
import org.apache.wicket.model.util.WildcardSetModel;
import org.apache.wicket.util.lang.Objects;
/**
* <code>Model</code> is the basic implementation of an <code>IModel</code>. It just wraps a simple
* model object. The model object must be serializable, as it is stored in the session. If you have
* large objects to store, consider using {@link org.apache.wicket.model.LoadableDetachableModel}
* instead of this class.
*
* @author Chris Turner
* @author Eelco Hillenius
*
* @param <T>
* The type of the Model Object
*/
public class Model<T extends Serializable> implements IModel<T>
{
private static final long serialVersionUID = 1L;
/** Backing object. */
private T object;
/**
* Construct the model without providing an object.
*/
public Model()
{
}
/**
* Construct the model, setting the given object as the wrapped object.
*
* @param object
* The model object proper
*/
public Model(final T object)
{
setObject(object);
}
/**
* Factory method for models that contain lists. This factory method will automatically rebuild
* a nonserializable <code>list</code> into a serializable one.
*
* @param <C>
* model type
* @param list
* The List, which may or may not be Serializable
* @return A Model object wrapping the List
*/
public static <C> IModel<List<? extends C>> ofList(final List<? extends C> list)
{
return new WildcardListModel<C>(list);
}
/**
* Factory method for models that contain maps. This factory method will automatically rebuild a
* nonserializable <code>map</code> into a serializable one.
*
* @param <K>
* key type in map
* @param <V>
* value type in map
* @param map
* The Map, which may or may not be Serializable
* @return A Model object wrapping the Map
*/
public static <K, V> IModel<Map<K, V>> ofMap(final Map<K, V> map)
{
return new MapModel<K, V>(map);
}
/**
* Factory method for models that contain sets. This factory method will automatically rebuild a
* nonserializable <code>set</code> into a serializable one.
*
* @param <C>
* model type
* @param set
* The Set, which may or may not be Serializable
* @return A Model object wrapping the Set
*/
public static <C> IModel<Set<? extends C>> ofSet(final Set<? extends C> set)
{
return new WildcardSetModel<C>(set);
}
/**
* Factory method for models that contain collections. This factory method will automatically
* rebuild a nonserializable <code>collection</code> into a serializable {@link ArrayList}.
*
* @param <C>
* model type
* @param set
* The Collection, which may or may not be Serializable
* @return A Model object wrapping the Set
*/
public static <C> IModel<Collection<? extends C>> of(final Collection<? extends C> set)
{
return new WildcardCollectionModel<C>(set);
}
/**
* Factory methods for Model which uses type inference to make code shorter. Equivalent to
* <code>new Model<TypeOfObject>(object)</code>.
*
* @param <T>
* @param object
* @return Model that contains <code>object</code>
*/
public static <T extends Serializable> Model<T> of(T object)
{
return new Model<T>(object);
}
/**
* Factory methods for Model which uses type inference to make code shorter. Equivalent to
* <code>new Model<TypeOfObject>()</code>.
*
* @param <T>
* @return Model that contains <code>object</code>
*/
public static <T extends Serializable> Model<T> of()
{
return new Model<T>();
}
/**
* @see org.apache.wicket.model.IModel#getObject()
*/
public T getObject()
{
return object;
}
/**
* Set the model object; calls setObject(java.io.Serializable). The model object must be
* serializable, as it is stored in the session
*
* @param object
* the model object
* @see org.apache.wicket.model.IModel#setObject(Object)
*/
public void setObject(final T object)
{
if (object != null)
{
if (!(object instanceof Serializable))
{
throw new WicketRuntimeException("Model object must be Serializable");
}
}
this.object = object;
}
/**
* @see org.apache.wicket.model.IDetachable#detach()
*/
public void detach()
{
if (object instanceof IDetachable)
{
((IDetachable)object).detach();
}
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("Model:classname=[");
sb.append(getClass().getName()).append("]");
sb.append(":object=[").append(object).append("]");
return sb.toString();
}
@Override
public int hashCode()
{
return Objects.hashCode(object);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof Model<?>))
{
return false;
}
Model<?> that = (Model<?>)obj;
return Objects.equal(object, that.object);
}
/**
* Supresses generics warning when converting model types
*
* @param <T>
* @param model
* @return <code>model</code>
*/
@SuppressWarnings("unchecked")
public static <T> IModel<T> of(IModel<?> model)
{
return (IModel<T>)model;
}
}
| |
/*
* 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.io.testtools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
/**
* Base class for testcases doing tests with files.
*/
public abstract class FileBasedTestCase extends TestCase {
private static volatile File testDir;
public FileBasedTestCase(final String name) {
super(name);
}
public static File getTestDirectory() {
if (testDir == null) {
testDir = new File("test/io/").getAbsoluteFile();
}
testDir.mkdirs();
return testDir;
}
protected void createFile(final File file, final long size)
throws IOException {
if (!file.getParentFile().exists()) {
throw new IOException("Cannot create file " + file
+ " as the parent directory does not exist");
}
final BufferedOutputStream output =
new BufferedOutputStream(new java.io.FileOutputStream(file));
try {
generateTestData(output, size);
} finally {
IOUtils.closeQuietly(output);
}
}
protected byte[] generateTestData(final long size) {
try {
final ByteArrayOutputStream baout = new ByteArrayOutputStream();
generateTestData(baout, size);
return baout.toByteArray();
} catch (final IOException ioe) {
throw new RuntimeException("This should never happen: " + ioe.getMessage());
}
}
protected void generateTestData(final OutputStream out, final long size)
throws IOException {
for (int i = 0; i < size; i++) {
//output.write((byte)'X');
// nice varied byte pattern compatible with Readers and Writers
out.write( (byte)( (i % 127) + 1) );
}
}
protected void createLineBasedFile(final File file, final String[] data) throws IOException {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
}
final PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
try {
for (final String element : data) {
output.println(element);
}
} finally {
IOUtils.closeQuietly(output);
}
}
protected File newFile(final String filename) throws IOException {
final File destination = new File( getTestDirectory(), filename );
/*
assertTrue( filename + "Test output data file shouldn't previously exist",
!destination.exists() );
*/
if (destination.exists()) {
FileUtils.forceDelete(destination);
}
return destination;
}
protected void checkFile( final File file, final File referenceFile )
throws Exception {
assertTrue( "Check existence of output file", file.exists() );
assertEqualContent( referenceFile, file );
}
/** Assert that the content of two files is the same. */
private void assertEqualContent( final File f0, final File f1 )
throws IOException
{
/* This doesn't work because the filesize isn't updated until the file
* is closed.
assertTrue( "The files " + f0 + " and " + f1 +
" have differing file sizes (" + f0.length() +
" vs " + f1.length() + ")", ( f0.length() == f1.length() ) );
*/
final InputStream is0 = new java.io.FileInputStream( f0 );
try {
final InputStream is1 = new java.io.FileInputStream( f1 );
try {
final byte[] buf0 = new byte[ 1024 ];
final byte[] buf1 = new byte[ 1024 ];
int n0 = 0;
int n1 = 0;
while( -1 != n0 )
{
n0 = is0.read( buf0 );
n1 = is1.read( buf1 );
assertTrue( "The files " + f0 + " and " + f1 +
" have differing number of bytes available (" + n0 +
" vs " + n1 + ")", ( n0 == n1 ) );
assertTrue( "The files " + f0 + " and " + f1 +
" have different content", Arrays.equals( buf0, buf1 ) );
}
} finally {
is1.close();
}
} finally {
is0.close();
}
}
/**
* Assert that the content of a file is equal to that in a byte[].
*
* @param b0 the expected contents
* @param file the file to check
*
* @throws IOException If an I/O error occurs while reading the file contents
*/
protected void assertEqualContent(final byte[] b0, final File file) throws IOException {
final InputStream is = new java.io.FileInputStream(file);
int count = 0, numRead = 0;
final byte[] b1 = new byte[b0.length];
try {
while (count < b0.length && numRead >= 0) {
numRead = is.read(b1, count, b0.length);
count += numRead;
}
assertEquals("Different number of bytes: ", b0.length, count);
for (int i = 0; i < count; i++) {
assertEquals("byte " + i + " differs", b0[i], b1[i]);
}
} finally {
is.close();
}
}
/**
* Assert that the content of a file is equal to that in a char[].
*
* @param c0 the expected contents
* @param file the file to check
*
* @throws IOException If an I/O error occurs while reading the file contents
*/
protected void assertEqualContent(final char[] c0, final File file) throws IOException {
final Reader ir = new java.io.FileReader(file);
int count = 0, numRead = 0;
final char[] c1 = new char[c0.length];
try {
while (count < c0.length && numRead >= 0) {
numRead = ir.read(c1, count, c0.length);
count += numRead;
}
assertEquals("Different number of chars: ", c0.length, count);
for (int i = 0; i < count; i++) {
assertEquals("char " + i + " differs", c0[i], c1[i]);
}
} finally {
ir.close();
}
}
protected void checkWrite(final OutputStream output) throws Exception {
try {
new java.io.PrintStream(output).write(0);
} catch (final Throwable t) {
throw new AssertionFailedError(
"The copy() method closed the stream "
+ "when it shouldn't have. "
+ t.getMessage());
}
}
protected void checkWrite(final Writer output) throws Exception {
try {
new java.io.PrintWriter(output).write('a');
} catch (final Throwable t) {
throw new AssertionFailedError(
"The copy() method closed the stream "
+ "when it shouldn't have. "
+ t.getMessage());
}
}
protected void deleteFile( final File file )
throws Exception {
if (file.exists()) {
assertTrue("Couldn't delete file: " + file, file.delete());
}
}
}
| |
/*
* 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.tephra.txprune;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import org.apache.hadoop.conf.Configuration;
import org.apache.tephra.Transaction;
import org.apache.tephra.TransactionManager;
import org.apache.tephra.TxConstants;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Test {@link TransactionPruningService}.
*/
public class TransactionPruningServiceTest {
@Before
public void resetData() {
MockTxManager.getPrunedInvalidsList().clear();
MockPlugin1.getInactiveTransactionBoundList().clear();
MockPlugin1.getMaxPrunedInvalidList().clear();
MockPlugin2.getInactiveTransactionBoundList().clear();
MockPlugin2.getMaxPrunedInvalidList().clear();
}
@Test
public void testTransactionPruningService() throws Exception {
// Setup plugins
Configuration conf = new Configuration();
conf.set(TxConstants.TransactionPruning.PLUGINS,
"data.tx.txprune.plugin.mockPlugin1, data.tx.txprune.plugin.mockPlugin2");
conf.set("data.tx.txprune.plugin.mockPlugin1.class",
"org.apache.tephra.txprune.TransactionPruningServiceTest$MockPlugin1");
conf.set("data.tx.txprune.plugin.mockPlugin2.class",
"org.apache.tephra.txprune.TransactionPruningServiceTest$MockPlugin2");
// Setup schedule to run every second
conf.setBoolean(TxConstants.TransactionPruning.PRUNE_ENABLE, true);
conf.setInt(TxConstants.Manager.CFG_TX_MAX_LIFETIME, 10);
conf.setLong(TxConstants.TransactionPruning.PRUNE_GRACE_PERIOD, 0);
// Setup mock data
long m = 1000;
long n = m * TxConstants.MAX_TX_PER_MS;
// Current time to be returned
Iterator<Long> currentTime = Iterators.cycle(120L * m, 220L * m);
// Transaction objects to be returned by mock tx manager
Iterator<Transaction> txns =
Iterators.cycle(new Transaction(100 * n, 110 * n, new long[]{40 * n, 50 * n, 60 * n, 70 * n},
new long[]{80 * n, 90 * n}, 80 * n),
new Transaction(200 * n, 210 * n, new long[]{60 * n, 75 * n, 78 * n, 100 * n, 110 * n, 120 * n},
new long[]{80 * n, 90 * n}, 80 * n));
// Prune upper bounds to be returned by the mock plugins
Iterator<Long> pruneUpperBoundsPlugin1 = Iterators.cycle(60L * n, 80L * n);
Iterator<Long> pruneUpperBoundsPlugin2 = Iterators.cycle(70L * n, 77L * n);
TestTransactionPruningRunnable.setCurrentTime(currentTime);
MockTxManager.setTxIter(txns);
MockPlugin1.setPruneUpperBoundIter(pruneUpperBoundsPlugin1);
MockPlugin2.setPruneUpperBoundIter(pruneUpperBoundsPlugin2);
MockTxManager mockTxManager = new MockTxManager(conf);
TransactionPruningService pruningService = new TestTransactionPruningService(conf, mockTxManager);
pruningService.startAndWait();
// This will cause the pruning run to happen three times,
// but we are interested in only first two runs for the assertions later
int pruneRuns = TestTransactionPruningRunnable.getRuns();
pruningService.pruneNow();
pruningService.pruneNow();
pruningService.pruneNow();
TestTransactionPruningRunnable.waitForRuns(pruneRuns + 3, 5, TimeUnit.MILLISECONDS);
pruningService.stopAndWait();
// Assert inactive transaction bound that the plugins receive.
// Both the plugins should get the same inactive transaction bound since it is
// computed and passed by the transaction service
Assert.assertEquals(ImmutableList.of(110L * n - 1, 210L * n - 1),
limitTwo(MockPlugin1.getInactiveTransactionBoundList()));
Assert.assertEquals(ImmutableList.of(110L * n - 1, 210L * n - 1),
limitTwo(MockPlugin2.getInactiveTransactionBoundList()));
// Assert invalid list entries that got pruned
// The min prune upper bound for the first run should be 60, and for the second run 77
Assert.assertEquals(ImmutableList.of(ImmutableSet.of(40L * n, 50L * n, 60L * n), ImmutableSet.of(60L * n, 75L * n)),
limitTwo(MockTxManager.getPrunedInvalidsList()));
// Assert max invalid tx pruned that the plugins receive for the prune complete call
// Both the plugins should get the same max invalid tx pruned value since it is
// computed and passed by the transaction service
Assert.assertEquals(ImmutableList.of(60L * n, 75L * n), limitTwo(MockPlugin1.getMaxPrunedInvalidList()));
Assert.assertEquals(ImmutableList.of(60L * n, 75L * n), limitTwo(MockPlugin2.getMaxPrunedInvalidList()));
}
@Test
public void testNoPruning() throws Exception {
// Setup plugins
Configuration conf = new Configuration();
conf.set(TxConstants.TransactionPruning.PLUGINS,
"data.tx.txprune.plugin.mockPlugin1, data.tx.txprune.plugin.mockPlugin2");
conf.set("data.tx.txprune.plugin.mockPlugin1.class",
"org.apache.tephra.txprune.TransactionPruningServiceTest$MockPlugin1");
conf.set("data.tx.txprune.plugin.mockPlugin2.class",
"org.apache.tephra.txprune.TransactionPruningServiceTest$MockPlugin2");
// Setup schedule to run every second
conf.setBoolean(TxConstants.TransactionPruning.PRUNE_ENABLE, true);
conf.setInt(TxConstants.Manager.CFG_TX_MAX_LIFETIME, 10);
conf.setLong(TxConstants.TransactionPruning.PRUNE_GRACE_PERIOD, 0);
// Setup mock data
long m = 1000;
long n = m * TxConstants.MAX_TX_PER_MS;
// Current time to be returned
Iterator<Long> currentTime = Iterators.cycle(120L * m, 220L * m);
// Transaction objects to be returned by mock tx manager
Iterator<Transaction> txns =
Iterators.cycle(new Transaction(100 * n, 110 * n, new long[]{40 * n, 50 * n, 60 * n, 70 * n},
new long[]{80 * n, 90 * n}, 80 * n),
new Transaction(200 * n, 210 * n, new long[]{60 * n, 75 * n, 78 * n, 100 * n, 110 * n, 120 * n},
new long[]{80 * n, 90 * n}, 80 * n));
// Prune upper bounds to be returned by the mock plugins
Iterator<Long> pruneUpperBoundsPlugin1 = Iterators.cycle(35L * n, -1L);
Iterator<Long> pruneUpperBoundsPlugin2 = Iterators.cycle(70L * n, 100L * n);
TestTransactionPruningRunnable.setCurrentTime(currentTime);
MockTxManager.setTxIter(txns);
MockPlugin1.setPruneUpperBoundIter(pruneUpperBoundsPlugin1);
MockPlugin2.setPruneUpperBoundIter(pruneUpperBoundsPlugin2);
MockTxManager mockTxManager = new MockTxManager(conf);
TransactionPruningService pruningService = new TestTransactionPruningService(conf, mockTxManager);
pruningService.startAndWait();
// This will cause the pruning run to happen three times,
// but we are interested in only first two runs for the assertions later
int pruneRuns = TestTransactionPruningRunnable.getRuns();
pruningService.pruneNow();
pruningService.pruneNow();
pruningService.pruneNow();
TestTransactionPruningRunnable.waitForRuns(pruneRuns + 3, 5, TimeUnit.MILLISECONDS);
pruningService.stopAndWait();
// Assert inactive transaction bound
Assert.assertEquals(ImmutableList.of(110L * n - 1, 210L * n - 1),
limitTwo(MockPlugin1.getInactiveTransactionBoundList()));
Assert.assertEquals(ImmutableList.of(110L * n - 1, 210L * n - 1),
limitTwo(MockPlugin2.getInactiveTransactionBoundList()));
// Invalid entries should not be pruned in any run
Assert.assertEquals(ImmutableList.of(), MockTxManager.getPrunedInvalidsList());
// No max invalid tx pruned for any run
Assert.assertEquals(ImmutableList.of(), limitTwo(MockPlugin1.getMaxPrunedInvalidList()));
Assert.assertEquals(ImmutableList.of(), limitTwo(MockPlugin2.getMaxPrunedInvalidList()));
}
/**
* Mock transaction manager for testing
*/
private static class MockTxManager extends TransactionManager {
private static Iterator<Transaction> txIter;
private static List<Set<Long>> prunedInvalidsList = new ArrayList<>();
MockTxManager(Configuration config) {
super(config);
}
@Override
public Transaction startShort() {
return txIter.next();
}
@Override
public void abort(Transaction tx) {
// do nothing
}
@Override
public boolean truncateInvalidTx(Set<Long> invalidTxIds) {
prunedInvalidsList.add(invalidTxIds);
return true;
}
static void setTxIter(Iterator<Transaction> txIter) {
MockTxManager.txIter = txIter;
}
static List<Set<Long>> getPrunedInvalidsList() {
return prunedInvalidsList;
}
}
/**
* Extends {@link TransactionPruningService} to use mock time to help in testing.
*/
private static class TestTransactionPruningService extends TransactionPruningService {
TestTransactionPruningService(Configuration conf, TransactionManager txManager) {
super(conf, txManager);
}
@Override
TransactionPruningRunnable getTxPruneRunnable(TransactionManager txManager,
Map<String, TransactionPruningPlugin> plugins,
long txMaxLifetimeMillis, long txPruneBufferMillis) {
return new TestTransactionPruningRunnable(txManager, plugins, txMaxLifetimeMillis, txPruneBufferMillis);
}
}
/**
* Extends {@link TransactionPruningRunnable} to use mock time to help in testing.
*/
private static class TestTransactionPruningRunnable extends TransactionPruningRunnable {
private static int pruneRuns = 0;
private static Iterator<Long> currentTime;
TestTransactionPruningRunnable(TransactionManager txManager, Map<String, TransactionPruningPlugin> plugins,
long txMaxLifetimeMillis, long txPruneBufferMillis) {
super(txManager, plugins, txMaxLifetimeMillis, txPruneBufferMillis);
}
@Override
long getTime() {
return currentTime.next();
}
static void setCurrentTime(Iterator<Long> currentTime) {
TestTransactionPruningRunnable.currentTime = currentTime;
}
@Override
public void run() {
super.run();
pruneRuns++;
}
private static int getRuns() {
return pruneRuns;
}
public static void waitForRuns(int runs, int timeout, TimeUnit unit) throws Exception {
long timeoutMillis = unit.toMillis(timeout);
Stopwatch stopWatch = new Stopwatch();
stopWatch.start();
while (pruneRuns < runs && stopWatch.elapsedMillis() < timeoutMillis) {
TimeUnit.MILLISECONDS.sleep(100);
}
}
}
/**
* Mock transaction pruning plugin for testing.
*/
private static class MockPlugin1 implements TransactionPruningPlugin {
private static Iterator<Long> pruneUpperBoundIter;
private static List<Long> inactiveTransactionBoundList = new ArrayList<>();
private static List<Long> maxPrunedInvalidList = new ArrayList<>();
@Override
public void initialize(Configuration conf) throws IOException {
// Nothing to do
}
@Override
public long fetchPruneUpperBound(long time, long inactiveTransactionBound) throws IOException {
inactiveTransactionBoundList.add(inactiveTransactionBound);
return pruneUpperBoundIter.next();
}
@Override
public void pruneComplete(long time, long maxPrunedInvalid) throws IOException {
maxPrunedInvalidList.add(maxPrunedInvalid);
}
@Override
public void destroy() {
// Nothing to do
}
static void setPruneUpperBoundIter(Iterator<Long> pruneUpperBoundIter) {
MockPlugin1.pruneUpperBoundIter = pruneUpperBoundIter;
}
static List<Long> getInactiveTransactionBoundList() {
return inactiveTransactionBoundList;
}
static List<Long> getMaxPrunedInvalidList() {
return maxPrunedInvalidList;
}
}
/**
* Mock transaction pruning plugin for testing.
*/
private static class MockPlugin2 implements TransactionPruningPlugin {
private static Iterator<Long> pruneUpperBoundIter;
private static List<Long> inactiveTransactionBoundList = new ArrayList<>();
private static List<Long> maxPrunedInvalidList = new ArrayList<>();
@Override
public void initialize(Configuration conf) throws IOException {
// Nothing to do
}
@Override
public long fetchPruneUpperBound(long time, long inactiveTransactionBound) throws IOException {
inactiveTransactionBoundList.add(inactiveTransactionBound);
return pruneUpperBoundIter.next();
}
@Override
public void pruneComplete(long time, long maxPrunedInvalid) throws IOException {
maxPrunedInvalidList.add(maxPrunedInvalid);
}
@Override
public void destroy() {
// Nothing to do
}
static void setPruneUpperBoundIter(Iterator<Long> pruneUpperBoundIter) {
MockPlugin2.pruneUpperBoundIter = pruneUpperBoundIter;
}
static List<Long> getInactiveTransactionBoundList() {
return inactiveTransactionBoundList;
}
static List<Long> getMaxPrunedInvalidList() {
return maxPrunedInvalidList;
}
}
private static <T> List<T> limitTwo(Iterable<T> iterable) {
return ImmutableList.copyOf(Iterables.limit(iterable, 2));
}
}
| |
/*
* Copyright 2014 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.gradle.model.internal.core;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import net.jcip.annotations.NotThreadSafe;
import net.jcip.annotations.ThreadSafe;
import org.gradle.api.Action;
import org.gradle.api.Transformer;
import org.gradle.internal.Actions;
import org.gradle.internal.BiAction;
import org.gradle.internal.Factories;
import org.gradle.internal.Factory;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.core.rule.describe.SimpleModelRuleDescriptor;
import org.gradle.model.internal.type.ModelType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ThreadSafe
public abstract class ModelRegistrations {
public static <T> Builder serviceInstance(ModelReference<T> modelReference, T instance) {
return bridgedInstance(modelReference, instance)
.hidden(true);
}
public static <T> Builder bridgedInstance(ModelReference<T> modelReference, T instance) {
return unmanagedInstance(modelReference, Factories.constant(instance), Actions.doNothing());
}
public static <T> Builder unmanagedInstance(ModelReference<T> modelReference, final Factory<? extends T> factory) {
return unmanagedInstance(modelReference, factory, Actions.doNothing());
}
public static <T> Builder unmanagedInstance(final ModelReference<T> modelReference, final Factory<? extends T> factory, final Action<? super MutableModelNode> initializer) {
return unmanagedInstanceOf(modelReference, new Transformer<T, MutableModelNode>() {
@Override
public T transform(MutableModelNode modelNode) {
T t = factory.create();
initializer.execute(modelNode);
return t;
}
});
}
public static <T> Builder unmanagedInstanceOf(final ModelReference<T> modelReference, final Transformer<? extends T, ? super MutableModelNode> factory) {
return of(modelReference.getPath())
.action(ModelActionRole.Create, new Action<MutableModelNode>() {
@Override
public void execute(MutableModelNode modelNode) {
T t = factory.transform(modelNode);
modelNode.setPrivateData(modelReference.getType(), t);
}
})
.withProjection(UnmanagedModelProjection.of(modelReference.getType()));
}
public static Builder of(ModelPath path) {
return new Builder(path);
}
public static Builder of(ModelPath path, NodeInitializer initializer) {
return new Builder(path, initializer);
}
@NotThreadSafe
public static class Builder {
private final ModelReference<Object> reference;
private final List<ModelProjection> projections = new ArrayList<ModelProjection>();
private final ListMultimap<ModelActionRole, ModelAction> actions = ArrayListMultimap.create();
private final NodeInitializer nodeInitializer;
private final DescriptorReference descriptorReference = new DescriptorReference();
private boolean hidden;
private Builder(ModelPath path) {
this(path, null);
}
private Builder(ModelPath path, NodeInitializer nodeInitializer) {
this.reference = ModelReference.of(path);
this.nodeInitializer = nodeInitializer;
}
public Builder descriptor(String descriptor) {
return descriptor(new SimpleModelRuleDescriptor(descriptor));
}
public Builder descriptor(ModelRuleDescriptor descriptor) {
this.descriptorReference.descriptor = descriptor;
return this;
}
public Builder action(ModelActionRole role, ModelAction action) {
this.actions.put(role, action);
return this;
}
public Builder action(ModelActionRole role, Action<? super MutableModelNode> action) {
return action(role, new NoInputsBuilderAction(reference, descriptorReference, action));
}
public <T> Builder action(ModelActionRole role, ModelReference<T> input, BiAction<MutableModelNode, T> action) {
return action(role, new InputsUsingBuilderAction(reference, descriptorReference, Collections.singleton(input), new SingleInputNodeBiAction<T>(input.getType(), action)));
}
public Builder action(ModelActionRole role, Iterable<? extends ModelReference<?>> inputs, BiAction<? super MutableModelNode, ? super List<ModelView<?>>> action) {
return action(role, new InputsUsingBuilderAction(reference, descriptorReference, inputs, action));
}
public Builder actions(Multimap<ModelActionRole, ? extends ModelAction> actions) {
this.actions.putAll(actions);
return this;
}
public Builder withProjection(ModelProjection projection) {
projections.add(projection);
return this;
}
public Builder hidden(boolean flag) {
this.hidden = flag;
return this;
}
public ModelRegistration build() {
ModelRuleDescriptor descriptor = descriptorReference.descriptor;
if (nodeInitializer != null) {
actions.putAll(nodeInitializer.getActions(reference, descriptor));
}
if (!projections.isEmpty()) {
action(ModelActionRole.Discover, AddProjectionsAction.of(reference, descriptor, projections));
}
return new DefaultModelRegistration(reference.getPath(), descriptor, hidden, actions);
}
private static class DescriptorReference {
private ModelRuleDescriptor descriptor;
}
private static abstract class AbstractBuilderAction implements ModelAction {
private final ModelReference<Object> subject;
private final DescriptorReference descriptorReference;
public AbstractBuilderAction(ModelReference<Object> subject, DescriptorReference descriptorReference) {
this.subject = subject;
this.descriptorReference = descriptorReference;
}
@Override
public ModelReference<Object> getSubject() {
return subject;
}
@Override
public ModelRuleDescriptor getDescriptor() {
return descriptorReference.descriptor;
}
}
private static class NoInputsBuilderAction extends AbstractBuilderAction {
private final Action<? super MutableModelNode> action;
public NoInputsBuilderAction(ModelReference<Object> subject, DescriptorReference descriptorReference, Action<? super MutableModelNode> action) {
super(subject, descriptorReference);
this.action = action;
}
@Override
public void execute(MutableModelNode modelNode, List<ModelView<?>> inputs) {
action.execute(modelNode);
}
@Override
public List<? extends ModelReference<?>> getInputs() {
return Collections.emptyList();
}
}
private static class InputsUsingBuilderAction extends AbstractBuilderAction {
private final List<ModelReference<?>> inputs;
private final BiAction<? super MutableModelNode, ? super List<ModelView<?>>> action;
public InputsUsingBuilderAction(ModelReference<Object> subject, DescriptorReference descriptorReference, Iterable<? extends ModelReference<?>> inputs, BiAction<? super MutableModelNode, ? super List<ModelView<?>>> action) {
super(subject, descriptorReference);
this.inputs = ImmutableList.copyOf(inputs);
this.action = action;
}
@Override
public void execute(MutableModelNode modelNode, List<ModelView<?>> inputs) {
action.execute(modelNode, inputs);
}
@Override
public List<? extends ModelReference<?>> getInputs() {
return inputs;
}
}
private static class SingleInputNodeBiAction<T> implements BiAction<MutableModelNode, List<ModelView<?>>> {
private final ModelType<T> type;
private final BiAction<MutableModelNode, T> action;
public SingleInputNodeBiAction(ModelType<T> type, BiAction<MutableModelNode, T> action) {
this.type = type;
this.action = action;
}
@Override
public void execute(MutableModelNode mutableModelNode, List<ModelView<?>> modelViews) {
T input = ModelViews.getInstance(modelViews, 0, type);
action.execute(mutableModelNode, input);
}
}
}
}
| |
/**
* Copyright (C) 2004-2011 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.sparkimpl.plugin.privacy;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo.Feature;
import org.jivesoftware.smackx.privacy.PrivacyList;
import org.jivesoftware.smackx.privacy.PrivacyListManager;
import org.jivesoftware.smackx.privacy.packet.PrivacyItem;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.privacy.list.PrivacyPresenceHandler;
import org.jivesoftware.sparkimpl.plugin.privacy.list.SparkPrivacyList;
import org.jivesoftware.sparkimpl.plugin.privacy.list.SparkPrivacyListListener;
import java.util.*;
/**
* @author Zolotarev Konstantin, Bergunde Holger
*/
public class PrivacyManager {
private static PrivacyManager singleton;
private static final Object LOCK = new Object();
// XEP-0126. To help ensure cross-client compatibility,
// it is RECOMMENDED to use the privacy list names "visible" and "invisible"
// for simple global visibility and invisibility respectively.
// It is also RECOMMENDED to use list names of the form "visible-to-GroupName"
// and "invisible-to-JID" for simple lists that implement visibility or invisibility
// with regard to roster groups and JIDs. Obviously list names could become rather complex,
// such as "visible-to-Group1 Group2 Group3".
private static final String INVISIBLE_LIST_NAME = "invisible";
private List<SparkPrivacyList> _privacyLists = new ArrayList<>();
private PrivacyListManager privacyManager;
private PrivacyPresenceHandler _presenceHandler = new PrivacyPresenceHandler();
private Set<SparkPrivacyListListener> _listListeners = new HashSet<>();
private boolean _active = false;
private SparkPrivacyList previousActiveList;
/**
* Creating PrivacyListManager instance
*/
private PrivacyManager() {
XMPPConnection conn = SparkManager.getConnection();
if (conn == null) {
Log.error("Privacy plugin: Connection not initialized.");
}
_active = checkIfPrivacyIsSupported(conn);
if (_active)
{
privacyManager = PrivacyListManager.getInstanceFor(conn);
initializePrivacyLists();
}
}
/**
* Get Class instance
*
* @return instance of {@link PrivacyManager}
*/
public static PrivacyManager getInstance() {
// Synchronize on LOCK to ensure that we don't end up creating
// two singletons.
synchronized (LOCK) {
if (null == singleton) {
singleton = new PrivacyManager();
}
}
return singleton;
}
private boolean checkIfPrivacyIsSupported(XMPPConnection conn) {
ServiceDiscoveryManager servDisc = ServiceDiscoveryManager.getInstanceFor(conn);
DiscoverInfo info = null;
try {
info = servDisc.discoverInfo(conn.getServiceName());
} catch (XMPPException | SmackException e) {
// We could not query the server
}
if (info != null) {
for ( final Feature feature : info.getFeatures() ) {
if (feature.getVar().contains("jabber:iq:privacy")) {
return true;
}
}
}
return false;
}
private void initializePrivacyLists()
{
try {
List<PrivacyList> lists = privacyManager.getPrivacyLists();
for (PrivacyList list: lists)
{
SparkPrivacyList sparkList = new SparkPrivacyList(list);
sparkList.addSparkPrivacyListener(_presenceHandler);
if (!isListHidden(sparkList))
_privacyLists.add(sparkList);
}
} catch (XMPPException | SmackException e) {
Log.error("Could not load PrivacyLists", e);
}
if(hasDefaultList())
{
setListAsActive(getDefaultList().getListName());
}
}
public void removePrivacyList(String listName) {
try {
privacyManager.deletePrivacyList(listName);
_privacyLists.remove(getPrivacyList(listName));
} catch (XMPPException | SmackException e) {
Log.warning("Could not remove PrivacyList " + listName, e);
}
}
/**
* Check for active list existence
*
* @return boolean
*/
public boolean hasActiveList() {
for (SparkPrivacyList list: _privacyLists)
{
if (list.isActive())
return true;
}
return false;
}
/**
* Returns the active PrivacyList
*
* @return the list if there is one, else null
*/
public SparkPrivacyList getActiveList() {
for (SparkPrivacyList list: _privacyLists)
{
if (list.isActive())
return list;
}
return null;
}
/**
* Returns the sparkprivacylist that the manager keeps local, to get updated
* version try to forcereloadlists
*
* @param s
* the name of the list
* @return SparkPrivacyList
*/
public SparkPrivacyList getPrivacyList(String s) {
for (SparkPrivacyList list: _privacyLists)
{
if (list.getListName().equals(s))
return list;
}
return createPrivacyList(s);
}
/**
* Check if active list exist
*
* @return boolean
*/
public boolean hasDefaultList() {
for (SparkPrivacyList list: _privacyLists)
{
if (list.isDefault())
return true;
}
return false;
}
public SparkPrivacyList getDefaultList()
{
for (SparkPrivacyList list: _privacyLists)
{
if (list.isDefault())
return list;
}
return null;
}
/**
* Get <code>org.jivesoftware.smackx.privacy.PrivacyListManager</code> instance
*
* @return PrivacyListManager
*/
public PrivacyListManager getPrivacyListManager() {
return privacyManager;
}
public SparkPrivacyList createPrivacyList(String listName) {
PrivacyItem item = new PrivacyItem(true,999999);
ArrayList<PrivacyItem> items = new ArrayList<>();
items.add(item);
SparkPrivacyList sparklist = null;
try {
privacyManager.createPrivacyList(listName, items);
privacyManager.getPrivacyList(listName).getItems().remove(item);
sparklist = new SparkPrivacyList(privacyManager.getPrivacyList(listName));
_privacyLists.add(sparklist);
sparklist.addSparkPrivacyListener(_presenceHandler);
} catch (XMPPException | SmackException e) {
Log.warning("Could not create PrivacyList "+listName, e);
}
return sparklist;
}
/**
* The server can store different privacylists. This method will return the
* names of the lists, currently available on the server
*
* @return All Listnames
*/
public List<SparkPrivacyList> getPrivacyLists() {
return new ArrayList<>( _privacyLists );
}
public void setListAsActive(String listname)
{
try {
privacyManager.setActiveListName(listname);
fireListActivated(listname);
if (hasActiveList())
{
_presenceHandler.removeIconsForList(getActiveList());
}
getPrivacyList(listname).setListAsActive(true);
for (SparkPrivacyList plist : _privacyLists) {
if (!plist.getListName().equals(listname))
plist.setListAsActive(false);
}
_presenceHandler.setIconsForList(getActiveList());
} catch (XMPPException | SmackException e) {
Log.warning("Could not activate PrivacyList " + listname, e);
}
}
public void setListAsDefault(String listname) {
try {
privacyManager.setDefaultListName(listname);
fireListSetAsDefault(listname);
getPrivacyList(listname).setListIsDefault(true);
for (SparkPrivacyList plist : _privacyLists) {
if (!plist.getListName().equals(listname))
plist.setListIsDefault(false);
}
} catch (XMPPException | SmackException e) {
Log.warning("Could not set PrivacyList " + listname+" as default", e);
}
}
public void declineActiveList()
{
try {
if(hasActiveList())
{
privacyManager.declineActiveList();
fireListDeActivated(getActiveList().getListName());
_presenceHandler.removeIconsForList(getActiveList());
}
for (SparkPrivacyList plist : _privacyLists) {
plist.setListAsActive(false);
}
} catch (XMPPException | SmackException e) {
Log.warning("Could not decline active privacy list", e);
}
}
public void declineDefaultList()
{
try {
if (hasDefaultList())
{
privacyManager.declineDefaultList();
fireListRemovedAsDefault(getDefaultList().getListName());
for (SparkPrivacyList plist : _privacyLists) {
plist.setListIsDefault(false);
}
}
} catch (XMPPException | SmackException e) {
Log.warning("Could not decline default privacy list", e);
}
}
public boolean isPrivacyActive()
{
return _active ;
}
public void addListListener (SparkPrivacyListListener listener)
{
_listListeners.add(listener);
}
public void deleteListListener (SparkPrivacyListListener listener)
{
_listListeners.remove(listener);
}
private void fireListActivated( String listName )
{
for ( final SparkPrivacyListListener listener : _listListeners )
{
try
{
listener.listActivated( listName );
}
catch ( Exception e )
{
Log.error( "A SparkPrivacyListListener (" + listener + ") threw an exception while processing a 'listActivated' event for: " + listName, e );
}
}
}
private void fireListDeActivated( String listName )
{
for ( final SparkPrivacyListListener listener : _listListeners )
{
try
{
listener.listDeActivated( listName );
}
catch ( Exception e )
{
Log.error( "A SparkPrivacyListListener (" + listener + ") threw an exception while processing a 'listDeActivated' event for: " + listName, e );
}
}
}
private void fireListSetAsDefault( String listName )
{
for ( final SparkPrivacyListListener listener : _listListeners )
{
try
{
listener.listSetAsDefault( listName );
}
catch ( Exception e )
{
Log.error( "A SparkPrivacyListListener (" + listener + ") threw an exception while processing a 'listSetAsDefault' event for: " + listName, e );
}
}
}
private void fireListRemovedAsDefault( String listName )
{
for ( final SparkPrivacyListListener listener : _listListeners )
{
try
{
listener.listRemovedAsDefault( listName );
}
catch ( Exception e )
{
Log.error( "A SparkPrivacyListListener (" + listener + ") threw an exception while processing a 'listRemovedAsDefault' event for: " + listName, e );
}
}
}
public void goToInvisible()
{
if (!_active)
return;
ensureGloballyInvisibleListExists();
// make it active
activateGloballyInvisibleList();
}
public void goToVisible()
{
if (!_active)
return;
try {
if (!isGloballyInvisibleListActive())
return;
privacyManager.declineActiveList();
SparkManager.getConnection().sendStanza(PresenceManager.getAvailablePresence());
Log.debug("List \"" + INVISIBLE_LIST_NAME + "\" has been disabled ");
if (previousActiveList != null) {
setListAsActive(previousActiveList.getListName());
Log.debug("List \"" + previousActiveList.getListName() + "\" has been activated instead. ");
}
} catch (Exception e) {
Log.error("PrivacyManager#goToVisible: ", e);
}
}
public void activateGloballyInvisibleList() {
if (!_active)
return;
if (!SparkManager.getConnection().isConnected() || isGloballyInvisibleListActive())
return;
try {
previousActiveList = getActiveList();
privacyManager.setActiveListName(INVISIBLE_LIST_NAME);
SparkManager.getConnection().sendStanza(PresenceManager.getAvailablePresence());
Log.debug("List \"" + INVISIBLE_LIST_NAME + "\" has been activated ");
} catch (Exception e) {
Log.error("PrivacyManager#activateGloballyInvisibleList: ", e);
}
}
public static boolean isListHidden(SparkPrivacyList list) {
return list != null && INVISIBLE_LIST_NAME.equalsIgnoreCase(list.getListName());
}
public boolean isGloballyInvisibleListActive() {
if (!_active)
return false;
try {
String pl = privacyManager.getActiveListName();
return pl != null && INVISIBLE_LIST_NAME.equalsIgnoreCase(pl.toString());
} catch (Exception e){
// it can return item-not-found if there is no active list.
// so it is fine to fall here.
Log.error("PrivacyManager#isGloballyInvisibleListActive: ", e);
}
return false;
}
private PrivacyList ensureGloballyInvisibleListExists() {
if (!_active)
return null;
PrivacyList list = null;
try
{
list = privacyManager.getPrivacyList(INVISIBLE_LIST_NAME);
if (list != null)
return list;
} catch (XMPPException | SmackException e1) {
Log.debug("PrivacyManager#ensureGloballyInvisibleListExists: Could not find globally invisible list. We need to create one");
}
try {
PrivacyItem item = new PrivacyItem(false, 1);
item.setFilterPresenceOut(true);
List<PrivacyItem> items = Arrays.asList(item);
privacyManager.createPrivacyList(INVISIBLE_LIST_NAME, items);
list = privacyManager.getPrivacyList(INVISIBLE_LIST_NAME);
Log.debug("List \"" + INVISIBLE_LIST_NAME + "\" has been created ");
}
catch (XMPPException | SmackException e)
{
Log.warning("PrivacyManager#ensureGloballyInvisibleListExists: Could not create PrivacyList " + INVISIBLE_LIST_NAME, e);
}
return list;
}
}
| |
package net.meisen.dissertation.server;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.text.DecimalFormat;
import java.util.Map;
import net.meisen.dissertation.config.xslt.DefaultValues;
import net.meisen.dissertation.exceptions.AuthException;
import net.meisen.dissertation.exceptions.PermissionException;
import net.meisen.dissertation.model.auth.IAuthManager;
import net.meisen.dissertation.model.auth.permissions.Permission;
import net.meisen.dissertation.server.sessions.Session;
import net.meisen.dissertation.server.sessions.SessionManager;
import net.meisen.general.genmisc.exceptions.ForwardedException;
import net.meisen.general.genmisc.exceptions.ForwardedRuntimeException;
import net.meisen.general.genmisc.exceptions.registry.IExceptionRegistry;
import net.meisen.general.sbconfigurator.api.IConfiguration;
import net.meisen.general.server.http.listener.api.IServlet;
import net.meisen.general.server.http.listener.util.RequestHandlingUtilities;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
/**
* Base implementation of a {@code Servlet}, which ensures the checking of
* permissions and binds the session to the thread of the servlet.
*
* @author pmeisen
*
*/
public abstract class BaseServlet implements IServlet {
/**
* The parameter used to specify the session's identifier
*/
public final static String PARAM_SESSIONID = "sessionId";
private final static Logger LOG = LoggerFactory
.getLogger(BaseServlet.class);
/**
* The result of a handle, see {@link BaseServlet#_handle(HttpRequest)}.
*
* @author pmeisen
*
*/
protected static class HandleResult {
/**
* the result
*/
public final String result;
/**
* the type
*/
public final ContentType type;
/**
* Constructor specifying the result and the type.
*
* @param result
* the result
* @param type
* the type of the result
*/
public HandleResult(final String result, final ContentType type) {
this.result = result;
this.type = type;
}
}
/**
* The used {@code AuthManager}.
*/
@Autowired
@Qualifier(DefaultValues.AUTHMANAGER_ID)
protected IAuthManager authManager;
/**
* The used {@code SessionManager}.
*/
@Autowired
@Qualifier(DefaultValues.SESSIONMANAGER_ID)
protected SessionManager sessionManager;
/**
* The used {@code ExceptionRegistry}.
*/
@Autowired(required = false)
@Qualifier(IConfiguration.coreExceptionRegistryId)
protected IExceptionRegistry exceptionRegistry;
/**
* Enables the base implementation to check the
* {@link Permission#connectHTTP}.
*
* @return {@code true} to enable the checking for the servlet, otherwise
* {@code false}
*/
protected boolean doHttpPermissionCheck() {
return true;
}
/**
* Enables the base implementation to check the
* {@link Permission#connectHTTP}.
*
* @return {@code true} to enable the checking for the servlet, otherwise
* {@code false}
*/
protected boolean needValidSession() {
return true;
}
/**
* Checks if the current user has the permission to connect via http.
*/
protected void checkHttpPermission() {
// check if the permission to use this kind of connection is available
if (!authManager.hasPermission(Permission.connectHTTP.create())) {
exceptionRegistry.throwRuntimeException(PermissionException.class,
1000, Permission.connectHTTP);
}
}
/**
* Checks the session and binds it to the current thread. The method throws
* an exception if the session is invalid.
*
* @param sessionId
* the identifier of the session to be checked
*
* @return the {@code Session} instance associated to the specified
* {@code sessionId}
*/
protected Session checkSession(final String sessionId) {
final Session session = sessionManager.getSession(sessionId, true);
authManager.bind(session);
return session;
}
/**
* @see #_handle(HttpRequest)
*/
@Override
public void handle(final HttpRequest request, final HttpResponse response,
final HttpContext context) {
/*
* TODO: we should make this one configurable... otherwise attacks may
* be possible
*/
response.setHeader("Access-Control-Allow-Origin", "*");
// check if we have an options call
if ("OPTIONS".equals(request.getRequestLine().getMethod())) {
// reply with an empty text
final StringEntity entity = new StringEntity("",
ContentType.TEXT_PLAIN);
response.setEntity(entity);
} else {
String result;
ContentType type;
try {
/*
* Start some performance measure on TRACE
*/
ThreadMXBean mxBean = null;
long start = 0L;
if (LOG.isInfoEnabled() && measurePerformace()) {
final ThreadMXBean tmpMxBean = ManagementFactory
.getThreadMXBean();
if (tmpMxBean.isCurrentThreadCpuTimeSupported()) {
start = tmpMxBean.getCurrentThreadCpuTime();
mxBean = tmpMxBean;
}
}
final HandleResult handleRes = _handle(request);
result = handleRes.result;
type = handleRes.type;
/*
* Stop performance measure on TRACE and write it
*/
if (mxBean != null) {
final long end = mxBean.getCurrentThreadCpuTime();
final DecimalFormat df = new DecimalFormat(
"###,##0.00000####");
final double cputime = ((double) end - start) / 1000000000.0;
LOG.info("Query was performed in " + df.format(cputime) + "s");
}
} catch (final AuthException e) {
if (LOG.isDebugEnabled()) {
LOG.error("Invalid request considering permissions.", e);
}
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
result = wrapExceptionToJson(e);
type = ContentType.APPLICATION_JSON;
} catch (final ForwardedException fwdE) {
type = ContentType.APPLICATION_JSON;
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
try {
exceptionRegistry.throwException(fwdE);
result = wrapExceptionToJson(fwdE);
} catch (final Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Request failed because of a failure.", e);
}
result = wrapExceptionToJson(e);
}
} catch (final ForwardedRuntimeException fwdE) {
type = ContentType.APPLICATION_JSON;
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
try {
exceptionRegistry.throwRuntimeException(fwdE);
result = wrapExceptionToJson(fwdE);
} catch (final Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Request failed because of a failure.", e);
}
result = wrapExceptionToJson(e);
}
} catch (final Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Request failed because of a failure.", e);
}
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
result = wrapExceptionToJson(e);
type = ContentType.APPLICATION_JSON;
} finally {
// make sure the current session is unbound from the current
// user
authManager.unbind();
}
// create the answer
final StringEntity entity = new StringEntity(result, type);
response.setEntity(entity);
}
}
/**
* Method specifying if measure performance of the servlet should be printed
* on info level.
*
* @return {@code true} if the performance should be printed on info level,
* otherwise {@code false}
*/
protected boolean measurePerformace() {
return true;
}
/**
* Method called to handle the request. When this method is called, the
* base-implementation already validated if an {@code OPTIONS} request was
* sent (i.e. {@code OPTIONS} method are not handled here, those are already
* handled in {@link #handle(HttpRequest, HttpResponse, HttpContext)}) <br/>
* <br/>
* <b>OPTIONS methods</b><br/>
* The OPTIONS method represents a request for information about the
* communication options available on the request/response chain identified
* by the Request-URI. This method allows the client to determine the
* options and/or requirements associated with a resource, or the
* capabilities of a server, without implying a resource action or
* initiating a resource retrieval.
*
* @param request
* the request
*
*
* @return the result of the handling
*
* @throws Exception
* if the request could not be handled
*/
protected HandleResult _handle(final HttpRequest request) throws Exception {
// get the parameters
final Map<String, String> parameters = RequestHandlingUtilities
.parsePostParameter(request);
if (LOG.isTraceEnabled()) {
LOG.trace("Received parameters with request: " + parameters);
}
// first of all the user has to be checked in
if (needValidSession()) {
final Session session = checkSession(parameters
.get(PARAM_SESSIONID));
session.markAsUsed();
}
// do a check first
if (doHttpPermissionCheck()) {
checkHttpPermission();
}
// now handle the request
final Object tmpResult = handleRequest(request, parameters);
// determine the representation of the result
String result;
ContentType type;
if (tmpResult == null) {
type = ContentType.APPLICATION_JSON;
result = JsonValue.NULL.toString();
} else if (tmpResult instanceof JsonObject) {
type = ContentType.APPLICATION_JSON;
result = tmpResult.toString();
} else if (tmpResult instanceof String) {
type = getResponseContentType();
result = tmpResult.toString();
} else {
if (LOG.isErrorEnabled()) {
LOG.error("Unsupported type '" + tmpResult
+ "' returned by request-handling.");
}
type = ContentType.APPLICATION_JSON;
result = JsonValue.NULL.toString();
}
return new HandleResult(result, type);
}
/**
* Method to be implemented by the concrete implementation.
*
* @param request
* the request asked for
* @param parameters
* the post-parameters retrieved from the request
* @return the result of the handling, can be {@code null}, a
* {@code JsonValue}, or a string usable by the client
*
* @throws Exception
* if an exception is fired during the handling
*/
protected abstract Object handleRequest(final HttpRequest request,
final Map<String, String> parameters) throws Exception;
/**
* Method defining the type of the {@code Object} returned by the
* {@link #handleRequest(HttpRequest, Map)}.
*
* @return the type of the result of the {@code handleRequest} method
*/
protected ContentType getResponseContentType() {
return ContentType.APPLICATION_JSON;
}
/**
* Wraps the exception into a {@code Json} instance.
*
* @param e
* the exception to be wrapped
*
* @return the JSON representing the exception
*/
protected String wrapExceptionToJson(final Exception e) {
final JsonObject wrappedException = new JsonObject().add("type",
"error").add("message", e.getLocalizedMessage());
return wrappedException.toString();
}
}
| |
package org.apache.lucene.search;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.FilterLeafReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
public class TestTermScorer extends LuceneTestCase {
protected Directory directory;
private static final String FIELD = "field";
protected String[] values = new String[] {"all", "dogs dogs", "like",
"playing", "fetch", "all"};
protected IndexSearcher indexSearcher;
protected LeafReader indexReader;
@Override
public void setUp() throws Exception {
super.setUp();
directory = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), directory,
newIndexWriterConfig(new MockAnalyzer(random()))
.setMergePolicy(newLogMergePolicy())
.setSimilarity(new DefaultSimilarity()));
for (int i = 0; i < values.length; i++) {
Document doc = new Document();
doc
.add(newTextField(FIELD, values[i], Field.Store.YES));
writer.addDocument(doc);
}
indexReader = SlowCompositeReaderWrapper.wrap(writer.getReader());
writer.close();
indexSearcher = newSearcher(indexReader);
indexSearcher.setSimilarity(new DefaultSimilarity());
}
@Override
public void tearDown() throws Exception {
indexReader.close();
directory.close();
super.tearDown();
}
public void test() throws IOException {
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
Weight weight = indexSearcher.createNormalizedWeight(termQuery, true);
assertTrue(indexSearcher.getTopReaderContext() instanceof LeafReaderContext);
LeafReaderContext context = (LeafReaderContext)indexSearcher.getTopReaderContext();
BulkScorer ts = weight.bulkScorer(context);
// we have 2 documents with the term all in them, one document for all the
// other values
final List<TestHit> docs = new ArrayList<>();
// must call next first
ts.score(new SimpleCollector() {
private int base = 0;
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) {
this.scorer = scorer;
}
@Override
public void collect(int doc) throws IOException {
float score = scorer.score();
doc = doc + base;
docs.add(new TestHit(doc, score));
assertTrue("score " + score + " is not greater than 0", score > 0);
assertTrue("Doc: " + doc + " does not equal 0 or doc does not equal 5",
doc == 0 || doc == 5);
}
@Override
protected void doSetNextReader(LeafReaderContext context) throws IOException {
base = context.docBase;
}
@Override
public boolean needsScores() {
return true;
}
}, null);
assertTrue("docs Size: " + docs.size() + " is not: " + 2, docs.size() == 2);
TestHit doc0 = docs.get(0);
TestHit doc5 = docs.get(1);
// The scores should be the same
assertTrue(doc0.score + " does not equal: " + doc5.score,
doc0.score == doc5.score);
/*
* Score should be (based on Default Sim.: All floats are approximate tf = 1
* numDocs = 6 docFreq(all) = 2 idf = ln(6/3) + 1 = 1.693147 idf ^ 2 =
* 2.8667 boost = 1 lengthNorm = 1 //there is 1 term in every document coord
* = 1 sumOfSquaredWeights = (idf * boost) ^ 2 = 1.693147 ^ 2 = 2.8667
* queryNorm = 1 / (sumOfSquaredWeights)^0.5 = 1 /(1.693147) = 0.590
*
* score = 1 * 2.8667 * 1 * 1 * 0.590 = 1.69
*/
assertTrue(doc0.score + " does not equal: " + 1.6931472f,
doc0.score == 1.6931472f);
}
public void testNext() throws Exception {
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
Weight weight = indexSearcher.createNormalizedWeight(termQuery, true);
assertTrue(indexSearcher.getTopReaderContext() instanceof LeafReaderContext);
LeafReaderContext context = (LeafReaderContext) indexSearcher.getTopReaderContext();
Scorer ts = weight.scorer(context);
assertTrue("next did not return a doc",
ts.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
assertTrue("score is not correct", ts.score() == 1.6931472f);
assertTrue("next did not return a doc",
ts.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
assertTrue("score is not correct", ts.score() == 1.6931472f);
assertTrue("next returned a doc and it should not have",
ts.nextDoc() == DocIdSetIterator.NO_MORE_DOCS);
}
public void testAdvance() throws Exception {
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
Weight weight = indexSearcher.createNormalizedWeight(termQuery, true);
assertTrue(indexSearcher.getTopReaderContext() instanceof LeafReaderContext);
LeafReaderContext context = (LeafReaderContext) indexSearcher.getTopReaderContext();
Scorer ts = weight.scorer(context);
assertTrue("Didn't skip", ts.advance(3) != DocIdSetIterator.NO_MORE_DOCS);
// The next doc should be doc 5
assertTrue("doc should be number 5", ts.docID() == 5);
}
private class TestHit {
public int doc;
public float score;
public TestHit(int doc, float score) {
this.doc = doc;
this.score = score;
}
@Override
public String toString() {
return "TestHit{" + "doc=" + doc + ", score=" + score + "}";
}
}
public void testDoesNotLoadNorms() throws IOException {
Term allTerm = new Term(FIELD, "all");
TermQuery termQuery = new TermQuery(allTerm);
LeafReader forbiddenNorms = new FilterLeafReader(indexReader) {
@Override
public NumericDocValues getNormValues(String field) throws IOException {
fail("Norms should not be loaded");
// unreachable
return null;
}
};
// We don't use newSearcher because it sometimes runs checkIndex which loads norms
IndexSearcher indexSearcher = new IndexSearcher(forbiddenNorms);
Weight weight = indexSearcher.createNormalizedWeight(termQuery, true);
try {
weight.scorer(forbiddenNorms.getContext()).nextDoc();
fail("Should load norms");
} catch (AssertionError e) {
// ok
}
weight = indexSearcher.createNormalizedWeight(termQuery, false);
// should not fail this time since norms are not necessary
weight.scorer(forbiddenNorms.getContext()).nextDoc();
}
}
| |
/*
* Copyright 2006 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.GlobalNamespace.Name;
import com.google.javascript.jscomp.GlobalNamespace.Ref;
import com.google.javascript.jscomp.GlobalNamespace.Ref.Type;
import com.google.javascript.jscomp.ReferenceCollectingCallback;
import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
import com.google.javascript.jscomp.Scope;
import com.google.javascript.jscomp.Scope.Var;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TokenStream;
import com.google.javascript.rhino.jstype.JSType;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Flattens global objects/namespaces by replacing each '.' with '$' in
* their names. This reduces the number of property lookups the browser has
* to do and allows the {@link RenameVars} pass to shorten namespaced names.
* For example, goog.events.handleEvent() -> goog$events$handleEvent() -> Za().
*
* <p>If a global object's name is assigned to more than once, or if a property
* is added to the global object in a complex expression, then none of its
* properties will be collapsed (for safety/correctness).
*
* <p>If, after a global object is declared, it is never referenced except when
* its properties are read or set, then the object will be removed after its
* properties have been collapsed.
*
* <p>Uninitialized variable stubs are created at a global object's declaration
* site for any of its properties that are added late in a local scope.
*
* <p>If, after an object is declared, it is referenced directly in a way that
* might create an alias for it, then none of its properties will be collapsed.
* This behavior is a safeguard to prevent the values associated with the
* flattened names from getting out of sync with the object's actual property
* values. For example, in the following case, an alias a$b, if created, could
* easily keep the value 0 even after a.b became 5:
* <code> a = {b: 0}; c = a; c.b = 5; </code>.
*
* <p>This pass doesn't flatten property accesses of the form: a[b].
*
* <p>For lots of examples, see the unit test.
*
*/
class CollapseProperties implements CompilerPass {
// Warnings
static final DiagnosticType UNSAFE_NAMESPACE_WARNING =
DiagnosticType.warning(
"JSC_UNSAFE_NAMESPACE",
"incomplete alias created for namespace {0}");
static final DiagnosticType NAMESPACE_REDEFINED_WARNING =
DiagnosticType.warning(
"JSC_NAMESPACE_REDEFINED",
"namespace {0} should not be redefined");
static final DiagnosticType UNSAFE_THIS = DiagnosticType.warning(
"JSC_UNSAFE_THIS",
"dangerous use of 'this' in static method {0}");
private AbstractCompiler compiler;
/** Global namespace tree */
private List<Name> globalNames;
/** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */
private Map<String, Name> nameMap;
private final boolean collapsePropertiesOnExternTypes;
private final boolean inlineAliases;
/**
* Creates an instance.
*
* @param compiler The JSCompiler, for reporting code changes
* @param collapsePropertiesOnExternTypes if true, will rename user-defined
* static properties on externed typed. E.g. String.foo.
* @param inlineAliases Whether we're allowed to inline local aliases of
* namespaces, etc.
*/
CollapseProperties(AbstractCompiler compiler,
boolean collapsePropertiesOnExternTypes, boolean inlineAliases) {
this.compiler = compiler;
this.collapsePropertiesOnExternTypes = collapsePropertiesOnExternTypes;
this.inlineAliases = inlineAliases;
}
@Override
public void process(Node externs, Node root) {
GlobalNamespace namespace;
if (collapsePropertiesOnExternTypes) {
namespace = new GlobalNamespace(compiler, externs, root);
} else {
namespace = new GlobalNamespace(compiler, root);
}
if (inlineAliases) {
inlineAliases(namespace);
}
nameMap = namespace.getNameIndex();
globalNames = namespace.getNameForest();
checkNamespaces();
for (Name n : globalNames) {
flattenReferencesToCollapsibleDescendantNames(n, n.getBaseName());
}
// We collapse property definitions after collapsing property references
// because this step can alter the parse tree above property references,
// invalidating the node ancestry stored with each reference.
for (Name n : globalNames) {
collapseDeclarationOfNameAndDescendants(n, n.getBaseName());
}
}
/**
* For each qualified name N in the global scope, we check if:
* (a) No ancestor of N is ever aliased or assigned an unknown value type.
* (If N = "a.b.c", "a" and "a.b" are never aliased).
* (b) N has exactly one write, and it lives in the global scope.
* (c) N is aliased in a local scope.
*
* If (a) is true, then GlobalNamespace must know all the writes to N.
* If (a) and (b) are true, then N cannot change during the execution of
* a local scope.
* If (a) and (b) and (c) are true, then the alias can be inlined if the
* alias obeys the usual rules for how we decide whether a variable is
* inlineable.
* @see InlineVariables
*/
private void inlineAliases(GlobalNamespace namespace) {
// Invariant: All the names in the worklist meet condition (a).
Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
while (!workList.isEmpty()) {
Name name = workList.pop();
// Don't attempt to inline a getter or setter property as a variable.
if (name.type == Name.Type.GET || name.type == Name.Type.SET) {
continue;
}
if (!name.inExterns && name.globalSets == 1 && name.localSets == 0 &&
name.aliasingGets > 0) {
// {@code name} meets condition (b). Find all of its local aliases
// and try to inline them.
List<Ref> refs = Lists.newArrayList(name.getRefs());
for (Ref ref : refs) {
if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {
// {@code name} meets condition (c). Try to inline it.
if (inlineAliasIfPossible(ref, namespace)) {
name.removeRef(ref);
}
}
}
}
// Check if {@code name} has any aliases left after the
// local-alias-inlining above.
if ((name.type == Name.Type.OBJECTLIT ||
name.type == Name.Type.FUNCTION) &&
name.aliasingGets == 0 && name.props != null) {
// All of {@code name}'s children meet condition (a), so they can be
// added to the worklist.
workList.addAll(name.props);
}
}
}
private boolean inlineAliasIfPossible(Ref alias, GlobalNamespace namespace) {
// Ensure that the alias is assigned to a local variable at that
// variable's declaration. If the alias's parent is a NAME,
// then the NAME must be the child of a VAR node, and we must
// be in a VAR assignment.
Node aliasParent = alias.node.getParent();
if (aliasParent.isName()) {
// Ensure that the local variable is well defined and never reassigned.
Scope scope = alias.scope;
Var aliasVar = scope.getVar(aliasParent.getString());
ReferenceCollectingCallback collector =
new ReferenceCollectingCallback(compiler,
ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR,
Predicates.<Var>equalTo(aliasVar));
(new NodeTraversal(compiler, collector)).traverseAtScope(scope);
ReferenceCollection aliasRefs = collector.getReferences(aliasVar);
if (aliasRefs.isWellDefined()
&& aliasRefs.firstReferenceIsAssigningDeclaration()
&& aliasRefs.isAssignedOnceInLifetime()) {
// The alias is well-formed, so do the inlining now.
int size = aliasRefs.references.size();
Set<Node> newNodes = Sets.newHashSetWithExpectedSize(size - 1);
for (int i = 1; i < size; i++) {
ReferenceCollectingCallback.Reference aliasRef =
aliasRefs.references.get(i);
Node newNode = alias.node.cloneTree();
aliasRef.getParent().replaceChild(aliasRef.getNode(), newNode);
newNodes.add(newNode);
}
// just set the original alias to null.
aliasParent.replaceChild(alias.node, IR.nullNode());
compiler.reportCodeChange();
// Inlining the variable may have introduced new references
// to descendants of {@code name}. So those need to be collected now.
namespace.scanNewNodes(alias.scope, newNodes);
return true;
}
}
return false;
}
/**
* Runs through all namespaces (prefixes of classes and enums), and checks if
* any of them have been used in an unsafe way.
*/
private void checkNamespaces() {
for (Name name : nameMap.values()) {
if (name.isNamespace() &&
(name.aliasingGets > 0 || name.localSets + name.globalSets > 1 ||
name.deleteProps > 0)) {
boolean initialized = name.getDeclaration() != null;
for (Ref ref : name.getRefs()) {
if (ref == name.getDeclaration()) {
continue;
}
if (ref.type == Ref.Type.DELETE_PROP) {
if (initialized) {
warnAboutNamespaceRedefinition(name, ref);
}
} else if (
ref.type == Ref.Type.SET_FROM_GLOBAL ||
ref.type == Ref.Type.SET_FROM_LOCAL) {
if (initialized) {
warnAboutNamespaceRedefinition(name, ref);
}
initialized = true;
} else if (ref.type == Ref.Type.ALIASING_GET) {
warnAboutNamespaceAliasing(name, ref);
}
}
}
}
}
/**
* Reports a warning because a namespace was aliased.
*
* @param nameObj A namespace that is being aliased
* @param ref The reference that forced the alias
*/
private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) {
compiler.report(
JSError.make(ref.getSourceName(), ref.node,
UNSAFE_NAMESPACE_WARNING, nameObj.getFullName()));
}
/**
* Reports a warning because a namespace was redefined.
*
* @param nameObj A namespace that is being redefined
* @param ref The reference that set the namespace
*/
private void warnAboutNamespaceRedefinition(Name nameObj, Ref ref) {
compiler.report(
JSError.make(ref.getSourceName(), ref.node,
NAMESPACE_REDEFINED_WARNING, nameObj.getFullName()));
}
/**
* Flattens all references to collapsible properties of a global name except
* their initial definitions. Recurses on subnames.
*
* @param n An object representing a global name
* @param alias The flattened name for {@code n}
*/
private void flattenReferencesToCollapsibleDescendantNames(
Name n, String alias) {
if (n.props == null) return;
for (Name p : n.props) {
String propAlias = appendPropForAlias(alias, p.getBaseName());
if (p.canCollapse()) {
flattenReferencesTo(p, propAlias);
} else if (p.isSimpleStubDeclaration()) {
flattenSimpleStubDeclaration(p, propAlias);
}
flattenReferencesToCollapsibleDescendantNames(p, propAlias);
}
}
/**
* Flattens a stub declaration.
* This is mostly a hack to support legacy users.
*/
private void flattenSimpleStubDeclaration(Name name, String alias) {
Ref ref = Iterables.getOnlyElement(name.getRefs());
Node nameNode = NodeUtil.newName(
compiler.getCodingConvention(), alias, ref.node,
name.getFullName());
Node varNode = IR.var(nameNode).copyInformationFrom(nameNode);
Preconditions.checkState(
ref.node.getParent().isExprResult());
Node parent = ref.node.getParent();
Node gramps = parent.getParent();
gramps.replaceChild(parent, varNode);
compiler.reportCodeChange();
}
/**
* Flattens all references to a collapsible property of a global name except
* its initial definition.
*
* @param n A global property name (e.g. "a.b" or "a.b.c.d")
* @param alias The flattened name (e.g. "a$b" or "a$b$c$d")
*/
private void flattenReferencesTo(Name n, String alias) {
String originalName = n.getFullName();
for (Ref r : n.getRefs()) {
if (r == n.getDeclaration()) {
// Declarations are handled separately.
continue;
}
Node rParent = r.node.getParent();
// There are two cases when we shouldn't flatten a reference:
// 1) Object literal keys, because duplicate keys show up as refs.
// 2) References inside a complex assign. (a = x.y = 0). These are
// called TWIN references, because they show up twice in the
// reference list. Only collapse the set, not the alias.
if (!NodeUtil.isObjectLitKey(r.node) &&
(r.getTwin() == null || r.isSet())) {
flattenNameRef(alias, r.node, rParent, originalName);
}
}
// Flatten all occurrences of a name as a prefix of its subnames. For
// example, if {@code n} corresponds to the name "a.b", then "a.b" will be
// replaced with "a$b" in all occurrences of "a.b.c", "a.b.c.d", etc.
if (n.props != null) {
for (Name p : n.props) {
flattenPrefixes(alias, p, 1);
}
}
}
/**
* Flattens all occurrences of a name as a prefix of subnames beginning
* with a particular subname.
*
* @param n A global property name (e.g. "a.b.c.d")
* @param alias A flattened prefix name (e.g. "a$b")
* @param depth The difference in depth between the property name and
* the prefix name (e.g. 2)
*/
private void flattenPrefixes(String alias, Name n, int depth) {
// Only flatten the prefix of a name declaration if the name being
// initialized is fully qualified (i.e. not an object literal key).
String originalName = n.getFullName();
Ref decl = n.getDeclaration();
if (decl != null && decl.node != null &&
decl.node.isGetProp()) {
flattenNameRefAtDepth(alias, decl.node, depth, originalName);
}
for (Ref r : n.getRefs()) {
if (r == decl) {
// Declarations are handled separately.
continue;
}
// References inside a complex assign (a = x.y = 0)
// have twins. We should only flatten one of the twins.
if (r.getTwin() == null || r.isSet()) {
flattenNameRefAtDepth(alias, r.node, depth, originalName);
}
}
if (n.props != null) {
for (Name p : n.props) {
flattenPrefixes(alias, p, depth + 1);
}
}
}
/**
* Flattens a particular prefix of a single name reference.
*
* @param alias A flattened prefix name (e.g. "a$b")
* @param n The node corresponding to a subproperty name (e.g. "a.b.c.d")
* @param depth The difference in depth between the property name and
* the prefix name (e.g. 2)
* @param originalName String version of the property name.
*/
private void flattenNameRefAtDepth(String alias, Node n, int depth,
String originalName) {
// This method has to work for both GETPROP chains and, in rare cases,
// OBJLIT keys, possibly nested. That's why we check for children before
// proceeding. In the OBJLIT case, we don't need to do anything.
int nType = n.getType();
boolean isQName = nType == Token.NAME || nType == Token.GETPROP;
boolean isObjKey = NodeUtil.isObjectLitKey(n);
Preconditions.checkState(isObjKey || isQName);
if (isQName) {
for (int i = 1; i < depth && n.hasChildren(); i++) {
n = n.getFirstChild();
}
if (n.hasChildren()) {
flattenNameRef(alias, n.getFirstChild(), n, originalName);
}
}
}
/**
* Replaces a GETPROP a.b.c with a NAME a$b$c.
*
* @param alias A flattened prefix name (e.g. "a$b")
* @param n The GETPROP node corresponding to the original name (e.g. "a.b")
* @param parent {@code n}'s parent
* @param originalName String version of the property name.
*/
private void flattenNameRef(String alias, Node n, Node parent,
String originalName) {
// BEFORE:
// getprop
// getprop
// name a
// string b
// string c
// AFTER:
// name a$b$c
Node ref = NodeUtil.newName(
compiler.getCodingConvention(), alias, n, originalName);
NodeUtil.copyNameAnnotations(n.getLastChild(), ref);
if (parent.isCall() && n == parent.getFirstChild()) {
// The node was a call target, we are deliberately flatten these as
// we node the "this" isn't provided by the namespace. Mark it as such:
parent.putBooleanProp(Node.FREE_CALL, true);
}
JSType type = n.getJSType();
if (type != null) {
ref.setJSType(type);
}
parent.replaceChild(n, ref);
compiler.reportCodeChange();
}
/**
* Collapses definitions of the collapsible properties of a global name.
* Recurses on subnames that also represent JavaScript objects with
* collapsible properties.
*
* @param n A node representing a global name
* @param alias The flattened name for {@code n}
*/
private void collapseDeclarationOfNameAndDescendants(Name n, String alias) {
boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames();
// Handle this name first so that nested object literals get unrolled.
if (n.canCollapse()) {
updateObjLitOrFunctionDeclaration(n, alias, canCollapseChildNames);
}
if (n.props != null) {
for (Name p : n.props) {
// Recurse first so that saved node ancestries are intact when needed.
collapseDeclarationOfNameAndDescendants(
p, appendPropForAlias(alias, p.getBaseName()));
if (!p.inExterns && canCollapseChildNames &&
p.getDeclaration() != null &&
p.canCollapse() &&
p.getDeclaration().node != null &&
p.getDeclaration().node.getParent() != null &&
p.getDeclaration().node.getParent().isAssign()) {
updateSimpleDeclaration(
appendPropForAlias(alias, p.getBaseName()), p, p.getDeclaration());
}
}
}
}
/**
* Updates the initial assignment to a collapsible property at global scope
* by changing it to a variable declaration (e.g. a.b = 1 -> var a$b = 1).
* The property's value may either be a primitive or an object literal or
* function whose properties aren't collapsible.
*
* @param alias The flattened property name (e.g. "a$b")
* @param refName The name for the reference being updated.
* @param ref An object containing information about the assignment getting
* updated
*/
private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
Node rvalue = ref.node.getNext();
Node parent = ref.node.getParent();
Node gramps = parent.getParent();
Node greatGramps = gramps.getParent();
if (rvalue != null && rvalue.isFunction()) {
checkForHosedThisReferences(rvalue, refName.docInfo, refName);
}
// Create the new alias node.
Node nameNode = NodeUtil.newName(
compiler.getCodingConvention(), alias, gramps.getFirstChild(),
refName.getFullName());
NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);
if (gramps.isExprResult()) {
// BEFORE: a.b.c = ...;
// exprstmt
// assign
// getprop
// getprop
// name a
// string b
// string c
// NODE
// AFTER: var a$b$c = ...;
// var
// name a$b$c
// NODE
// Remove the r-value (NODE).
parent.removeChild(rvalue);
nameNode.addChildToFront(rvalue);
Node varNode = IR.var(nameNode);
greatGramps.replaceChild(gramps, varNode);
} else {
// This must be a complex assignment.
Preconditions.checkNotNull(ref.getTwin());
// BEFORE:
// ... (x.y = 3);
//
// AFTER:
// var x$y;
// ... (x$y = 3);
Node current = gramps;
Node currentParent = gramps.getParent();
for (; !currentParent.isScript() &&
!currentParent.isBlock();
current = currentParent,
currentParent = currentParent.getParent()) {}
// Create a stub variable declaration right
// before the current statement.
Node stubVar = IR.var(nameNode.cloneTree())
.copyInformationFrom(nameNode);
currentParent.addChildBefore(stubVar, current);
parent.replaceChild(ref.node, nameNode);
}
compiler.reportCodeChange();
}
/**
* Updates the first initialization (a.k.a "declaration") of a global name.
* This involves flattening the global name (if it's not just a global
* variable name already), collapsing object literal keys into global
* variables, declaring stub global variables for properties added later
* in a local scope.
*
* It may seem odd that this function also takes care of declaring stubs
* for direct children. The ultimate goal of this function is to eliminate
* the global name entirely (when possible), so that "middlemen" namespaces
* disappear, and to do that we need to make sure that all the direct children
* will be collapsed as well.
*
* @param n An object representing a global name (e.g. "a", "a.b.c")
* @param alias The flattened name for {@code n} (e.g. "a", "a$b$c")
* @param canCollapseChildNames Whether it's possible to collapse children of
* this name. (This is mostly passed for convenience; it's equivalent to
* n.canCollapseChildNames()).
*/
private void updateObjLitOrFunctionDeclaration(
Name n, String alias, boolean canCollapseChildNames) {
Ref decl = n.getDeclaration();
if (decl == null) {
// Some names do not have declarations, because they
// are only defined in local scopes.
return;
}
if (decl.getTwin() != null) {
// Twin declarations will get handled when normal references
// are handled.
return;
}
switch (decl.node.getParent().getType()) {
case Token.ASSIGN:
updateObjLitOrFunctionDeclarationAtAssignNode(
n, alias, canCollapseChildNames);
break;
case Token.VAR:
updateObjLitOrFunctionDeclarationAtVarNode(n, canCollapseChildNames);
break;
case Token.FUNCTION:
updateFunctionDeclarationAtFunctionNode(n, canCollapseChildNames);
break;
}
}
/**
* Updates the first initialization (a.k.a "declaration") of a global name
* that occurs at an ASSIGN node. See comment for
* {@link #updateObjLitOrFunctionDeclaration}.
*
* @param n An object representing a global name (e.g. "a", "a.b.c")
* @param alias The flattened name for {@code n} (e.g. "a", "a$b$c")
*/
private void updateObjLitOrFunctionDeclarationAtAssignNode(
Name n, String alias, boolean canCollapseChildNames) {
// NOTE: It's important that we don't add additional nodes
// (e.g. a var node before the exprstmt) because the exprstmt might be
// the child of an if statement that's not inside a block).
Ref ref = n.getDeclaration();
Node rvalue = ref.node.getNext();
Node varNode = new Node(Token.VAR);
Node varParent = ref.node.getAncestor(3);
Node gramps = ref.node.getAncestor(2);
boolean isObjLit = rvalue.isObjectLit();
boolean insertedVarNode = false;
if (isObjLit && n.canEliminate()) {
// Eliminate the object literal altogether.
varParent.replaceChild(gramps, varNode);
ref.node = null;
insertedVarNode = true;
} else if (!n.isSimpleName()) {
// Create a VAR node to declare the name.
if (rvalue.isFunction()) {
checkForHosedThisReferences(rvalue, n.docInfo, n);
}
ref.node.getParent().removeChild(rvalue);
Node nameNode = NodeUtil.newName(
compiler.getCodingConvention(),
alias, ref.node.getAncestor(2), n.getFullName());
JSDocInfo info = ref.node.getParent().getJSDocInfo();
if (ref.node.getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME) ||
(info != null && info.isConstant())) {
nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
if (info != null) {
varNode.setJSDocInfo(info);
}
varNode.addChildToBack(nameNode);
nameNode.addChildToFront(rvalue);
varParent.replaceChild(gramps, varNode);
// Update the node ancestry stored in the reference.
ref.node = nameNode;
insertedVarNode = true;
}
if (canCollapseChildNames) {
if (isObjLit) {
declareVarsForObjLitValues(
n, alias, rvalue,
varNode, varParent.getChildBefore(varNode), varParent);
}
addStubsForUndeclaredProperties(n, alias, varParent, varNode);
}
if (insertedVarNode) {
if (!varNode.hasChildren()) {
varParent.removeChild(varNode);
}
compiler.reportCodeChange();
}
}
/**
* Warns about any references to "this" in the given FUNCTION. The function
* is getting collapsed, so the references will change.
*/
private void checkForHosedThisReferences(Node function, JSDocInfo docInfo,
final Name name) {
// A function is getting collapsed. Make sure that if it refers to
// "this", it must be a constructor or documented with @this.
if (docInfo == null ||
(!docInfo.isConstructor() && !docInfo.hasThisType())) {
NodeTraversal.traverse(compiler, function.getLastChild(),
new NodeTraversal.AbstractShallowCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isThis()) {
compiler.report(
JSError.make(name.getDeclaration().getSourceName(), n,
UNSAFE_THIS, name.getFullName()));
}
}
});
}
}
/**
* Updates the first initialization (a.k.a "declaration") of a global name
* that occurs at a VAR node. See comment for
* {@link #updateObjLitOrFunctionDeclaration}.
*
* @param n An object representing a global name (e.g. "a")
*/
private void updateObjLitOrFunctionDeclarationAtVarNode(
Name n, boolean canCollapseChildNames) {
if (!canCollapseChildNames) {
return;
}
Ref ref = n.getDeclaration();
String name = ref.node.getString();
Node rvalue = ref.node.getFirstChild();
Node varNode = ref.node.getParent();
Node gramps = varNode.getParent();
boolean isObjLit = rvalue.isObjectLit();
int numChanges = 0;
if (isObjLit) {
numChanges += declareVarsForObjLitValues(
n, name, rvalue, varNode, gramps.getChildBefore(varNode),
gramps);
}
numChanges += addStubsForUndeclaredProperties(n, name, gramps, varNode);
if (isObjLit && n.canEliminate()) {
varNode.removeChild(ref.node);
if (!varNode.hasChildren()) {
gramps.removeChild(varNode);
}
numChanges++;
// Clear out the object reference, since we've eliminated it from the
// parse tree.
ref.node = null;
}
if (numChanges > 0) {
compiler.reportCodeChange();
}
}
/**
* Updates the first initialization (a.k.a "declaration") of a global name
* that occurs at a FUNCTION node. See comment for
* {@link #updateObjLitOrFunctionDeclaration}.
*
* @param n An object representing a global name (e.g. "a")
*/
private void updateFunctionDeclarationAtFunctionNode(
Name n, boolean canCollapseChildNames) {
if (!canCollapseChildNames) {
return;
}
Ref ref = n.getDeclaration();
String fnName = ref.node.getString();
addStubsForUndeclaredProperties(
n, fnName, ref.node.getAncestor(2), ref.node.getParent());
}
/**
* Declares global variables to serve as aliases for the values in an object
* literal, optionally removing all of the object literal's keys and values.
*
* @param alias The object literal's flattened name (e.g. "a$b$c")
* @param objlit The OBJLIT node
* @param varNode The VAR node to which new global variables should be added
* as children
* @param nameToAddAfter The child of {@code varNode} after which new
* variables should be added (may be null)
* @param varParent {@code varNode}'s parent
* @return The number of variables added
*/
private int declareVarsForObjLitValues(
Name objlitName, String alias, Node objlit, Node varNode,
Node nameToAddAfter, Node varParent) {
int numVars = 0;
int arbitraryNameCounter = 0;
boolean discardKeys = !objlitName.shouldKeepKeys();
for (Node key = objlit.getFirstChild(), nextKey; key != null;
key = nextKey) {
Node value = key.getFirstChild();
nextKey = key.getNext();
// A get or a set can not be rewritten as a VAR.
if (key.isGetterDef() || key.isSetterDef()) {
continue;
}
// We generate arbitrary names for keys that aren't valid JavaScript
// identifiers, since those keys are never referenced. (If they were,
// this object literal's child names wouldn't be collapsible.) The only
// reason that we don't eliminate them entirely is the off chance that
// their values are expressions that have side effects.
boolean isJsIdentifier = !key.isNumber() &&
TokenStream.isJSIdentifier(key.getString());
String propName = isJsIdentifier ?
key.getString() : String.valueOf(++arbitraryNameCounter);
// If the name cannot be collapsed, skip it.
String qName = objlitName.getFullName() + '.' + propName;
Name p = nameMap.get(qName);
if (p != null && !p.canCollapse()) {
continue;
}
String propAlias = appendPropForAlias(alias, propName);
Node refNode = null;
if (discardKeys) {
objlit.removeChild(key);
value.detachFromParent();
} else {
// Substitute a reference for the value.
refNode = IR.name(propAlias);
if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) {
refNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
key.replaceChild(value, refNode);
}
// Declare the collapsed name as a variable with the original value.
Node nameNode = IR.name(propAlias);
nameNode.addChildToFront(value);
if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) {
nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
Node newVar = IR.var(nameNode)
.copyInformationFromForTree(key);
if (nameToAddAfter != null) {
varParent.addChildAfter(newVar, nameToAddAfter);
} else {
varParent.addChildBefore(newVar, varNode);
}
compiler.reportCodeChange();
nameToAddAfter = newVar;
// Update the global name's node ancestry if it hasn't already been
// done. (Duplicate keys in an object literal can bring us here twice
// for the same global name.)
if (isJsIdentifier && p != null) {
if (!discardKeys) {
Ref newAlias =
p.getDeclaration().cloneAndReclassify(Ref.Type.ALIASING_GET);
newAlias.node = refNode;
p.addRef(newAlias);
}
p.getDeclaration().node = nameNode;
if (value.isFunction()) {
checkForHosedThisReferences(value, value.getJSDocInfo(), p);
}
}
numVars++;
}
return numVars;
}
/**
* Adds global variable "stubs" for any properties of a global name that are
* only set in a local scope or read but never set.
*
* @param n An object representing a global name (e.g. "a", "a.b.c")
* @param alias The flattened name of the object whose properties we are
* adding stubs for (e.g. "a$b$c")
* @param parent The node to which new global variables should be added
* as children
* @param addAfter The child of after which new
* variables should be added (may be null)
* @return The number of variables added
*/
private int addStubsForUndeclaredProperties(
Name n, String alias, Node parent, Node addAfter) {
Preconditions.checkState(n.canCollapseUnannotatedChildNames());
Preconditions.checkArgument(NodeUtil.isStatementBlock(parent));
Preconditions.checkNotNull(addAfter);
int numStubs = 0;
if (n.props != null) {
for (Name p : n.props) {
if (p.needsToBeStubbed()) {
String propAlias = appendPropForAlias(alias, p.getBaseName());
Node nameNode = IR.name(propAlias);
Node newVar = IR.var(nameNode)
.copyInformationFromForTree(addAfter);
parent.addChildAfter(newVar, addAfter);
addAfter = newVar;
numStubs++;
compiler.reportCodeChange();
// Determine if this is a constant var by checking the first
// reference to it. Don't check the declaration, as it might be null.
if (p.getRefs().get(0).node.getLastChild().getBooleanProp(
Node.IS_CONSTANT_NAME)) {
nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
}
}
}
}
return numStubs;
}
private static String appendPropForAlias(String root, String prop) {
if (prop.indexOf('$') != -1) {
// Encode '$' in a property as '$0'. Because '0' cannot be the
// start of an identifier, this will never conflict with our
// encoding from '.' -> '$'.
prop = prop.replace("$", "$0");
}
return root + '$' + prop;
}
}
| |
/*
* 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.accumulo.tserver.log;
import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_FINISH;
import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_START;
import static org.apache.accumulo.tserver.logger.LogEvents.DEFINE_TABLET;
import static org.apache.accumulo.tserver.logger.LogEvents.MANY_MUTATIONS;
import static org.apache.accumulo.tserver.logger.LogEvents.MUTATION;
import static org.apache.accumulo.tserver.logger.LogEvents.OPEN;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.tserver.logger.LogFileKey;
import org.apache.accumulo.tserver.logger.LogFileValue;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Extract Mutations for a tablet from a set of logs that have been sorted by operation and tablet.
*
*/
public class SortedLogRecovery {
private static final Logger log = LoggerFactory.getLogger(SortedLogRecovery.class);
static class EmptyMapFileException extends Exception {
private static final long serialVersionUID = 1L;
public EmptyMapFileException() {
super();
}
}
static class UnusedException extends Exception {
private static final long serialVersionUID = 1L;
public UnusedException() {
super();
}
}
private VolumeManager fs;
public SortedLogRecovery(VolumeManager fs) {
this.fs = fs;
}
private enum Status {
INITIAL, LOOKING_FOR_FINISH, COMPLETE
};
private static class LastStartToFinish {
long lastStart = -1;
long seq = -1;
long lastFinish = -1;
Status compactionStatus = Status.INITIAL;
String tserverSession = "";
private void update(long newFinish) {
this.seq = this.lastStart;
if (newFinish != -1)
lastFinish = newFinish;
}
private void update(int newStartFile, long newStart) {
this.lastStart = newStart;
}
private void update(String newSession) {
this.lastStart = -1;
this.lastFinish = -1;
this.compactionStatus = Status.INITIAL;
this.tserverSession = newSession;
}
}
public void recover(KeyExtent extent, List<Path> recoveryLogs, Set<String> tabletFiles, MutationReceiver mr) throws IOException {
int[] tids = new int[recoveryLogs.size()];
LastStartToFinish lastStartToFinish = new LastStartToFinish();
for (int i = 0; i < recoveryLogs.size(); i++) {
Path logfile = recoveryLogs.get(i);
log.info("Looking at mutations from " + logfile + " for " + extent);
MultiReader reader = new MultiReader(fs, logfile);
try {
try {
tids[i] = findLastStartToFinish(reader, i, extent, tabletFiles, lastStartToFinish);
} catch (EmptyMapFileException ex) {
log.info("Ignoring empty map file " + logfile);
tids[i] = -1;
} catch (UnusedException ex) {
log.info("Ignoring log file " + logfile + " appears to be unused by " + extent);
tids[i] = -1;
}
} finally {
try {
reader.close();
} catch (IOException ex) {
log.warn("Ignoring error closing file");
}
}
}
if (lastStartToFinish.compactionStatus == Status.LOOKING_FOR_FINISH)
throw new RuntimeException("COMPACTION_FINISH (without preceding COMPACTION_START) not followed by successful minor compaction");
for (int i = 0; i < recoveryLogs.size(); i++) {
Path logfile = recoveryLogs.get(i);
MultiReader reader = new MultiReader(fs, logfile);
try {
playbackMutations(reader, tids[i], lastStartToFinish, mr);
} finally {
try {
reader.close();
} catch (IOException ex) {
log.warn("Ignoring error closing file");
}
}
log.info("Recovery complete for " + extent + " using " + logfile);
}
}
private String getPathSuffix(String pathString) {
Path path = new Path(pathString);
if (path.depth() < 2)
throw new IllegalArgumentException("Bad path " + pathString);
return path.getParent().getName() + "/" + path.getName();
}
int findLastStartToFinish(MultiReader reader, int fileno, KeyExtent extent, Set<String> tabletFiles, LastStartToFinish lastStartToFinish) throws IOException,
EmptyMapFileException, UnusedException {
HashSet<String> suffixes = new HashSet<String>();
for (String path : tabletFiles)
suffixes.add(getPathSuffix(path));
// Scan for tableId for this extent (should always be in the log)
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
int tid = -1;
if (!reader.next(key, value))
throw new EmptyMapFileException();
if (key.event != OPEN)
throw new RuntimeException("First log entry value is not OPEN");
if (key.tserverSession.compareTo(lastStartToFinish.tserverSession) != 0) {
if (lastStartToFinish.compactionStatus == Status.LOOKING_FOR_FINISH)
throw new RuntimeException("COMPACTION_FINISH (without preceding COMPACTION_START) is not followed by a successful minor compaction.");
lastStartToFinish.update(key.tserverSession);
}
KeyExtent alternative = extent;
if (extent.isRootTablet()) {
alternative = RootTable.OLD_EXTENT;
}
LogFileKey defineKey = null;
// find the maximum tablet id... because a tablet may leave a tserver and then come back, in which case it would have a different tablet id
// for the maximum tablet id, find the minimum sequence #... may be ok to find the max seq, but just want to make the code behave like it used to
while (reader.next(key, value)) {
// log.debug("Event " + key.event + " tablet " + key.tablet);
if (key.event != DEFINE_TABLET)
break;
if (key.tablet.equals(extent) || key.tablet.equals(alternative)) {
if (tid != key.tid) {
tid = key.tid;
defineKey = key;
key = new LogFileKey();
}
}
}
if (tid < 0) {
throw new UnusedException();
}
log.debug("Found tid, seq " + tid + " " + defineKey.seq);
// Scan start/stop events for this tablet
key = defineKey;
key.event = COMPACTION_START;
reader.seek(key);
while (reader.next(key, value)) {
// LogFileEntry.printEntry(entry);
if (key.tid != tid)
break;
if (key.event == COMPACTION_START) {
if (lastStartToFinish.compactionStatus == Status.INITIAL)
lastStartToFinish.compactionStatus = Status.COMPLETE;
if (key.seq <= lastStartToFinish.lastStart)
throw new RuntimeException("Sequence numbers are not increasing for start/stop events: " + key.seq + " vs " + lastStartToFinish.lastStart);
lastStartToFinish.update(fileno, key.seq);
// Tablet server finished the minor compaction, but didn't remove the entry from the METADATA table.
log.debug("minor compaction into " + key.filename + " finished, but was still in the METADATA");
if (suffixes.contains(getPathSuffix(key.filename)))
lastStartToFinish.update(-1);
} else if (key.event == COMPACTION_FINISH) {
if (key.seq <= lastStartToFinish.lastStart)
throw new RuntimeException("Sequence numbers are not increasing for start/stop events: " + key.seq + " vs " + lastStartToFinish.lastStart);
if (lastStartToFinish.compactionStatus == Status.INITIAL)
lastStartToFinish.compactionStatus = Status.LOOKING_FOR_FINISH;
else if (lastStartToFinish.lastFinish > lastStartToFinish.lastStart)
throw new RuntimeException("COMPACTION_FINISH does not have preceding COMPACTION_START event.");
else
lastStartToFinish.compactionStatus = Status.COMPLETE;
lastStartToFinish.update(key.seq);
} else
break;
}
return tid;
}
private void playbackMutations(MultiReader reader, int tid, LastStartToFinish lastStartToFinish, MutationReceiver mr) throws IOException {
LogFileKey key = new LogFileKey();
LogFileValue value = new LogFileValue();
// Playback mutations after the last stop to finish
log.info("Scanning for mutations starting at sequence number " + lastStartToFinish.seq + " for tid " + tid);
key.event = MUTATION;
key.tid = tid;
// the seq number for the minor compaction start is now the same as the
// last update made to memory. Scan up to that mutation, but not past it.
key.seq = lastStartToFinish.seq;
reader.seek(key);
while (true) {
if (!reader.next(key, value))
break;
if (key.tid != tid)
break;
if (key.event == MUTATION) {
mr.receive(value.mutations.get(0));
} else if (key.event == MANY_MUTATIONS) {
for (Mutation m : value.mutations) {
mr.receive(m);
}
} else {
throw new RuntimeException("unexpected log key type: " + key.event);
}
}
}
}
| |
/*
* 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.dubbo.common.extension;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.context.Lifecycle;
import org.apache.dubbo.common.extension.support.ActivateComparator;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX;
/**
*
* {@link org.apache.dubbo.rpc.model.ApplicationModel}, {@code DubboBootstrap} and this class are
* at present designed to be singleton or static (by itself totally static or uses some static fields).
* So the instances returned from them are of process or classloader scope. If you want to support
* multiple dubbo servers in a single process, you may need to refactor these three classes.
*
* Load dubbo extensions
* <ul>
* <li>auto inject dependency extension </li>
* <li>auto wrap extension in wrapper </li>
* <li>default extension is an adaptive instance</li>
* </ul>
*
* @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Service Provider in Java 5</a>
* @see org.apache.dubbo.common.extension.SPI
* @see org.apache.dubbo.common.extension.Adaptive
* @see org.apache.dubbo.common.extension.Activate
*/
public class ExtensionLoader<T> {
private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class);
private static final String SERVICES_DIRECTORY = "META-INF/services/";
private static final String DUBBO_DIRECTORY = "META-INF/dubbo/";
private static final String DUBBO_INTERNAL_DIRECTORY = DUBBO_DIRECTORY + "internal/";
private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");
private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<>();
private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<>();
private final Class<?> type;
private final ExtensionFactory objectFactory;
private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<>();
private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<>();
private final Map<String, Object> cachedActivates = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<>();
private final Holder<Object> cachedAdaptiveInstance = new Holder<>();
private volatile Class<?> cachedAdaptiveClass = null;
private String cachedDefaultName;
private volatile Throwable createAdaptiveInstanceError;
private Set<Class<?>> cachedWrapperClasses;
private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<>();
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
private static <T> boolean withExtensionAnnotation(Class<T> type) {
return type.isAnnotationPresent(SPI.class);
}
@SuppressWarnings("unchecked")
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
}
if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type (" + type +
") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}
// For testing purposes only
public static void resetExtensionLoader(Class type) {
ExtensionLoader loader = EXTENSION_LOADERS.get(type);
if (loader != null) {
// Remove all instances associated with this loader as well
Map<String, Class<?>> classes = loader.getExtensionClasses();
for (Map.Entry<String, Class<?>> entry : classes.entrySet()) {
EXTENSION_INSTANCES.remove(entry.getValue());
}
classes.clear();
EXTENSION_LOADERS.remove(type);
}
}
public static void destroyAll() {
EXTENSION_INSTANCES.forEach((_type, instance) -> {
if (instance instanceof Lifecycle) {
Lifecycle lifecycle = (Lifecycle) instance;
try {
lifecycle.destroy();
} catch (Exception e) {
logger.error("Error destroying extension " + lifecycle, e);
}
}
});
}
private static ClassLoader findClassLoader() {
return ClassUtils.getClassLoader(ExtensionLoader.class);
}
public String getExtensionName(T extensionInstance) {
return getExtensionName(extensionInstance.getClass());
}
public String getExtensionName(Class<?> extensionClass) {
getExtensionClasses();// load class
return cachedNames.get(extensionClass);
}
/**
* This is equivalent to {@code getActivateExtension(url, key, null)}
*
* @param url url
* @param key url parameter key which used to get extension point names
* @return extension list which are activated.
* @see #getActivateExtension(org.apache.dubbo.common.URL, String, String)
*/
public List<T> getActivateExtension(URL url, String key) {
return getActivateExtension(url, key, null);
}
/**
* This is equivalent to {@code getActivateExtension(url, values, null)}
*
* @param url url
* @param values extension point names
* @return extension list which are activated
* @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String)
*/
public List<T> getActivateExtension(URL url, String[] values) {
return getActivateExtension(url, values, null);
}
/**
* This is equivalent to {@code getActivateExtension(url, url.getParameter(key).split(","), null)}
*
* @param url url
* @param key url parameter key which used to get extension point names
* @param group group
* @return extension list which are activated.
* @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String)
*/
public List<T> getActivateExtension(URL url, String key, String group) {
String value = url.getParameter(key);
return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group);
}
/**
* Get activate extensions.
*
* @param url url
* @param values extension point names
* @param group group
* @return extension list which are activated
* @see org.apache.dubbo.common.extension.Activate
*/
public List<T> getActivateExtension(URL url, String[] values, String group) {
List<T> exts = new ArrayList<>();
List<String> names = values == null ? new ArrayList<>(0) : Arrays.asList(values);
if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) {
getExtensionClasses();
for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) {
String name = entry.getKey();
Object activate = entry.getValue();
String[] activateGroup, activateValue;
if (activate instanceof Activate) {
activateGroup = ((Activate) activate).group();
activateValue = ((Activate) activate).value();
} else if (activate instanceof com.alibaba.dubbo.common.extension.Activate) {
activateGroup = ((com.alibaba.dubbo.common.extension.Activate) activate).group();
activateValue = ((com.alibaba.dubbo.common.extension.Activate) activate).value();
} else {
continue;
}
if (isMatchGroup(group, activateGroup)
&& !names.contains(name)
&& !names.contains(REMOVE_VALUE_PREFIX + name)
&& isActive(activateValue, url)) {
exts.add(getExtension(name));
}
}
exts.sort(ActivateComparator.COMPARATOR);
}
List<T> usrs = new ArrayList<>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
if (!name.startsWith(REMOVE_VALUE_PREFIX)
&& !names.contains(REMOVE_VALUE_PREFIX + name)) {
if (DEFAULT_KEY.equals(name)) {
if (!usrs.isEmpty()) {
exts.addAll(0, usrs);
usrs.clear();
}
} else {
usrs.add(getExtension(name));
}
}
}
if (!usrs.isEmpty()) {
exts.addAll(usrs);
}
return exts;
}
private boolean isMatchGroup(String group, String[] groups) {
if (StringUtils.isEmpty(group)) {
return true;
}
if (groups != null && groups.length > 0) {
for (String g : groups) {
if (group.equals(g)) {
return true;
}
}
}
return false;
}
private boolean isActive(String[] keys, URL url) {
if (keys.length == 0) {
return true;
}
for (String key : keys) {
// @Active(value="key1:value1, key2:value2")
String keyValue = null;
if (key.contains(":")) {
String[] arr = key.split(":");
key = arr[0];
keyValue = arr[1];
}
for (Map.Entry<String, String> entry : url.getParameters().entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if ((k.equals(key) || k.endsWith("." + key))
&& ((keyValue != null && keyValue.equals(v)) || (keyValue == null && ConfigUtils.isNotEmpty(v)))) {
return true;
}
}
}
return false;
}
/**
* Get extension's instance. Return <code>null</code> if extension is not found or is not initialized. Pls. note
* that this method will not trigger extension load.
* <p>
* In order to trigger extension load, call {@link #getExtension(String)} instead.
*
* @see #getExtension(String)
*/
@SuppressWarnings("unchecked")
public T getLoadedExtension(String name) {
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
Holder<Object> holder = getOrCreateHolder(name);
return (T) holder.get();
}
private Holder<Object> getOrCreateHolder(String name) {
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<>());
holder = cachedInstances.get(name);
}
return holder;
}
/**
* Return the list of extensions which are already loaded.
* <p>
* Usually {@link #getSupportedExtensions()} should be called in order to get all extensions.
*
* @see #getSupportedExtensions()
*/
public Set<String> getLoadedExtensions() {
return Collections.unmodifiableSet(new TreeSet<>(cachedInstances.keySet()));
}
public List<T> getLoadedExtensionInstances() {
List<T> instances = new ArrayList<>();
cachedInstances.values().forEach(holder -> instances.add((T) holder.get()));
return instances;
}
public Object getLoadedAdaptiveExtensionInstances() {
return cachedAdaptiveInstance.get();
}
// public T getPrioritizedExtensionInstance() {
// Set<String> supported = getSupportedExtensions();
//
// Set<T> instances = new HashSet<>();
// Set<T> prioritized = new HashSet<>();
// for (String s : supported) {
//
// }
//
// }
/**
* Find the extension with the given name. If the specified name is not found, then {@link IllegalStateException}
* will be thrown.
*/
@SuppressWarnings("unchecked")
public T getExtension(String name) {
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
if ("true".equals(name)) {
return getDefaultExtension();
}
final Holder<Object> holder = getOrCreateHolder(name);
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
instance = holder.get();
if (instance == null) {
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
/**
* Get the extension by specified name if found, or {@link #getDefaultExtension() returns the default one}
*
* @param name the name of extension
* @return non-null
*/
public T getOrDefaultExtension(String name) {
return containsExtension(name) ? getExtension(name) : getDefaultExtension();
}
/**
* Return default extension, return <code>null</code> if it's not configured.
*/
public T getDefaultExtension() {
getExtensionClasses();
if (StringUtils.isBlank(cachedDefaultName) || "true".equals(cachedDefaultName)) {
return null;
}
return getExtension(cachedDefaultName);
}
public boolean hasExtension(String name) {
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
Class<?> c = this.getExtensionClass(name);
return c != null;
}
public Set<String> getSupportedExtensions() {
Map<String, Class<?>> clazzes = getExtensionClasses();
return Collections.unmodifiableSet(new TreeSet<>(clazzes.keySet()));
}
public Set<T> getSupportedExtensionInstances() {
Set<T> instances = new HashSet<>();
Set<String> supportedExtensions = getSupportedExtensions();
if (CollectionUtils.isNotEmpty(supportedExtensions)) {
for (String name : supportedExtensions) {
instances.add(getExtension(name));
}
}
return instances;
}
/**
* Return default extension name, return <code>null</code> if not configured.
*/
public String getDefaultExtensionName() {
getExtensionClasses();
return cachedDefaultName;
}
/**
* Register new extension via API
*
* @param name extension name
* @param clazz extension class
* @throws IllegalStateException when extension with the same name has already been registered.
*/
public void addExtension(String name, Class<?> clazz) {
getExtensionClasses(); // load classes
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Input type " +
clazz + " doesn't implement the Extension " + type);
}
if (clazz.isInterface()) {
throw new IllegalStateException("Input type " +
clazz + " can't be interface!");
}
if (!clazz.isAnnotationPresent(Adaptive.class)) {
if (StringUtils.isBlank(name)) {
throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
}
if (cachedClasses.get().containsKey(name)) {
throw new IllegalStateException("Extension name " +
name + " already exists (Extension " + type + ")!");
}
cachedNames.put(clazz, name);
cachedClasses.get().put(name, clazz);
} else {
if (cachedAdaptiveClass != null) {
throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!");
}
cachedAdaptiveClass = clazz;
}
}
/**
* Replace the existing extension via API
*
* @param name extension name
* @param clazz extension class
* @throws IllegalStateException when extension to be placed doesn't exist
* @deprecated not recommended any longer, and use only when test
*/
@Deprecated
public void replaceExtension(String name, Class<?> clazz) {
getExtensionClasses(); // load classes
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Input type " +
clazz + " doesn't implement Extension " + type);
}
if (clazz.isInterface()) {
throw new IllegalStateException("Input type " +
clazz + " can't be interface!");
}
if (!clazz.isAnnotationPresent(Adaptive.class)) {
if (StringUtils.isBlank(name)) {
throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
}
if (!cachedClasses.get().containsKey(name)) {
throw new IllegalStateException("Extension name " +
name + " doesn't exist (Extension " + type + ")!");
}
cachedNames.put(clazz, name);
cachedClasses.get().put(name, clazz);
cachedInstances.remove(name);
} else {
if (cachedAdaptiveClass == null) {
throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!");
}
cachedAdaptiveClass = clazz;
cachedAdaptiveInstance.set(null);
}
}
@SuppressWarnings("unchecked")
public T getAdaptiveExtension() {
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
if (createAdaptiveInstanceError != null) {
throw new IllegalStateException("Failed to create adaptive instance: " +
createAdaptiveInstanceError.toString(),
createAdaptiveInstanceError);
}
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
instance = createAdaptiveExtension();
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t);
}
}
}
}
return (T) instance;
}
private IllegalStateException findException(String name) {
for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) {
if (entry.getKey().toLowerCase().contains(name.toLowerCase())) {
return entry.getValue();
}
}
StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name);
int i = 1;
for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) {
if (i == 1) {
buf.append(", possible causes: ");
}
buf.append("\r\n(");
buf.append(i++);
buf.append(") ");
buf.append(entry.getKey());
buf.append(":\r\n");
buf.append(StringUtils.toString(entry.getValue()));
}
return new IllegalStateException(buf.toString());
}
@SuppressWarnings("unchecked")
private T createExtension(String name) {
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (CollectionUtils.isNotEmpty(wrapperClasses)) {
for (Class<?> wrapperClass : wrapperClasses) {
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
initExtension(instance);
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
type + ") couldn't be instantiated: " + t.getMessage(), t);
}
}
private boolean containsExtension(String name) {
return getExtensionClasses().containsKey(name);
}
private T injectExtension(T instance) {
if (objectFactory == null) {
return instance;
}
try {
for (Method method : instance.getClass().getMethods()) {
if (!isSetter(method)) {
continue;
}
/**
* Check {@link DisableInject} to see if we need auto injection for this property
*/
if (method.getAnnotation(DisableInject.class) != null) {
continue;
}
Class<?> pt = method.getParameterTypes()[0];
if (ReflectUtils.isPrimitives(pt)) {
continue;
}
try {
String property = getSetterProperty(method);
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
method.invoke(instance, object);
}
} catch (Exception e) {
logger.error("Failed to inject via method " + method.getName()
+ " of interface " + type.getName() + ": " + e.getMessage(), e);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return instance;
}
private void initExtension(T instance) {
if (instance instanceof Lifecycle) {
Lifecycle lifecycle = (Lifecycle) instance;
lifecycle.initialize();
}
}
/**
* get properties name for setter, for instance: setVersion, return "version"
* <p>
* return "", if setter name with length less than 3
*/
private String getSetterProperty(Method method) {
return method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
}
/**
* return true if and only if:
* <p>
* 1, public
* <p>
* 2, name starts with "set"
* <p>
* 3, only has one parameter
*/
private boolean isSetter(Method method) {
return method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers());
}
private Class<?> getExtensionClass(String name) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
if (name == null) {
throw new IllegalArgumentException("Extension name == null");
}
return getExtensionClasses().get(name);
}
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
/**
* synchronized in getExtensionClasses
* */
private Map<String, Class<?>> loadExtensionClasses() {
cacheDefaultExtensionName();
Map<String, Class<?>> extensionClasses = new HashMap<>();
// internal extension load from ExtensionLoader's ClassLoader first
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName(), true);
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"), true);
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName());
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName());
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
return extensionClasses;
}
/**
* extract and cache default extension name if exists
*/
private void cacheDefaultExtensionName() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation == null) {
return;
}
String value = defaultAnnotation.value();
if ((value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(value);
if (names.length > 1) {
throw new IllegalStateException("More than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if (names.length == 1) {
cachedDefaultName = names[0];
}
}
}
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) {
loadDirectory(extensionClasses, dir, type, false);
}
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type, boolean extensionLoaderClassLoaderFirst) {
String fileName = dir + type;
try {
Enumeration<java.net.URL> urls = null;
ClassLoader classLoader = findClassLoader();
// try to load from ExtensionLoader's ClassLoader first
if (extensionLoaderClassLoaderFirst) {
ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader();
if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) {
urls = extensionLoaderClassLoader.getResources(fileName);
}
}
if(urls == null || !urls.hasMoreElements()) {
if (classLoader != null) {
urls = classLoader.getResources(fileName);
} else {
urls = ClassLoader.getSystemResources(fileName);
}
}
if (urls != null) {
while (urls.hasMoreElements()) {
java.net.URL resourceURL = urls.nextElement();
loadResource(extensionClasses, classLoader, resourceURL);
}
}
} catch (Throwable t) {
logger.error("Exception occurred when loading extension class (interface: " +
type + ", description file: " + fileName + ").", t);
}
}
private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL) {
try {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
try {
String name = null;
int i = line.indexOf('=');
if (i > 0) {
name = line.substring(0, i).trim();
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name);
}
} catch (Throwable t) {
IllegalStateException e = new IllegalStateException("Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t);
exceptions.put(line, e);
}
}
}
}
} catch (Throwable t) {
logger.error("Exception occurred when loading extension class (interface: " +
type + ", class file: " + resourceURL + ") in " + resourceURL, t);
}
}
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException {
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error occurred when loading extension class (interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + " is not subtype of interface.");
}
if (clazz.isAnnotationPresent(Adaptive.class)) {
cacheAdaptiveClass(clazz);
} else if (isWrapperClass(clazz)) {
cacheWrapperClass(clazz);
} else {
clazz.getConstructor();
if (StringUtils.isEmpty(name)) {
name = findAnnotationName(clazz);
if (name.length() == 0) {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL);
}
}
String[] names = NAME_SEPARATOR.split(name);
if (ArrayUtils.isNotEmpty(names)) {
cacheActivateClass(clazz, names[0]);
for (String n : names) {
cacheName(clazz, n);
saveInExtensionClass(extensionClasses, clazz, n);
}
}
}
}
/**
* cache name
*/
private void cacheName(Class<?> clazz, String name) {
if (!cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, name);
}
}
/**
* put clazz in extensionClasses
*/
private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) {
Class<?> c = extensionClasses.get(name);
if (c == null) {
extensionClasses.put(name, clazz);
} else if (c != clazz) {
String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName();
logger.error(duplicateMsg);
throw new IllegalStateException(duplicateMsg);
}
}
/**
* cache Activate class which is annotated with <code>Activate</code>
* <p>
* for compatibility, also cache class with old alibaba Activate annotation
*/
private void cacheActivateClass(Class<?> clazz, String name) {
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
cachedActivates.put(name, activate);
} else {
// support com.alibaba.dubbo.common.extension.Activate
com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
if (oldActivate != null) {
cachedActivates.put(name, oldActivate);
}
}
}
/**
* cache Adaptive class which is annotated with <code>Adaptive</code>
*/
private void cacheAdaptiveClass(Class<?> clazz) {
if (cachedAdaptiveClass == null) {
cachedAdaptiveClass = clazz;
} else if (!cachedAdaptiveClass.equals(clazz)) {
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getName()
+ ", " + clazz.getName());
}
}
/**
* cache wrapper class
* <p>
* like: ProtocolFilterWrapper, ProtocolListenerWrapper
*/
private void cacheWrapperClass(Class<?> clazz) {
if (cachedWrapperClasses == null) {
cachedWrapperClasses = new ConcurrentHashSet<>();
}
cachedWrapperClasses.add(clazz);
}
/**
* test if clazz is a wrapper class
* <p>
* which has Constructor with given class type as its only argument
*/
private boolean isWrapperClass(Class<?> clazz) {
try {
clazz.getConstructor(type);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
@SuppressWarnings("deprecation")
private String findAnnotationName(Class<?> clazz) {
org.apache.dubbo.common.Extension extension = clazz.getAnnotation(org.apache.dubbo.common.Extension.class);
if (extension != null) {
return extension.value();
}
String name = clazz.getSimpleName();
if (name.endsWith(type.getSimpleName())) {
name = name.substring(0, name.length() - type.getSimpleName().length());
}
return name.toLowerCase();
}
@SuppressWarnings("unchecked")
private T createAdaptiveExtension() {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
private Class<?> createAdaptiveExtensionClass() {
String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate();
ClassLoader classLoader = findClassLoader();
org.apache.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
return compiler.compile(code, classLoader);
}
@Override
public String toString() {
return this.getClass().getName() + "[" + type.getName() + "]";
}
}
| |
/*
* 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 sa.com.is.filter;
import java.math.BigInteger;
import java.nio.charset.Charset;
/**
* Provides Base64 encoding and decoding as defined by RFC 2045.
*
* <p>
* This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @author Apache Software Foundation
* @since 1.0-dev
* @version $Id$
*/
public class Base64 {
public static String decode(String encoded) {
if (encoded == null) {
return null;
}
byte[] decoded = new Base64().decode(encoded.getBytes());
return new String(decoded);
}
public static String encode(String s) {
if (s == null) {
return null;
}
byte[] encoded = new Base64().encode(s.getBytes());
return new String(encoded);
}
/**
* Chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
static final int CHUNK_SIZE = 76;
/**
* Chunk separator per RFC 2045 section 2.1.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
*/
static final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in Table 1 of RFC 2045.
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] intToBase64 = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/**
* Byte used to pad output.
*/
private static final byte PAD = '=';
/**
* This array is a lookup table that translates unicode characters
* drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
* into their 6-bit positive integer equivalents. Characters that
* are not in the Base64 alphabet but fall within the bounds of the
* array are translated to -1.
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] base64ToInt = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
/** Mask used to extract 6 bits, used when encoding */
private static final int MASK_6BITS = 0x3f;
/** Mask used to extract 8 bits, used in decoding base64 bytes */
private static final int MASK_8BITS = 0xff;
// The static final fields above are used for the original static byte[] methods on Base64.
// The private member fields below are used with the new streaming approach, which requires
// some state be preserved between calls of encode() and decode().
/**
* Line length for encoding. Not used when decoding. A value of zero or less implies
* no chunking of the base64 encoded data.
*/
private final int lineLength;
/**
* Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
*/
private final byte[] lineSeparator;
/**
* Convenience variable to help us determine when our buffer is going to run out of
* room and needs resizing. <code>decodeSize = 3 + lineSeparator.length;</code>
*/
private final int decodeSize;
/**
* Convenience variable to help us determine when our buffer is going to run out of
* room and needs resizing. <code>encodeSize = 4 + lineSeparator.length;</code>
*/
private final int encodeSize;
/**
* Buffer for streaming.
*/
private byte[] buf;
/**
* Position where next character should be written in the buffer.
*/
private int pos;
/**
* Position where next character should be read from the buffer.
*/
private int readPos;
/**
* Variable tracks how many characters have been written to the current line.
* Only used when encoding. We use it to make sure each encoded line never
* goes beyond lineLength (if lineLength > 0).
*/
private int currentLinePos;
/**
* Writes to the buffer only occur after every 3 reads when encoding, an
* every 4 reads when decoding. This variable helps track that.
*/
private int modulus;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been
* reached, this Base64 object becomes useless, and must be thrown away.
*/
private boolean eof;
/**
* Place holder for the 3 bytes we're dealing with for our base64 logic.
* Bitwise operations store and extract the base64 encoding or decoding from
* this variable.
*/
private int x;
/**
* Default constructor: lineLength is 76, and the lineSeparator is CRLF
* when encoding, and all forms can be decoded.
*/
public Base64() {
this(CHUNK_SIZE, CHUNK_SEPARATOR);
}
/**
* <p>
* Consumer can use this constructor to choose a different lineLength
* when encoding (lineSeparator is still CRLF). All forms of data can
* be decoded.
* </p><p>
* Note: lineLengths that aren't multiples of 4 will still essentially
* end up being multiples of 4 in the encoded data.
* </p>
*
* @param lineLength each line of encoded data will be at most this long
* (rounded up to nearest multiple of 4).
* If lineLength <= 0, then the output will not be divided into lines (chunks).
* Ignored when decoding.
*/
public Base64(int lineLength) {
this(lineLength, CHUNK_SEPARATOR);
}
/**
* <p>
* Consumer can use this constructor to choose a different lineLength
* and lineSeparator when encoding. All forms of data can
* be decoded.
* </p><p>
* Note: lineLengths that aren't multiples of 4 will still essentially
* end up being multiples of 4 in the encoded data.
* </p>
* @param lineLength Each line of encoded data will be at most this long
* (rounded up to nearest multiple of 4). Ignored when decoding.
* If <= 0, then output will not be divided into lines (chunks).
* @param lineSeparator Each line of encoded data will end with this
* sequence of bytes.
* If lineLength <= 0, then the lineSeparator is not used.
* @throws IllegalArgumentException The provided lineSeparator included
* some base64 characters. That's not going to work!
*/
public Base64(int lineLength, byte[] lineSeparator) {
this.lineLength = lineLength;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
if (lineLength > 0) {
this.encodeSize = 4 + lineSeparator.length;
} else {
this.encodeSize = 4;
}
this.decodeSize = encodeSize - 1;
if (containsBase64Byte(lineSeparator)) {
String sep = new String(lineSeparator, Charset.forName("UTF-8"));
throw new IllegalArgumentException("lineSeperator must not contain base64 characters: [" + sep + "]");
}
}
/**
* Returns true if this Base64 object has buffered data for reading.
*
* @return true if there is Base64 object still available for reading.
*/
boolean hasData() {
return buf != null;
}
/**
* Returns the amount of buffered data available for reading.
*
* @return The amount of buffered data available for reading.
*/
int avail() {
return buf != null ? pos - readPos : 0;
}
/** Doubles our buffer. */
private void resizeBuf() {
if (buf == null) {
buf = new byte[8192];
pos = 0;
readPos = 0;
} else {
byte[] b = new byte[buf.length * 2];
System.arraycopy(buf, 0, b, 0, buf.length);
buf = b;
}
}
/**
* Extracts buffered data into the provided byte[] array, starting
* at position bPos, up to a maximum of bAvail bytes. Returns how
* many bytes were actually extracted.
*
* @param b byte[] array to extract the buffered data into.
* @param bPos position in byte[] array to start extraction at.
* @param bAvail amount of bytes we're allowed to extract. We may extract
* fewer (if fewer are available).
* @return The number of bytes successfully extracted into the provided
* byte[] array.
*/
int readResults(byte[] b, int bPos, int bAvail) {
if (buf != null) {
int len = Math.min(avail(), bAvail);
if (buf != b) {
System.arraycopy(buf, readPos, b, bPos, len);
readPos += len;
if (readPos >= pos) {
buf = null;
}
} else {
// Re-using the original consumer's output array is only
// allowed for one round.
buf = null;
}
return len;
} else {
return eof ? -1 : 0;
}
}
/**
* Small optimization where we try to buffer directly to the consumer's
* output array for one round (if consumer calls this method first!) instead
* of starting our own buffer.
*
* @param out byte[] array to buffer directly to.
* @param outPos Position to start buffering into.
* @param outAvail Amount of bytes available for direct buffering.
*/
void setInitialBuffer(byte[] out, int outPos, int outAvail) {
// We can re-use consumer's original output array under
// special circumstances, saving on some System.arraycopy().
if (out != null && out.length == outAvail) {
buf = out;
pos = outPos;
readPos = outPos;
}
}
/**
* <p>
* Encodes all of the provided data, starting at inPos, for inAvail bytes.
* Must be called at least twice: once with the data to encode, and once
* with inAvail set to "-1" to alert encoder that EOF has been reached,
* so flush last remaining bytes (if not multiple of 3).
* </p><p>
* Thanks to "commons" project in ws.apache.org for the bitwise operations,
* and general approach.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* </p>
*
* @param in byte[] array of binary data to base64 encode.
* @param inPos Position to start reading data from.
* @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) {
if (eof) {
return;
}
// inAvail < 0 is how we're informed of EOF in the underlying data we're
// encoding.
if (inAvail < 0) {
eof = true;
if (buf == null || buf.length - pos < encodeSize) {
resizeBuf();
}
switch (modulus) {
case 1:
buf[pos++] = intToBase64[(x >> 2) & MASK_6BITS];
buf[pos++] = intToBase64[(x << 4) & MASK_6BITS];
buf[pos++] = PAD;
buf[pos++] = PAD;
break;
case 2:
buf[pos++] = intToBase64[(x >> 10) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 4) & MASK_6BITS];
buf[pos++] = intToBase64[(x << 2) & MASK_6BITS];
buf[pos++] = PAD;
break;
}
if (lineLength > 0) {
System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
pos += lineSeparator.length;
}
} else {
for (int i = 0; i < inAvail; i++) {
if (buf == null || buf.length - pos < encodeSize) {
resizeBuf();
}
modulus = (++modulus) % 3;
int b = in[inPos++];
if (b < 0) {
b += 256;
}
x = (x << 8) + b;
if (0 == modulus) {
buf[pos++] = intToBase64[(x >> 18) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 12) & MASK_6BITS];
buf[pos++] = intToBase64[(x >> 6) & MASK_6BITS];
buf[pos++] = intToBase64[x & MASK_6BITS];
currentLinePos += 4;
if (lineLength > 0 && lineLength <= currentLinePos) {
System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
pos += lineSeparator.length;
currentLinePos = 0;
}
}
}
}
}
/**
* <p>
* Decodes all of the provided data, starting at inPos, for inAvail bytes.
* Should be called at least twice: once with the data to decode, and once
* with inAvail set to "-1" to alert decoder that EOF has been reached.
* The "-1" call is not necessary when decoding, but it doesn't hurt, either.
* </p><p>
* Ignores all non-base64 characters. This is how chunked (e.g. 76 character)
* data is handled, since CR and LF are silently ignored, but has implications
* for other bytes, too. This method subscribes to the garbage-in, garbage-out
* philosophy: it will not check the provided data for validity.
* </p><p>
* Thanks to "commons" project in ws.apache.org for the bitwise operations,
* and general approach.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* </p>
* @param in byte[] array of ascii data to base64 decode.
* @param inPos Position to start reading data from.
* @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
return;
}
if (inAvail < 0) {
eof = true;
}
for (int i = 0; i < inAvail; i++) {
if (buf == null || buf.length - pos < decodeSize) {
resizeBuf();
}
byte b = in[inPos++];
if (b == PAD) {
x = x << 6;
switch (modulus) {
case 2:
x = x << 6;
buf[pos++] = (byte)((x >> 16) & MASK_8BITS);
break;
case 3:
buf[pos++] = (byte)((x >> 16) & MASK_8BITS);
buf[pos++] = (byte)((x >> 8) & MASK_8BITS);
break;
}
// WE'RE DONE!!!!
eof = true;
return;
} else {
if (b >= 0 && b < base64ToInt.length) {
int result = base64ToInt[b];
if (result >= 0) {
modulus = (++modulus) % 4;
x = (x << 6) + result;
if (modulus == 0) {
buf[pos++] = (byte)((x >> 16) & MASK_8BITS);
buf[pos++] = (byte)((x >> 8) & MASK_8BITS);
buf[pos++] = (byte)(x & MASK_8BITS);
}
}
}
}
}
}
/**
* Returns whether or not the <code>octet</code> is in the base 64 alphabet.
*
* @param octet
* The value to test
* @return <code>true</code> if the value is defined in the the base 64 alphabet, <code>false</code> otherwise.
*/
public static boolean isBase64(byte octet) {
return octet == PAD || (octet >= 0 && octet < base64ToInt.length && base64ToInt[octet] != -1);
}
/**
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
* Currently the method treats whitespace as valid.
*
* @param arrayOctet
* byte array to test
* @return <code>true</code> if all bytes are valid characters in the Base64 alphabet or if the byte array is
* empty; false, otherwise
*/
public static boolean isArrayByteBase64(byte[] arrayOctet) {
for (byte anArrayOctet : arrayOctet) {
if (!isBase64(anArrayOctet) && !isWhiteSpace(anArrayOctet)) {
return false;
}
}
return true;
}
/*
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.
*
* @param arrayOctet
* byte array to test
* @return <code>true</code> if any byte is a valid character in the Base64 alphabet; false herwise
*/
private static boolean containsBase64Byte(byte[] arrayOctet) {
for (byte element : arrayOctet) {
if (isBase64(element)) {
return true;
}
}
return false;
}
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
*
* @param binaryData
* binary data to encode
* @return Base64 characters
*/
public static byte[] encodeBase64(byte[] binaryData) {
return encodeBase64(binaryData, false);
}
/**
* Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks
*
* @param binaryData
* binary data to encode
* @return Base64 characters chunked in 76 character blocks
*/
public static byte[] encodeBase64Chunked(byte[] binaryData) {
return encodeBase64(binaryData, true);
}
/**
* Decodes an Object using the base64 algorithm. This method is provided in order to satisfy the requirements of the
* Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[].
*
* @param pObject
* Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] supplied.
* @throws DecoderException
* if the parameter supplied is not of type byte[]
*/
public Object decode(Object pObject) throws DecoderException {
if (!(pObject instanceof byte[])) {
throw new DecoderException("Parameter supplied to Base64 decode is not a byte[]");
}
return decode((byte[]) pObject);
}
/**
* Decodes a byte[] containing containing characters in the Base64 alphabet.
*
* @param pArray
* A byte array containing Base64 character data
* @return a byte array containing binary data
*/
public byte[] decode(byte[] pArray) {
return decodeBase64(pArray);
}
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
* @param binaryData
* Array containing binary data to encode.
* @param isChunked
* if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
* @return Base64-encoded data.
* @throws IllegalArgumentException
* Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE}
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
if (binaryData == null || binaryData.length == 0) {
return binaryData;
}
Base64 b64 = isChunked ? new Base64() : new Base64(0);
long len = (binaryData.length * 4) / 3;
long mod = len % 4;
if (mod != 0) {
len += 4 - mod;
}
if (isChunked) {
len += (1 + (len / CHUNK_SIZE)) * CHUNK_SEPARATOR.length;
}
if (len > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"Input array too big, output array would be bigger than Integer.MAX_VALUE=" + Integer.MAX_VALUE);
}
byte[] buf = new byte[(int) len];
b64.setInitialBuffer(buf, 0, buf.length);
b64.encode(binaryData, 0, binaryData.length);
b64.encode(binaryData, 0, -1); // Notify encoder of EOF.
// Encoder might have resized, even though it was unnecessary.
if (b64.buf != buf) {
b64.readResults(buf, 0, buf.length);
}
return buf;
}
/**
* Decodes Base64 data into octets
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
if (base64Data == null || base64Data.length == 0) {
return base64Data;
}
Base64 b64 = new Base64();
long len = (base64Data.length * 3) / 4;
byte[] buf = new byte[(int) len];
b64.setInitialBuffer(buf, 0, buf.length);
b64.decode(base64Data, 0, base64Data.length);
b64.decode(base64Data, 0, -1); // Notify decoder of EOF.
// We have no idea what the line-length was, so we
// cannot know how much of our array wasn't used.
byte[] result = new byte[b64.pos];
b64.readResults(result, 0, result.length);
return result;
}
/**
* Check if a byte value is whitespace or not.
*
* @param byteToCheck the byte to check
* @return true if byte is whitespace, false otherwise
*/
private static boolean isWhiteSpace(byte byteToCheck) {
switch (byteToCheck) {
case ' ' :
case '\n' :
case '\r' :
case '\t' :
return true;
default :
return false;
}
}
/**
* Discards any characters outside of the base64 alphabet, per the requirements on page 25 of RFC 2045 - "Any
* characters outside of the base64 alphabet are to be ignored in base64 encoded data."
*
* @param data
* The base-64 encoded data to groom
* @return The data, less non-base64 characters (see RFC 2045).
*/
static byte[] discardNonBase64(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (byte element : data) {
if (isBase64(element)) {
groomedData[bytesCopied++] = element;
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
// Implementation of the Encoder Interface
/**
* Encodes an Object using the base64 algorithm. This method is provided in order to satisfy the requirements of the
* Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
* @param pObject
* Object to encode
* @return An object (of type byte[]) containing the base64 encoded data which corresponds to the byte[] supplied.
* @throws EncoderException
* if the parameter supplied is not of type byte[]
*/
public Object encode(Object pObject) throws EncoderException {
if (!(pObject instanceof byte[])) {
throw new EncoderException("Parameter supplied to Base64 encode is not a byte[]");
}
return encode((byte[]) pObject);
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the Base64 alphabet.
*
* @param pArray
* a byte array containing binary data
* @return A byte array containing only Base64 character data
*/
public byte[] encode(byte[] pArray) {
return encodeBase64(pArray, false);
}
// Implementation of integer encoding used for crypto
/**
* Decode a byte64-encoded integer according to crypto
* standards such as W3C's XML-Signature
*
* @param pArray a byte array containing base64 character data
* @return A BigInteger
*/
public static BigInteger decodeInteger(byte[] pArray) {
return new BigInteger(1, decodeBase64(pArray));
}
/**
* Encode to a byte64-encoded integer according to crypto
* standards such as W3C's XML-Signature
*
* @param bigInt a BigInteger
* @return A byte array containing base64 character data
* @throws NullPointerException if null is passed in
*/
public static byte[] encodeInteger(BigInteger bigInt) {
if (bigInt == null) {
throw new NullPointerException("encodeInteger called with null parameter");
}
return encodeBase64(toIntegerBytes(bigInt), false);
}
/**
* Returns a byte-array representation of a <code>BigInteger</code>
* without sign bit.
*
* @param bigInt <code>BigInteger</code> to be converted
* @return a byte array representation of the BigInteger parameter
*/
static byte[] toIntegerBytes(BigInteger bigInt) {
int bitlen = bigInt.bitLength();
// round bitlen
bitlen = ((bitlen + 7) >> 3) << 3;
byte[] bigBytes = bigInt.toByteArray();
if (((bigInt.bitLength() % 8) != 0) &&
(((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
return bigBytes;
}
// set up params for copying everything but sign bit
int startSrc = 0;
int len = bigBytes.length;
// if bigInt is exactly byte-aligned, just skip signbit in copy
if ((bigInt.bitLength() % 8) == 0) {
startSrc = 1;
len--;
}
int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
byte[] resizedBytes = new byte[bitlen / 8];
System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
return resizedBytes;
}
static class DecoderException extends Exception {
private static final long serialVersionUID = -3786485780312120437L;
DecoderException(String error) {
super(error);
}
}
static class EncoderException extends Exception {
private static final long serialVersionUID = -5204809025392124652L;
EncoderException(String error) {
super(error);
}
}
}
| |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.provider.Settings;
import android.util.Printer;
import com.android.internal.util.FastPrintWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Describes an application error.
*
* A report has a type, which is one of
* <ul>
* <li> {@link #TYPE_NONE} uninitialized instance of {@link ApplicationErrorReport}.
* <li> {@link #TYPE_CRASH} application crash. Information about the crash
* is stored in {@link #crashInfo}.
* <li> {@link #TYPE_ANR} application not responding. Information about the
* ANR is stored in {@link #anrInfo}.
* <li> {@link #TYPE_BATTERY} user reported application is using too much
* battery. Information about the battery use is stored in {@link #batteryInfo}.
* <li> {@link #TYPE_RUNNING_SERVICE} user reported application is leaving an
* unneeded serive running. Information about the battery use is stored in
* {@link #runningServiceInfo}.
* </ul>
*/
public class ApplicationErrorReport implements Parcelable {
// System property defining error report receiver for system apps
static final String SYSTEM_APPS_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.system.apps";
// System property defining default error report receiver
static final String DEFAULT_ERROR_RECEIVER_PROPERTY = "ro.error.receiver.default";
/**
* Uninitialized error report.
*/
public static final int TYPE_NONE = 0;
/**
* An error report about an application crash.
*/
public static final int TYPE_CRASH = 1;
/**
* An error report about an application that's not responding.
*/
public static final int TYPE_ANR = 2;
/**
* An error report about an application that's consuming too much battery.
*/
public static final int TYPE_BATTERY = 3;
/**
* A report from a user to a developer about a running service that the
* user doesn't think should be running.
*/
public static final int TYPE_RUNNING_SERVICE = 5;
/**
* Type of this report. Can be one of {@link #TYPE_NONE},
* {@link #TYPE_CRASH}, {@link #TYPE_ANR}, {@link #TYPE_BATTERY},
* or {@link #TYPE_RUNNING_SERVICE}.
*/
public int type;
/**
* Package name of the application.
*/
public String packageName;
/**
* Package name of the application which installed the application this
* report pertains to.
* This identifies which market the application came from.
*/
public String installerPackageName;
/**
* Process name of the application.
*/
public String processName;
/**
* Time at which the error occurred.
*/
public long time;
/**
* Set if the app is on the system image.
*/
public boolean systemApp;
/**
* If this report is of type {@link #TYPE_CRASH}, contains an instance
* of CrashInfo describing the crash; otherwise null.
*/
public CrashInfo crashInfo;
/**
* If this report is of type {@link #TYPE_ANR}, contains an instance
* of AnrInfo describing the ANR; otherwise null.
*/
public AnrInfo anrInfo;
/**
* If this report is of type {@link #TYPE_BATTERY}, contains an instance
* of BatteryInfo; otherwise null.
*/
public BatteryInfo batteryInfo;
/**
* If this report is of type {@link #TYPE_RUNNING_SERVICE}, contains an instance
* of RunningServiceInfo; otherwise null.
*/
public RunningServiceInfo runningServiceInfo;
/**
* Create an uninitialized instance of {@link ApplicationErrorReport}.
*/
public ApplicationErrorReport() {
}
/**
* Create an instance of {@link ApplicationErrorReport} initialized from
* a parcel.
*/
ApplicationErrorReport(Parcel in) {
readFromParcel(in);
}
public static ComponentName getErrorReportReceiver(Context context,
String packageName, int appFlags) {
// check if error reporting is enabled in secure settings
int enabled = Settings.Global.getInt(context.getContentResolver(),
Settings.Global.SEND_ACTION_APP_ERROR, 0);
if (enabled == 0) {
return null;
}
PackageManager pm = context.getPackageManager();
// look for receiver in the installer package
String candidate = pm.getInstallerPackageName(packageName);
ComponentName result = getErrorReportReceiver(pm, packageName, candidate);
if (result != null) {
return result;
}
// if the error app is on the system image, look for system apps
// error receiver
if ((appFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
candidate = SystemProperties.get(SYSTEM_APPS_ERROR_RECEIVER_PROPERTY);
result = getErrorReportReceiver(pm, packageName, candidate);
if (result != null) {
return result;
}
}
// if there is a default receiver, try that
candidate = SystemProperties.get(DEFAULT_ERROR_RECEIVER_PROPERTY);
return getErrorReportReceiver(pm, packageName, candidate);
}
/**
* Return activity in receiverPackage that handles ACTION_APP_ERROR.
*
* @param pm PackageManager instance
* @param errorPackage package which caused the error
* @param receiverPackage candidate package to receive the error
* @return activity component within receiverPackage which handles
* ACTION_APP_ERROR, or null if not found
*/
static ComponentName getErrorReportReceiver(PackageManager pm, String errorPackage,
String receiverPackage) {
if (receiverPackage == null || receiverPackage.length() == 0) {
return null;
}
// break the loop if it's the error report receiver package that crashed
if (receiverPackage.equals(errorPackage)) {
return null;
}
Intent intent = new Intent(Intent.ACTION_APP_ERROR);
intent.setPackage(receiverPackage);
ResolveInfo info = pm.resolveActivity(intent, 0);
if (info == null || info.activityInfo == null) {
return null;
}
return new ComponentName(receiverPackage, info.activityInfo.name);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(type);
dest.writeString(packageName);
dest.writeString(installerPackageName);
dest.writeString(processName);
dest.writeLong(time);
dest.writeInt(systemApp ? 1 : 0);
switch (type) {
case TYPE_CRASH:
crashInfo.writeToParcel(dest, flags);
break;
case TYPE_ANR:
anrInfo.writeToParcel(dest, flags);
break;
case TYPE_BATTERY:
batteryInfo.writeToParcel(dest, flags);
break;
case TYPE_RUNNING_SERVICE:
runningServiceInfo.writeToParcel(dest, flags);
break;
}
}
public void readFromParcel(Parcel in) {
type = in.readInt();
packageName = in.readString();
installerPackageName = in.readString();
processName = in.readString();
time = in.readLong();
systemApp = in.readInt() == 1;
switch (type) {
case TYPE_CRASH:
crashInfo = new CrashInfo(in);
anrInfo = null;
batteryInfo = null;
runningServiceInfo = null;
break;
case TYPE_ANR:
anrInfo = new AnrInfo(in);
crashInfo = null;
batteryInfo = null;
runningServiceInfo = null;
break;
case TYPE_BATTERY:
batteryInfo = new BatteryInfo(in);
anrInfo = null;
crashInfo = null;
runningServiceInfo = null;
break;
case TYPE_RUNNING_SERVICE:
batteryInfo = null;
anrInfo = null;
crashInfo = null;
runningServiceInfo = new RunningServiceInfo(in);
break;
}
}
/**
* Describes an application crash.
*/
public static class CrashInfo {
/**
* Class name of the exception that caused the crash.
*/
public String exceptionClassName;
/**
* Message stored in the exception.
*/
public String exceptionMessage;
/**
* File which the exception was thrown from.
*/
public String throwFileName;
/**
* Class which the exception was thrown from.
*/
public String throwClassName;
/**
* Method which the exception was thrown from.
*/
public String throwMethodName;
/**
* Line number the exception was thrown from.
*/
public int throwLineNumber;
/**
* Stack trace.
*/
public String stackTrace;
/**
* Create an uninitialized instance of CrashInfo.
*/
public CrashInfo() {
}
/**
* Create an instance of CrashInfo initialized from an exception.
*/
public CrashInfo(Throwable tr) {
StringWriter sw = new StringWriter();
PrintWriter pw = new FastPrintWriter(sw, false, 256);
tr.printStackTrace(pw);
pw.flush();
stackTrace = sw.toString();
exceptionMessage = tr.getMessage();
// Populate fields with the "root cause" exception
Throwable rootTr = tr;
while (tr.getCause() != null) {
tr = tr.getCause();
if (tr.getStackTrace() != null && tr.getStackTrace().length > 0) {
rootTr = tr;
}
String msg = tr.getMessage();
if (msg != null && msg.length() > 0) {
exceptionMessage = msg;
}
}
exceptionClassName = rootTr.getClass().getName();
if (rootTr.getStackTrace().length > 0) {
StackTraceElement trace = rootTr.getStackTrace()[0];
throwFileName = trace.getFileName();
throwClassName = trace.getClassName();
throwMethodName = trace.getMethodName();
throwLineNumber = trace.getLineNumber();
} else {
throwFileName = "unknown";
throwClassName = "unknown";
throwMethodName = "unknown";
throwLineNumber = 0;
}
}
/**
* Create an instance of CrashInfo initialized from a Parcel.
*/
public CrashInfo(Parcel in) {
exceptionClassName = in.readString();
exceptionMessage = in.readString();
throwFileName = in.readString();
throwClassName = in.readString();
throwMethodName = in.readString();
throwLineNumber = in.readInt();
stackTrace = in.readString();
}
/**
* Save a CrashInfo instance to a parcel.
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(exceptionClassName);
dest.writeString(exceptionMessage);
dest.writeString(throwFileName);
dest.writeString(throwClassName);
dest.writeString(throwMethodName);
dest.writeInt(throwLineNumber);
dest.writeString(stackTrace);
}
/**
* Dump a CrashInfo instance to a Printer.
*/
public void dump(Printer pw, String prefix) {
pw.println(prefix + "exceptionClassName: " + exceptionClassName);
pw.println(prefix + "exceptionMessage: " + exceptionMessage);
pw.println(prefix + "throwFileName: " + throwFileName);
pw.println(prefix + "throwClassName: " + throwClassName);
pw.println(prefix + "throwMethodName: " + throwMethodName);
pw.println(prefix + "throwLineNumber: " + throwLineNumber);
pw.println(prefix + "stackTrace: " + stackTrace);
}
}
/**
* Describes an application not responding error.
*/
public static class AnrInfo {
/**
* Activity name.
*/
public String activity;
/**
* Description of the operation that timed out.
*/
public String cause;
/**
* Additional info, including CPU stats.
*/
public String info;
/**
* Create an uninitialized instance of AnrInfo.
*/
public AnrInfo() {
}
/**
* Create an instance of AnrInfo initialized from a Parcel.
*/
public AnrInfo(Parcel in) {
activity = in.readString();
cause = in.readString();
info = in.readString();
}
/**
* Save an AnrInfo instance to a parcel.
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(activity);
dest.writeString(cause);
dest.writeString(info);
}
/**
* Dump an AnrInfo instance to a Printer.
*/
public void dump(Printer pw, String prefix) {
pw.println(prefix + "activity: " + activity);
pw.println(prefix + "cause: " + cause);
pw.println(prefix + "info: " + info);
}
}
/**
* Describes a battery usage report.
*/
public static class BatteryInfo {
/**
* Percentage of the battery that was used up by the process.
*/
public int usagePercent;
/**
* Duration in microseconds over which the process used the above
* percentage of battery.
*/
public long durationMicros;
/**
* Dump of various info impacting battery use.
*/
public String usageDetails;
/**
* Checkin details.
*/
public String checkinDetails;
/**
* Create an uninitialized instance of BatteryInfo.
*/
public BatteryInfo() {
}
/**
* Create an instance of BatteryInfo initialized from a Parcel.
*/
public BatteryInfo(Parcel in) {
usagePercent = in.readInt();
durationMicros = in.readLong();
usageDetails = in.readString();
checkinDetails = in.readString();
}
/**
* Save a BatteryInfo instance to a parcel.
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(usagePercent);
dest.writeLong(durationMicros);
dest.writeString(usageDetails);
dest.writeString(checkinDetails);
}
/**
* Dump a BatteryInfo instance to a Printer.
*/
public void dump(Printer pw, String prefix) {
pw.println(prefix + "usagePercent: " + usagePercent);
pw.println(prefix + "durationMicros: " + durationMicros);
pw.println(prefix + "usageDetails: " + usageDetails);
pw.println(prefix + "checkinDetails: " + checkinDetails);
}
}
/**
* Describes a running service report.
*/
public static class RunningServiceInfo {
/**
* Duration in milliseconds that the service has been running.
*/
public long durationMillis;
/**
* Dump of debug information about the service.
*/
public String serviceDetails;
/**
* Create an uninitialized instance of RunningServiceInfo.
*/
public RunningServiceInfo() {
}
/**
* Create an instance of RunningServiceInfo initialized from a Parcel.
*/
public RunningServiceInfo(Parcel in) {
durationMillis = in.readLong();
serviceDetails = in.readString();
}
/**
* Save a RunningServiceInfo instance to a parcel.
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(durationMillis);
dest.writeString(serviceDetails);
}
/**
* Dump a BatteryInfo instance to a Printer.
*/
public void dump(Printer pw, String prefix) {
pw.println(prefix + "durationMillis: " + durationMillis);
pw.println(prefix + "serviceDetails: " + serviceDetails);
}
}
public static final Parcelable.Creator<ApplicationErrorReport> CREATOR
= new Parcelable.Creator<ApplicationErrorReport>() {
public ApplicationErrorReport createFromParcel(Parcel source) {
return new ApplicationErrorReport(source);
}
public ApplicationErrorReport[] newArray(int size) {
return new ApplicationErrorReport[size];
}
};
public int describeContents() {
return 0;
}
/**
* Dump the report to a Printer.
*/
public void dump(Printer pw, String prefix) {
pw.println(prefix + "type: " + type);
pw.println(prefix + "packageName: " + packageName);
pw.println(prefix + "installerPackageName: " + installerPackageName);
pw.println(prefix + "processName: " + processName);
pw.println(prefix + "time: " + time);
pw.println(prefix + "systemApp: " + systemApp);
switch (type) {
case TYPE_CRASH:
crashInfo.dump(pw, prefix);
break;
case TYPE_ANR:
anrInfo.dump(pw, prefix);
break;
case TYPE_BATTERY:
batteryInfo.dump(pw, prefix);
break;
case TYPE_RUNNING_SERVICE:
runningServiceInfo.dump(pw, prefix);
break;
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 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.di.trans.steps.concatfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaBase;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.trans.step.StepInjectionMetaEntry;
import org.pentaho.di.trans.step.StepMetaInjectionInterface;
import org.pentaho.di.trans.steps.textfileoutput.TextFileField;
/**
* This takes care of the external metadata injection into the TableOutputMeta class
*
* @author Chris
*/
public class ConcatFieldsMetaInjection implements StepMetaInjectionInterface {
private enum Entry {
TARGET_FIELDNAME( ValueMetaInterface.TYPE_STRING, "The target field name" ),
TARGET_LENGTH( ValueMetaInterface.TYPE_STRING, "The length of the target field" ),
SEPARATOR( ValueMetaInterface.TYPE_STRING, "The separator" ),
ENCLOSURE( ValueMetaInterface.TYPE_STRING, "The enclosure" ),
REMOVE_FIELDS( ValueMetaInterface.TYPE_STRING, "Remove selected fields? (Y/N)" ),
FORCE_ENCLOSURE( ValueMetaInterface.TYPE_STRING, "Force the enclosure around fields? (Y/N)" ),
DISABLE_ENCLOSURE_FIX( ValueMetaInterface.TYPE_STRING, "Disable the enclosure fix? (Y/N)" ),
HEADER( ValueMetaInterface.TYPE_STRING, "Include header row? (Y/N)" ),
FOOTER( ValueMetaInterface.TYPE_STRING, "Include footer row? (Y/N)" ),
ENCODING( ValueMetaInterface.TYPE_STRING,
"Encoding type (for allowed values see: http://wiki.pentaho.com/display/EAI/Concat+Fields)" ),
RIGHT_PAD_FIELDS( ValueMetaInterface.TYPE_STRING, "Right pad fields? (Y/N)" ),
FAST_DATA_DUMP( ValueMetaInterface.TYPE_STRING, "Fast data dump? (Y/N)" ),
SPLIT_EVERY( ValueMetaInterface.TYPE_STRING, "Split every ... rows" ),
ADD_ENDING_LINE( ValueMetaInterface.TYPE_STRING, "Add ending line after last row" ),
CONCAT_FIELDS( ValueMetaInterface.TYPE_NONE, "The fields to concatenate" ),
CONCAT_FIELD( ValueMetaInterface.TYPE_NONE, "One field to concatenate" ),
CONCAT_FIELDNAME( ValueMetaInterface.TYPE_STRING, "Field to concatenate" ),
CONCAT_TYPE( ValueMetaInterface.TYPE_STRING,
"Field type (for allowed values see: http://wiki.pentaho.com/display/EAI/Concat+Fields)" ),
CONCAT_FORMAT( ValueMetaInterface.TYPE_STRING, "Field format" ),
CONCAT_LENGTH( ValueMetaInterface.TYPE_STRING, "Field length" ),
CONCAT_PRECISION( ValueMetaInterface.TYPE_STRING, "Field precision" ),
CONCAT_CURRENCY( ValueMetaInterface.TYPE_STRING, "Field currency symbol" ),
CONCAT_DECIMAL( ValueMetaInterface.TYPE_STRING, "Field decimal symbol" ),
CONCAT_GROUP( ValueMetaInterface.TYPE_STRING, "Field grouping symbol" ),
CONCAT_TRIM( ValueMetaInterface.TYPE_STRING, "Field trim type (none,left,both,right)" ),
CONCAT_NULL( ValueMetaInterface.TYPE_STRING, "Value to replace nulls with" );
private int valueType;
private String description;
private Entry( int valueType, String description ) {
this.valueType = valueType;
this.description = description;
}
/**
* @return the valueType
*/
public int getValueType() {
return valueType;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
public static Entry findEntry( String key ) {
return Entry.valueOf( key );
}
}
private ConcatFieldsMeta meta;
public ConcatFieldsMetaInjection( ConcatFieldsMeta meta ) {
this.meta = meta;
}
@Override
public List<StepInjectionMetaEntry> getStepInjectionMetadataEntries() throws KettleException {
List<StepInjectionMetaEntry> all = new ArrayList<StepInjectionMetaEntry>();
Entry[] topEntries =
new Entry[] {
Entry.TARGET_FIELDNAME, Entry.TARGET_LENGTH, Entry.SEPARATOR, Entry.ENCLOSURE,
Entry.REMOVE_FIELDS, Entry.FORCE_ENCLOSURE, Entry.DISABLE_ENCLOSURE_FIX,
Entry.HEADER, Entry.FOOTER, Entry.ENCODING, Entry.RIGHT_PAD_FIELDS,
Entry.FAST_DATA_DUMP, Entry.SPLIT_EVERY, Entry.ADD_ENDING_LINE, };
for ( Entry topEntry : topEntries ) {
all.add( new StepInjectionMetaEntry( topEntry.name(), topEntry.getValueType(), topEntry.getDescription() ) );
}
// The fields
//
StepInjectionMetaEntry fieldsEntry =
new StepInjectionMetaEntry(
Entry.CONCAT_FIELDS.name(), ValueMetaInterface.TYPE_NONE, Entry.CONCAT_FIELDS.description );
all.add( fieldsEntry );
StepInjectionMetaEntry fieldEntry =
new StepInjectionMetaEntry(
Entry.CONCAT_FIELD.name(), ValueMetaInterface.TYPE_NONE, Entry.CONCAT_FIELD.description );
fieldsEntry.getDetails().add( fieldEntry );
Entry[] fieldsEntries = new Entry[] { Entry.CONCAT_FIELDNAME, Entry.CONCAT_TYPE, Entry.CONCAT_LENGTH,
Entry.CONCAT_FORMAT, Entry.CONCAT_PRECISION, Entry.CONCAT_CURRENCY, Entry.CONCAT_DECIMAL,
Entry.CONCAT_GROUP, Entry.CONCAT_TRIM, Entry.CONCAT_NULL, };
for ( Entry entry : fieldsEntries ) {
StepInjectionMetaEntry metaEntry =
new StepInjectionMetaEntry( entry.name(), entry.getValueType(), entry.getDescription() );
fieldEntry.getDetails().add( metaEntry );
}
return all;
}
@Override
public void injectStepMetadataEntries( List<StepInjectionMetaEntry> all ) throws KettleException {
List<String> concatFields = new ArrayList<String>();
List<String> concatTypes = new ArrayList<String>();
List<String> concatLengths = new ArrayList<String>();
List<String> concatFormats = new ArrayList<String>();
List<String> concatPrecisions = new ArrayList<String>();
List<String> concatCurrencies = new ArrayList<String>();
List<String> concatDecimals = new ArrayList<String>();
List<String> concatGroups = new ArrayList<String>();
List<String> concatTrims = new ArrayList<String>();
List<String> concatNulls = new ArrayList<String>();
// Parse the fields, inject into the meta class..
//
for ( StepInjectionMetaEntry lookFields : all ) {
Entry fieldsEntry = Entry.findEntry( lookFields.getKey() );
if ( fieldsEntry == null ) {
continue;
}
String lookValue = (String) lookFields.getValue();
switch ( fieldsEntry ) {
case CONCAT_FIELDS:
for ( StepInjectionMetaEntry lookField : lookFields.getDetails() ) {
Entry fieldEntry = Entry.findEntry( lookField.getKey() );
if ( fieldEntry == Entry.CONCAT_FIELD ) {
String concatFieldname = null;
String concatType = null;
String concatLength = null;
String concatFormat = null;
String concatPrecision = null;
String concatCurrency = null;
String concatDecimal = null;
String concatGroup = null;
String concatTrim = null;
String concatNull = null;
List<StepInjectionMetaEntry> entries = lookField.getDetails();
for ( StepInjectionMetaEntry entry : entries ) {
Entry metaEntry = Entry.findEntry( entry.getKey() );
if ( metaEntry != null ) {
String value = (String) entry.getValue();
switch ( metaEntry ) {
case CONCAT_FIELDNAME:
concatFieldname = value;
break;
case CONCAT_TYPE:
concatType = value;
break;
case CONCAT_LENGTH:
concatLength = value;
break;
case CONCAT_FORMAT:
concatFormat = value;
break;
case CONCAT_PRECISION:
concatPrecision = value;
break;
case CONCAT_CURRENCY:
concatCurrency = value;
break;
case CONCAT_DECIMAL:
concatDecimal = value;
break;
case CONCAT_GROUP:
concatGroup = value;
break;
case CONCAT_TRIM:
concatTrim = value;
break;
case CONCAT_NULL:
concatNull = value;
break;
default:
break;
}
}
}
concatFields.add( concatFieldname );
concatTypes.add( concatType );
concatLengths.add( concatLength );
concatFormats.add( concatFormat );
concatPrecisions.add( concatPrecision );
concatCurrencies.add( concatCurrency );
concatDecimals.add( concatDecimal );
concatGroups.add( concatGroup );
concatTrims.add( concatTrim );
concatNulls.add( concatNull );
}
}
break;
case TARGET_FIELDNAME:
meta.setTargetFieldName( lookValue );
break;
case TARGET_LENGTH:
meta.setTargetFieldLength( Const.toInt( lookValue, 0 ) );
break;
case SEPARATOR:
meta.setSeparator( lookValue );
break;
case ENCLOSURE:
meta.setEnclosure( lookValue );
break;
case REMOVE_FIELDS:
meta.setRemoveSelectedFields( "Y".equalsIgnoreCase( lookValue ) );
break;
case FORCE_ENCLOSURE:
meta.setEnclosureForced( "Y".equalsIgnoreCase( lookValue ) );
break;
case DISABLE_ENCLOSURE_FIX:
meta.setEnclosureFixDisabled( "Y".equalsIgnoreCase( lookValue ) );
break;
case HEADER:
meta.setHeaderEnabled( "Y".equalsIgnoreCase( lookValue ) );
break;
case FOOTER:
meta.setFooterEnabled( "Y".equalsIgnoreCase( lookValue ) );
break;
case ENCODING:
meta.setEncoding( lookValue );
break;
case RIGHT_PAD_FIELDS:
meta.setPadded( "Y".equalsIgnoreCase( lookValue ) );
break;
case FAST_DATA_DUMP:
meta.setFastDump( "Y".equalsIgnoreCase( lookValue ) );
break;
case SPLIT_EVERY:
meta.setSplitEvery( Const.toInt( lookValue, 0 ) );
break;
case ADD_ENDING_LINE:
meta.setEndedLine( lookValue );
break;
default:
break;
}
}
// Pass the grid to the step metadata
//
if ( concatFields.size() > 0 ) {
TextFileField[] tff = new TextFileField[concatFields.size()];
Iterator<String> iConcatFields = concatFields.iterator();
Iterator<String> iConcatTypes = concatTypes.iterator();
Iterator<String> iConcatLengths = concatLengths.iterator();
Iterator<String> iConcatFormats = concatFormats.iterator();
Iterator<String> iConcatPrecisions = concatPrecisions.iterator();
Iterator<String> iConcatCurrencies = concatCurrencies.iterator();
Iterator<String> iConcatDecimals = concatDecimals.iterator();
Iterator<String> iConcatGroups = concatGroups.iterator();
Iterator<String> iConcatTrims = concatTrims.iterator();
Iterator<String> iConcatNulls = concatNulls.iterator();
int i = 0;
while ( iConcatFields.hasNext() ) {
TextFileField field = new TextFileField();
field.setName( iConcatFields.next() );
field.setType( ValueMetaFactory.getIdForValueMeta( iConcatTypes.next() ) );
field.setFormat( iConcatFormats.next() );
field.setLength( Const.toInt( iConcatLengths.next(), -1 ) );
field.setPrecision( Const.toInt( iConcatPrecisions.next(), -1 ) );
field.setCurrencySymbol( iConcatCurrencies.next() );
field.setDecimalSymbol( iConcatDecimals.next() );
field.setGroupingSymbol( iConcatGroups.next() );
field.setNullString( iConcatNulls.next() );
field.setTrimType( ValueMetaBase.getTrimTypeByDesc( iConcatTrims.next() ) );
tff[i] = field;
i++;
}
meta.setOutputFields( tff );
}
}
@Override
public List<StepInjectionMetaEntry> extractStepMetadataEntries() throws KettleException {
return null;
}
public ConcatFieldsMeta getMeta() {
return meta;
}
}
| |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation 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.unitime.timetable.events;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.defaults.SessionAttribute;
import org.unitime.timetable.gwt.command.client.GwtRpcResponse;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.EventInterface.EventRpcRequest;
import org.unitime.timetable.gwt.shared.EventInterface.MeetingConflictInterface;
import org.unitime.timetable.gwt.shared.EventInterface.MeetingInterface;
import org.unitime.timetable.gwt.shared.PageAccessException;
import org.unitime.timetable.model.Meeting;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.security.Qualifiable;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.UserAuthority;
import org.unitime.timetable.security.UserContext;
import org.unitime.timetable.security.evaluation.UniTimePermissionCheck;
import org.unitime.timetable.security.qualifiers.SimpleQualifier;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.util.Formats;
/**
* @author Tomas Muller
*/
public abstract class EventAction<T extends EventRpcRequest<R>, R extends GwtRpcResponse> implements GwtRpcImplementation<T, R> {
protected static GwtMessages MESSAGES = Localization.create(GwtMessages.class);
protected static GwtConstants CONSTANTS = Localization.create(GwtConstants.class);
protected static Formats.Format<Date> sDateFormat = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT);
@Override
public R execute(T request, SessionContext context) {
// Check basic permissions
context.checkPermissionAnyAuthority(Right.Events, new SimpleQualifier("Session", request.getSessionId()));
// Execute action
return execute(request, new EventContext(context, request.getSessionId()));
}
public abstract R execute(T request, EventContext context);
protected static Formats.Format<Date> getDateFormat() {
return sDateFormat;
}
protected static String toString(MeetingInterface meeting) {
return (meeting instanceof MeetingConflictInterface ? ((MeetingConflictInterface)meeting).getName() + " " : "") +
(meeting.getMeetingDate() == null ? "" : getDateFormat().format(meeting.getMeetingDate()) + " ") +
meeting.getAllocatedTime(CONSTANTS) + (meeting.hasLocation() ? " " + meeting.getLocationName() : "");
}
protected static String toString(Meeting meeting) {
return (meeting.getMeetingDate() == null ? "" : getDateFormat().format(meeting.getMeetingDate()) + " ") +
time2string(meeting.getStartPeriod(), 0) + " - " + time2string(meeting.getStopPeriod(), 0) +
(meeting.getLocation() == null ? " " + meeting.getLocation().getLabel() : "");
}
protected static String time2string(int slot, int offset) {
int min = 5 * slot + offset;
if (min == 0 || min == 1440) return CONSTANTS.timeMidnight();
if (min == 720) return CONSTANTS.timeNoon();
int h = min / 60;
int m = min % 60;
if (CONSTANTS.useAmPm()) {
return (h > 12 ? h - 12 : h) + ":" + (m < 10 ? "0" : "") + m + (h == 24 ? "a" : h >= 12 ? "p" : "a");
} else {
return h + ":" + (m < 10 ? "0" : "") + m;
}
}
public static class EventContext implements SessionContext {
private SessionContext iContext;
private Qualifiable[] iFilter;
private Date iToday, iBegin, iEnd;
private UserContext iUser;
private boolean iAllowEditPast = false;
public EventContext(SessionContext context, UserContext user, Long sessionId) {
iContext = (context instanceof EventContext ? ((EventContext)context).iContext : context);
iUser = user;
if (sessionId == null)
sessionId = context.getUser().getCurrentAcademicSessionId();
iFilter = new Qualifiable[] { new SimpleQualifier("Session", sessionId) };
Calendar cal = Calendar.getInstance(Localization.getJavaLocale());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
iToday = cal.getTime();
Session session = SessionDAO.getInstance().get(sessionId);
if (session != null) {
iBegin = session.getEventBeginDate();
cal.setTime(session.getEventEndDate());
cal.add(Calendar.DAY_OF_YEAR, 1);
iEnd = cal.getTime();
}
if (user != null) {
String role = (user.getCurrentAuthority() == null ? null : user.getCurrentAuthority().getRole());
for (UserAuthority authority: user.getAuthorities()) {
if (authority.getAcademicSession() != null && authority.getAcademicSession().getQualifierId().equals(sessionId) && (role == null || role.equals(authority.getRole()))) {
iUser = new UniTimePermissionCheck.UserContextWrapper(user, authority);
if (role != null) iFilter = new Qualifiable[] { new SimpleQualifier("Session", sessionId), new SimpleQualifier("Role", role) };
break;
}
}
}
iAllowEditPast = context.hasPermission(Right.EventEditPast);
}
public EventContext(SessionContext context, Long sessionId) {
this(context, context.getUser(), sessionId);
}
public boolean isOutside(Date date) {
return date == null || (iBegin != null && date.before(iBegin)) || (iEnd != null && !date.before(iEnd));
}
public boolean isPast(Date date) {
return !iAllowEditPast && (date == null || date.before(iToday));
}
public boolean isPastOrOutside(Date date) {
return isPast(date) || isOutside(date);
}
@Override
public boolean isAuthenticated() { return iUser != null; }
@Override
public UserContext getUser() { return iUser; }
@Override
public boolean isHttpSessionNew() { return iContext.isHttpSessionNew(); }
@Override
public String getHttpSessionId() { return iContext.getHttpSessionId(); }
@Override
public Object getAttribute(String name) { return iContext.getAttribute(name); }
@Override
public void removeAttribute(String name) { iContext.removeAttribute(name); }
@Override
public void setAttribute(String name, Object value) { iContext.setAttribute(name, value); }
@Override
public void removeAttribute(SessionAttribute attribute) { iContext.removeAttribute(attribute); }
@Override
public void setAttribute(SessionAttribute attribute, Object value) { iContext.setAttribute(attribute, value); }
@Override
public Object getAttribute(SessionAttribute attribute) { return iContext.getAttribute(attribute); }
public PageAccessException getException() {
if (iContext.isAuthenticated()) return new PageAccessException(MESSAGES.authenticationInsufficient());
return new PageAccessException(iContext.isHttpSessionNew() ? MESSAGES.authenticationExpired() : MESSAGES.authenticationRequired());
}
@Override
public void checkPermission(Right right) {
if (!iContext.hasPermissionAnyAuthority(right, iFilter)) throw getException();
}
@Override
public void checkPermission(Serializable targetId, String targetType, Right right) {
if (!iContext.hasPermissionAnyAuthority(targetId, targetType, right, iFilter)) throw getException();
}
@Override
public void checkPermission(Object targetObject, Right right) {
if (!iContext.hasPermissionAnyAuthority(targetObject, right, iFilter)) throw getException();
}
@Override
public boolean hasPermission(Right right) {
return iContext.hasPermissionAnyAuthority(right, iFilter);
}
@Override
public boolean hasPermission(Serializable targetId, String targetType, Right right) {
return iContext.hasPermissionAnyAuthority(targetId, targetType, right, iFilter);
}
@Override
public boolean hasPermission(Object targetObject, Right right) {
return iContext.hasPermissionAnyAuthority(targetObject, right, iFilter);
}
@Override
public boolean hasPermissionAnyAuthority(Right right, Qualifiable... filter) {
return iContext.hasPermissionAnyAuthority(right, filter == null || filter.length == 0 ? iFilter : filter);
}
@Override
public boolean hasPermissionAnyAuthority(Serializable targetId, String targetType, Right right, Qualifiable... filter) {
return iContext.hasPermissionAnyAuthority(targetId, targetType, right, filter == null || filter.length == 0 ? iFilter : filter);
}
@Override
public boolean hasPermissionAnyAuthority(Object targetObject, Right right, Qualifiable... filter) {
return iContext.hasPermissionAnyAuthority(targetObject, right, filter == null || filter.length == 0 ? iFilter : filter);
}
@Override
public void checkPermissionAnyAuthority(Right right, Qualifiable... filter) {
iContext.checkPermissionAnyAuthority(right, filter == null || filter.length == 0 ? iFilter : filter);
}
@Override
public void checkPermissionAnyAuthority(Serializable targetId, String targetType, Right right, Qualifiable... filter) {
iContext.checkPermissionAnyAuthority(targetId, targetType, right, filter == null || filter.length == 0 ? iFilter : filter);
}
@Override
public void checkPermissionAnyAuthority(Object targetObject, Right right, Qualifiable... filter) {
iContext.checkPermissionAnyAuthority(targetObject, right, filter == null || filter.length == 0 ? iFilter : filter);
}
}
}
| |
package io.airlift.airline.model;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import io.airlift.airline.Accessor;
import io.airlift.airline.Arguments;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.airlift.airline.OptionType;
import io.airlift.airline.Suggester;
import javax.inject.Inject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.stream;
import static java.util.Objects.requireNonNull;
public final class MetadataLoader
{
private MetadataLoader() {}
public static GlobalMetadata loadGlobal(String name,
String description,
CommandMetadata defaultCommand,
Iterable<CommandMetadata> defaultGroupCommands,
Iterable<CommandGroupMetadata> groups)
{
ImmutableList.Builder<OptionMetadata> globalOptionsBuilder = ImmutableList.builder();
if (defaultCommand != null) {
globalOptionsBuilder.addAll(defaultCommand.getGlobalOptions());
}
for (CommandMetadata command : defaultGroupCommands) {
globalOptionsBuilder.addAll(command.getGlobalOptions());
}
for (CommandGroupMetadata group : groups) {
for (CommandMetadata command : group.getCommands()) {
globalOptionsBuilder.addAll(command.getGlobalOptions());
}
}
List<OptionMetadata> globalOptions = mergeOptionSet(globalOptionsBuilder.build());
return new GlobalMetadata(name, description, globalOptions, defaultCommand, defaultGroupCommands, groups);
}
public static CommandGroupMetadata loadCommandGroup(String name, String description, CommandMetadata defaultCommand, Iterable<CommandMetadata> commands)
{
ImmutableList.Builder<OptionMetadata> groupOptionsBuilder = ImmutableList.builder();
if (defaultCommand != null) {
groupOptionsBuilder.addAll(defaultCommand.getGroupOptions());
}
for (CommandMetadata command : commands) {
groupOptionsBuilder.addAll(command.getGroupOptions());
}
List<OptionMetadata> groupOptions = mergeOptionSet(groupOptionsBuilder.build());
return new CommandGroupMetadata(name, description, groupOptions, defaultCommand, commands);
}
public static <T> ImmutableList<CommandMetadata> loadCommands(Iterable<Class<? extends T>> defaultCommands)
{
return stream(defaultCommands)
.map(MetadataLoader::loadCommand)
.collect(toImmutableList());
}
public static CommandMetadata loadCommand(Class<?> commandType)
{
requireNonNull(commandType, "commandType is null");
Command command = null;
for (Class<?> cls = commandType; command == null && !Object.class.equals(cls); cls = cls.getSuperclass()) {
command = cls.getAnnotation(Command.class);
}
checkArgument(command != null, "Command %s is not annotated with @Command", commandType.getName());
String name = command.name();
String description = command.description().isEmpty() ? null : command.description();
boolean hidden = command.hidden();
InjectionMetadata injectionMetadata = loadInjectionMetadata(commandType);
CommandMetadata commandMetadata = new CommandMetadata(
name,
description,
hidden, injectionMetadata.globalOptions,
injectionMetadata.groupOptions,
injectionMetadata.commandOptions,
Iterables.getFirst(injectionMetadata.arguments, null),
injectionMetadata.metadataInjections,
commandType);
return commandMetadata;
}
public static SuggesterMetadata loadSuggester(Class<? extends Suggester> suggesterClass)
{
InjectionMetadata injectionMetadata = loadInjectionMetadata(suggesterClass);
return new SuggesterMetadata(suggesterClass, injectionMetadata.metadataInjections);
}
public static InjectionMetadata loadInjectionMetadata(Class<?> type)
{
InjectionMetadata injectionMetadata = new InjectionMetadata();
loadInjectionMetadata(type, injectionMetadata, ImmutableList.<Field>of());
injectionMetadata.compact();
return injectionMetadata;
}
public static void loadInjectionMetadata(Class<?> type, InjectionMetadata injectionMetadata, List<Field> fields)
{
for (Class<?> cls = type; !Object.class.equals(cls); cls = cls.getSuperclass()) {
for (Field field : cls.getDeclaredFields()) {
field.setAccessible(true);
ImmutableList<Field> path = concat(fields, field);
Inject injectAnnotation = field.getAnnotation(Inject.class);
if (injectAnnotation != null) {
if (field.getType().equals(GlobalMetadata.class) ||
field.getType().equals(CommandGroupMetadata.class) ||
field.getType().equals(CommandMetadata.class)) {
injectionMetadata.metadataInjections.add(new Accessor(path));
}
else {
loadInjectionMetadata(field.getType(), injectionMetadata, path);
}
}
Option optionAnnotation = field.getAnnotation(Option.class);
if (optionAnnotation != null) {
OptionType optionType = optionAnnotation.type();
String name;
if (!optionAnnotation.title().isEmpty()) {
name = optionAnnotation.title();
}
else {
name = field.getName();
}
List<String> options = ImmutableList.copyOf(optionAnnotation.name());
String description = optionAnnotation.description();
int arity = optionAnnotation.arity();
checkArgument(arity >= 0 || arity == Integer.MIN_VALUE, "Invalid arity for option %s", name);
if (optionAnnotation.arity() >= 0) {
arity = optionAnnotation.arity();
}
else {
Class<?> fieldType = field.getType();
if (Boolean.class.isAssignableFrom(fieldType) || boolean.class.isAssignableFrom(fieldType)) {
arity = 0;
}
else {
arity = 1;
}
}
boolean required = optionAnnotation.required();
boolean hidden = optionAnnotation.hidden();
List<String> allowedValues = ImmutableList.copyOf(optionAnnotation.allowedValues());
if (allowedValues.isEmpty()) {
allowedValues = null;
}
OptionMetadata optionMetadata = new OptionMetadata(optionType, options, name, description, arity, required, hidden, allowedValues, path);
switch (optionType) {
case GLOBAL:
injectionMetadata.globalOptions.add(optionMetadata);
break;
case GROUP:
injectionMetadata.groupOptions.add(optionMetadata);
break;
case COMMAND:
injectionMetadata.commandOptions.add(optionMetadata);
break;
}
}
Arguments argumentsAnnotation = field.getAnnotation(Arguments.class);
if (field.isAnnotationPresent(Arguments.class)) {
String title;
if (!argumentsAnnotation.title().isEmpty()) {
title = argumentsAnnotation.title();
}
else {
title = field.getName();
}
String description = argumentsAnnotation.description();
String usage = argumentsAnnotation.usage();
boolean required = argumentsAnnotation.required();
injectionMetadata.arguments.add(new ArgumentsMetadata(title, description, usage, required, path));
}
}
}
}
private static List<OptionMetadata> mergeOptionSet(List<OptionMetadata> options)
{
ListMultimap<OptionMetadata, OptionMetadata> metadataIndex = ArrayListMultimap.create();
for (OptionMetadata option : options) {
metadataIndex.put(option, option);
}
options = metadataIndex.asMap().values().stream()
.map(OptionMetadata::new)
.collect(toImmutableList());
Map<String, OptionMetadata> optionIndex = new HashMap<>();
for (OptionMetadata option : options) {
for (String optionName : option.getOptions()) {
if (optionIndex.containsKey(optionName)) {
throw new IllegalArgumentException(String.format("Fields %s and %s have conflicting definitions of option %s",
optionIndex.get(optionName).getAccessors().iterator().next(),
option.getAccessors().iterator().next(),
optionName));
}
optionIndex.put(optionName, option);
}
}
return options;
}
private static <T> ImmutableList<T> concat(Iterable<T> iterable, T item)
{
return ImmutableList.<T>builder().addAll(iterable).add(item).build();
}
private static class InjectionMetadata
{
private List<OptionMetadata> globalOptions = new ArrayList<>();
private List<OptionMetadata> groupOptions = new ArrayList<>();
private List<OptionMetadata> commandOptions = new ArrayList<>();
private List<ArgumentsMetadata> arguments = new ArrayList<>();
private List<Accessor> metadataInjections = new ArrayList<>();
private void compact()
{
globalOptions = mergeOptionSet(globalOptions);
groupOptions = mergeOptionSet(groupOptions);
commandOptions = mergeOptionSet(commandOptions);
if (arguments.size() > 1) {
arguments = ImmutableList.of(new ArgumentsMetadata(arguments));
}
}
}
}
| |
package com.sap.cloud.lm.sl.cf.process.mock;
import static org.mockito.Mockito.spy;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FlowableListener;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.mockito.Mockito;
public class MockDelegateExecution implements DelegateExecution {
private Map<String, Object> mockVariables = new HashMap<String, Object>();
public static DelegateExecution createSpyInstance() {
MockDelegateExecution instance = new MockDelegateExecution();
return spy(instance);
}
public Map<String, Object> getMockVariables() {
return this.mockVariables;
}
@Override
public Object getVariable(String arg0) {
return mockVariables.get(arg0);
}
@Override
public Object getVariableLocal(String arg0) {
return null;
}
@Override
public Set<String> getVariableNames() {
return null;
}
@Override
public Set<String> getVariableNamesLocal() {
return null;
}
@Override
public Map<String, Object> getVariables() {
return mockVariables;
}
@Override
public Map<String, Object> getVariablesLocal() {
return null;
}
@Override
public boolean hasVariable(String arg0) {
return mockVariables.containsKey(arg0);
}
@Override
public boolean hasVariableLocal(String arg0) {
return false;
}
@Override
public boolean hasVariables() {
return false;
}
@Override
public boolean hasVariablesLocal() {
return false;
}
@Override
public void removeVariable(String arg0) {
this.mockVariables.remove(arg0);
}
@Override
public void removeVariableLocal(String arg0) {
}
@Override
public void removeVariables() {
}
@Override
public void removeVariables(Collection<String> arg0) {
}
@Override
public void removeVariablesLocal() {
}
@Override
public void removeVariablesLocal(Collection<String> arg0) {
}
@Override
public void setVariable(String arg0, Object arg1) {
this.mockVariables.put(arg0, arg1);
}
@Override
public Object setVariableLocal(String arg0, Object arg1) {
return null;
}
@Override
public void setVariables(Map<String, ? extends Object> arg0) {
}
@Override
public void setVariablesLocal(Map<String, ? extends Object> arg0) {
}
@Override
public String getCurrentActivityId() {
return "1";
}
@Override
public String getEventName() {
return null;
}
@Override
public String getId() {
return null;
}
@Override
public String getParentId() {
return null;
}
@Override
public String getProcessDefinitionId() {
return null;
}
@Override
public String getProcessInstanceId() {
return "1";
}
@Override
public String getTenantId() {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstances() {
return null;
}
@Override
public Map<String, Object> getVariables(Collection<String> variableNames) {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstances(Collection<String> variableNames) {
return null;
}
@Override
public Map<String, Object> getVariables(Collection<String> variableNames, boolean fetchAllVariables) {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstances(Collection<String> variableNames, boolean fetchAllVariables) {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal() {
return null;
}
@Override
public Map<String, Object> getVariablesLocal(Collection<String> variableNames) {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal(Collection<String> variableNames) {
return null;
}
@Override
public Map<String, Object> getVariablesLocal(Collection<String> variableNames, boolean fetchAllVariables) {
return null;
}
@Override
public Map<String, VariableInstance> getVariableInstancesLocal(Collection<String> variableNames, boolean fetchAllVariables) {
return null;
}
@Override
public VariableInstance getVariableInstance(String variableName) {
return null;
}
@Override
public Object getVariable(String variableName, boolean fetchAllVariables) {
return null;
}
@Override
public VariableInstance getVariableInstance(String variableName, boolean fetchAllVariables) {
return null;
}
@Override
public VariableInstance getVariableInstanceLocal(String variableName) {
return null;
}
@Override
public Object getVariableLocal(String variableName, boolean fetchAllVariables) {
return null;
}
@Override
public VariableInstance getVariableInstanceLocal(String variableName, boolean fetchAllVariables) {
return null;
}
@Override
public <T> T getVariable(String variableName, Class<T> variableClass) {
return null;
}
@Override
public <T> T getVariableLocal(String variableName, Class<T> variableClass) {
return null;
}
@Override
public void setVariable(String variableName, Object value, boolean fetchAllVariables) {
}
@Override
public Object setVariableLocal(String variableName, Object value, boolean fetchAllVariables) {
return null;
}
@Override
public String getSuperExecutionId() {
return null;
}
@Override
public Object getTransientVariable(String arg0) {
return null;
}
@Override
public Object getTransientVariableLocal(String arg0) {
return null;
}
@Override
public Map<String, Object> getTransientVariables() {
return null;
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
return null;
}
@Override
public void removeTransientVariable(String arg0) {
}
@Override
public void removeTransientVariableLocal(String arg0) {
}
@Override
public void removeTransientVariables() {
}
@Override
public void removeTransientVariablesLocal() {
}
@Override
public void setTransientVariable(String arg0, Object arg1) {
}
@Override
public void setTransientVariableLocal(String arg0, Object arg1) {
}
@Override
public void setTransientVariables(Map<String, Object> arg0) {
}
@Override
public void setTransientVariablesLocal(Map<String, Object> arg0) {
}
@Override
public String getRootProcessInstanceId() {
return null;
}
@Override
public void setEventName(String eventName) {
}
@Override
public String getProcessInstanceBusinessKey() {
return null;
}
@Override
public FlowElement getCurrentFlowElement() {
FlowElement mockFlowElement = Mockito.mock(FlowElement.class);
Mockito.when(mockFlowElement.getName())
.thenReturn("Default Name");
return mockFlowElement;
}
@Override
public void setCurrentFlowElement(FlowElement flowElement) {
}
@Override
public FlowableListener getCurrentFlowableListener() {
return null;
}
@Override
public void setCurrentFlowableListener(FlowableListener currentListener) {
}
@Override
public DelegateExecution getParent() {
return null;
}
@Override
public List<? extends DelegateExecution> getExecutions() {
return null;
}
@Override
public void setActive(boolean isActive) {
}
@Override
public boolean isActive() {
return false;
}
@Override
public boolean isEnded() {
return false;
}
@Override
public void setConcurrent(boolean isConcurrent) {
}
@Override
public boolean isConcurrent() {
return false;
}
@Override
public boolean isProcessInstanceType() {
return false;
}
@Override
public void inactivate() {
}
@Override
public boolean isScope() {
return false;
}
@Override
public void setScope(boolean isScope) {
}
@Override
public boolean isMultiInstanceRoot() {
return false;
}
@Override
public void setMultiInstanceRoot(boolean isMultiInstanceRoot) {
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.plugins;
import org.apache.log4j.Level;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.IndexModule;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.instanceOf;
@LuceneTestCase.SuppressFileSystems(value = "ExtrasFS")
public class PluginsServiceTests extends ESTestCase {
public static class AdditionalSettingsPlugin1 extends Plugin {
@Override
public Settings additionalSettings() {
return Settings.builder().put("foo.bar", "1").put(IndexModule.INDEX_STORE_TYPE_SETTING.getKey(), IndexModule.Type.MMAPFS.getSettingsKey()).build();
}
}
public static class AdditionalSettingsPlugin2 extends Plugin {
@Override
public Settings additionalSettings() {
return Settings.builder().put("foo.bar", "2").build();
}
}
public static class FilterablePlugin extends Plugin implements ScriptPlugin {}
static PluginsService newPluginsService(Settings settings, Class<? extends Plugin>... classpathPlugins) {
return new PluginsService(settings, null, null, TestEnvironment.newEnvironment(settings).pluginsFile(), Arrays.asList(classpathPlugins));
}
public void testAdditionalSettings() {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.put("my.setting", "test")
.put(IndexModule.INDEX_STORE_TYPE_SETTING.getKey(), IndexModule.Type.SIMPLEFS.getSettingsKey()).build();
PluginsService service = newPluginsService(settings, AdditionalSettingsPlugin1.class);
Settings newSettings = service.updatedSettings();
assertEquals("test", newSettings.get("my.setting")); // previous settings still exist
assertEquals("1", newSettings.get("foo.bar")); // added setting exists
assertEquals(IndexModule.Type.SIMPLEFS.getSettingsKey(), newSettings.get(IndexModule.INDEX_STORE_TYPE_SETTING.getKey())); // does not override pre existing settings
}
public void testAdditionalSettingsClash() {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build();
PluginsService service = newPluginsService(settings, AdditionalSettingsPlugin1.class, AdditionalSettingsPlugin2.class);
try {
service.updatedSettings();
fail("Expected exception when building updated settings");
} catch (IllegalArgumentException e) {
String msg = e.getMessage();
assertTrue(msg, msg.contains("Cannot have additional setting [foo.bar]"));
assertTrue(msg, msg.contains("plugin [" + AdditionalSettingsPlugin1.class.getName()));
assertTrue(msg, msg.contains("plugin [" + AdditionalSettingsPlugin2.class.getName()));
}
}
public void testExistingPluginMissingDescriptor() throws Exception {
Path pluginsDir = createTempDir();
Files.createDirectory(pluginsDir.resolve("plugin-missing-descriptor"));
try {
PluginsService.getPluginBundles(pluginsDir);
fail();
} catch (IllegalStateException e) {
assertTrue(e.getMessage(), e.getMessage().contains("Could not load plugin descriptor for existing plugin [plugin-missing-descriptor]"));
}
}
public void testFilterPlugins() {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.put("my.setting", "test")
.put(IndexModule.INDEX_STORE_TYPE_SETTING.getKey(), IndexModule.Type.SIMPLEFS.getSettingsKey()).build();
PluginsService service = newPluginsService(settings, AdditionalSettingsPlugin1.class, FilterablePlugin.class);
List<ScriptPlugin> scriptPlugins = service.filterPlugins(ScriptPlugin.class);
assertEquals(1, scriptPlugins.size());
assertEquals(FilterablePlugin.class, scriptPlugins.get(0).getClass());
}
public void testHiddenFiles() throws IOException {
final Path home = createTempDir();
final Settings settings =
Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), home)
.build();
final Path hidden = home.resolve("plugins").resolve(".hidden");
Files.createDirectories(hidden);
@SuppressWarnings("unchecked")
final IllegalStateException e = expectThrows(
IllegalStateException.class,
() -> newPluginsService(settings));
final String expected = "Could not load plugin descriptor for existing plugin [.hidden]";
assertThat(e, hasToString(containsString(expected)));
}
public void testDesktopServicesStoreFiles() throws IOException {
final Path home = createTempDir();
final Settings settings =
Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), home)
.build();
final Path plugins = home.resolve("plugins");
Files.createDirectories(plugins);
final Path desktopServicesStore = plugins.resolve(".DS_Store");
Files.createFile(desktopServicesStore);
if (Constants.MAC_OS_X) {
@SuppressWarnings("unchecked") final PluginsService pluginsService = newPluginsService(settings);
assertNotNull(pluginsService);
} else {
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> newPluginsService(settings));
assertThat(e, hasToString(containsString("Could not load plugin descriptor for existing plugin [.DS_Store]")));
assertNotNull(e.getCause());
assertThat(e.getCause(), instanceOf(FileSystemException.class));
if (Constants.WINDOWS) {
assertThat(e.getCause(), instanceOf(NoSuchFileException.class));
} else {
assertThat(e.getCause(), hasToString(containsString("Not a directory")));
}
}
}
public void testStartupWithRemovingMarker() throws IOException {
final Path home = createTempDir();
final Settings settings =
Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), home)
.build();
final Path fake = home.resolve("plugins").resolve("fake");
Files.createDirectories(fake);
Files.createFile(fake.resolve("plugin.jar"));
final Path removing = home.resolve("plugins").resolve(".removing-fake");
Files.createFile(removing);
PluginTestUtil.writePluginProperties(
fake,
"description", "fake",
"name", "fake",
"version", "1.0.0",
"elasticsearch.version", Version.CURRENT.toString(),
"java.version", System.getProperty("java.specification.version"),
"classname", "Fake",
"has.native.controller", "false");
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> newPluginsService(settings));
final String expected = String.format(
Locale.ROOT,
"found file [%s] from a failed attempt to remove the plugin [fake]; execute [elasticsearch-plugin remove fake]",
removing);
assertThat(e, hasToString(containsString(expected)));
}
public void testLoadPluginWithNoPublicConstructor() {
class NoPublicConstructorPlugin extends Plugin {
private NoPublicConstructorPlugin() {
}
}
final Path home = createTempDir();
final Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), home).build();
final IllegalStateException e =
expectThrows(IllegalStateException.class, () -> newPluginsService(settings, NoPublicConstructorPlugin.class));
assertThat(e, hasToString(containsString("no public constructor")));
}
public void testLoadPluginWithMultiplePublicConstructors() {
class MultiplePublicConstructorsPlugin extends Plugin {
@SuppressWarnings("unused")
public MultiplePublicConstructorsPlugin() {
}
@SuppressWarnings("unused")
public MultiplePublicConstructorsPlugin(final Settings settings) {
}
}
final Path home = createTempDir();
final Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), home).build();
final IllegalStateException e =
expectThrows(IllegalStateException.class, () -> newPluginsService(settings, MultiplePublicConstructorsPlugin.class));
assertThat(e, hasToString(containsString("no unique public constructor")));
}
public void testLoadPluginWithNoPublicConstructorOfCorrectSignature() {
class TooManyParametersPlugin extends Plugin {
@SuppressWarnings("unused")
public TooManyParametersPlugin(Settings settings, Path configPath, Object object) {
}
}
class TwoParametersFirstIncorrectType extends Plugin {
@SuppressWarnings("unused")
public TwoParametersFirstIncorrectType(Object object, Path configPath) {
}
}
class TwoParametersSecondIncorrectType extends Plugin {
@SuppressWarnings("unused")
public TwoParametersSecondIncorrectType(Settings settings, Object object) {
}
}
class OneParameterIncorrectType extends Plugin {
@SuppressWarnings("unused")
public OneParameterIncorrectType(Object object) {
}
}
final Collection<Class<? extends Plugin>> classes = Arrays.asList(
TooManyParametersPlugin.class,
TwoParametersFirstIncorrectType.class,
TwoParametersSecondIncorrectType.class,
OneParameterIncorrectType.class);
for (Class<? extends Plugin> pluginClass : classes) {
final Path home = createTempDir();
final Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), home).build();
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> newPluginsService(settings, pluginClass));
assertThat(e, hasToString(containsString("no public constructor of correct signature")));
}
}
public void testSortBundlesCycleSelfReference() throws Exception {
Path pluginDir = createTempDir();
PluginInfo info = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Collections.singletonList("foo"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.sortBundles(Collections.singleton(bundle))
);
assertEquals("Cycle found in plugin dependencies: foo -> foo", e.getMessage());
}
public void testSortBundlesCycle() throws Exception {
Path pluginDir = createTempDir();
Set<PluginsService.Bundle> bundles = new LinkedHashSet<>(); // control iteration order, so we get know the beginning of the cycle
PluginInfo info = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Arrays.asList("bar", "other"), false, false);
bundles.add(new PluginsService.Bundle(info, pluginDir));
PluginInfo info2 = new PluginInfo("bar", "desc", "1.0", "MyPlugin", Collections.singletonList("baz"), false, false);
bundles.add(new PluginsService.Bundle(info2, pluginDir));
PluginInfo info3 = new PluginInfo("baz", "desc", "1.0", "MyPlugin", Collections.singletonList("foo"), false, false);
bundles.add(new PluginsService.Bundle(info3, pluginDir));
PluginInfo info4 = new PluginInfo("other", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
bundles.add(new PluginsService.Bundle(info4, pluginDir));
IllegalStateException e = expectThrows(IllegalStateException.class, () -> PluginsService.sortBundles(bundles));
assertEquals("Cycle found in plugin dependencies: foo -> bar -> baz -> foo", e.getMessage());
}
public void testSortBundlesSingle() throws Exception {
Path pluginDir = createTempDir();
PluginInfo info = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info, pluginDir);
List<PluginsService.Bundle> sortedBundles = PluginsService.sortBundles(Collections.singleton(bundle));
assertThat(sortedBundles, Matchers.contains(bundle));
}
public void testSortBundlesNoDeps() throws Exception {
Path pluginDir = createTempDir();
Set<PluginsService.Bundle> bundles = new LinkedHashSet<>(); // control iteration order
PluginInfo info1 = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle1 = new PluginsService.Bundle(info1, pluginDir);
bundles.add(bundle1);
PluginInfo info2 = new PluginInfo("bar", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle2 = new PluginsService.Bundle(info2, pluginDir);
bundles.add(bundle2);
PluginInfo info3 = new PluginInfo("baz", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle3 = new PluginsService.Bundle(info3, pluginDir);
bundles.add(bundle3);
List<PluginsService.Bundle> sortedBundles = PluginsService.sortBundles(bundles);
assertThat(sortedBundles, Matchers.contains(bundle1, bundle2, bundle3));
}
public void testSortBundlesMissingDep() throws Exception {
Path pluginDir = createTempDir();
PluginInfo info = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Collections.singletonList("dne"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info, pluginDir);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () ->
PluginsService.sortBundles(Collections.singleton(bundle))
);
assertEquals("Missing plugin [dne], dependency of [foo]", e.getMessage());
}
public void testSortBundlesCommonDep() throws Exception {
Path pluginDir = createTempDir();
Set<PluginsService.Bundle> bundles = new LinkedHashSet<>(); // control iteration order
PluginInfo info1 = new PluginInfo("grandparent", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle1 = new PluginsService.Bundle(info1, pluginDir);
bundles.add(bundle1);
PluginInfo info2 = new PluginInfo("foo", "desc", "1.0", "MyPlugin", Collections.singletonList("common"), false, false);
PluginsService.Bundle bundle2 = new PluginsService.Bundle(info2, pluginDir);
bundles.add(bundle2);
PluginInfo info3 = new PluginInfo("bar", "desc", "1.0", "MyPlugin", Collections.singletonList("common"), false, false);
PluginsService.Bundle bundle3 = new PluginsService.Bundle(info3, pluginDir);
bundles.add(bundle3);
PluginInfo info4 = new PluginInfo("common", "desc", "1.0", "MyPlugin", Collections.singletonList("grandparent"), false, false);
PluginsService.Bundle bundle4 = new PluginsService.Bundle(info4, pluginDir);
bundles.add(bundle4);
List<PluginsService.Bundle> sortedBundles = PluginsService.sortBundles(bundles);
assertThat(sortedBundles, Matchers.contains(bundle1, bundle4, bundle2, bundle3));
}
public void testSortBundlesAlreadyOrdered() throws Exception {
Path pluginDir = createTempDir();
Set<PluginsService.Bundle> bundles = new LinkedHashSet<>(); // control iteration order
PluginInfo info1 = new PluginInfo("dep", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle1 = new PluginsService.Bundle(info1, pluginDir);
bundles.add(bundle1);
PluginInfo info2 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Collections.singletonList("dep"), false, false);
PluginsService.Bundle bundle2 = new PluginsService.Bundle(info2, pluginDir);
bundles.add(bundle2);
List<PluginsService.Bundle> sortedBundles = PluginsService.sortBundles(bundles);
assertThat(sortedBundles, Matchers.contains(bundle1, bundle2));
}
public static class DummyClass1 {}
public static class DummyClass2 {}
public static class DummyClass3 {}
void makeJar(Path jarFile, Class... classes) throws Exception {
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(jarFile))) {
for (Class clazz : classes) {
String relativePath = clazz.getCanonicalName().replaceAll("\\.", "/") + ".class";
if (relativePath.contains(PluginsServiceTests.class.getSimpleName())) {
// static inner class of this test
relativePath = relativePath.replace("/" + clazz.getSimpleName(), "$" + clazz.getSimpleName());
}
Path codebase = PathUtils.get(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
if (codebase.toString().endsWith(".jar")) {
// copy from jar, exactly as is
out.putNextEntry(new ZipEntry(relativePath));
try (ZipInputStream in = new ZipInputStream(Files.newInputStream(codebase))) {
ZipEntry entry = in.getNextEntry();
while (entry != null) {
if (entry.getName().equals(relativePath)) {
byte[] buffer = new byte[10*1024];
int read = in.read(buffer);
while (read != -1) {
out.write(buffer, 0, read);
read = in.read(buffer);
}
break;
}
in.closeEntry();
entry = in.getNextEntry();
}
}
} else {
// copy from dir, and use a different canonical path to not conflict with test classpath
out.putNextEntry(new ZipEntry("test/" + clazz.getSimpleName() + ".class"));
Files.copy(codebase.resolve(relativePath), out);
}
out.closeEntry();
}
}
}
public void testJarHellDuplicateCodebaseWithDep() throws Exception {
Path pluginDir = createTempDir();
Path dupJar = pluginDir.resolve("dup.jar");
makeJar(dupJar);
Map<String, Set<URL>> transitiveDeps = new HashMap<>();
transitiveDeps.put("dep", Collections.singleton(dupJar.toUri().toURL()));
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Collections.singletonList("dep"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.checkBundleJarHell(bundle, transitiveDeps));
assertEquals("failed to load plugin myplugin due to jar hell", e.getMessage());
assertThat(e.getCause().getMessage(), containsString("jar hell! duplicate codebases with extended plugin"));
}
public void testJarHellDuplicateCodebaseAcrossDeps() throws Exception {
Path pluginDir = createTempDir();
Path pluginJar = pluginDir.resolve("plugin.jar");
makeJar(pluginJar, DummyClass1.class);
Path otherDir = createTempDir();
Path dupJar = otherDir.resolve("dup.jar");
makeJar(dupJar, DummyClass2.class);
Map<String, Set<URL>> transitiveDeps = new HashMap<>();
transitiveDeps.put("dep1", Collections.singleton(dupJar.toUri().toURL()));
transitiveDeps.put("dep2", Collections.singleton(dupJar.toUri().toURL()));
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Arrays.asList("dep1", "dep2"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.checkBundleJarHell(bundle, transitiveDeps));
assertEquals("failed to load plugin myplugin due to jar hell", e.getMessage());
assertThat(e.getCause().getMessage(), containsString("jar hell!"));
assertThat(e.getCause().getMessage(), containsString("duplicate codebases"));
}
// Note: testing dup codebase with core is difficult because it requires a symlink, but we have mock filesystems and security manager
public void testJarHellDuplicateClassWithCore() throws Exception {
// need a jar file of core dep, use log4j here
Path pluginDir = createTempDir();
Path pluginJar = pluginDir.resolve("plugin.jar");
makeJar(pluginJar, Level.class);
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Collections.emptyList(), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.checkBundleJarHell(bundle, new HashMap<>()));
assertEquals("failed to load plugin myplugin due to jar hell", e.getMessage());
assertThat(e.getCause().getMessage(), containsString("jar hell!"));
assertThat(e.getCause().getMessage(), containsString("Level"));
}
public void testJarHellDuplicateClassWithDep() throws Exception {
Path pluginDir = createTempDir();
Path pluginJar = pluginDir.resolve("plugin.jar");
makeJar(pluginJar, DummyClass1.class);
Path depDir = createTempDir();
Path depJar = depDir.resolve("dep.jar");
makeJar(depJar, DummyClass1.class);
Map<String, Set<URL>> transitiveDeps = new HashMap<>();
transitiveDeps.put("dep", Collections.singleton(depJar.toUri().toURL()));
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Collections.singletonList("dep"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.checkBundleJarHell(bundle, transitiveDeps));
assertEquals("failed to load plugin myplugin due to jar hell", e.getMessage());
assertThat(e.getCause().getMessage(), containsString("jar hell!"));
assertThat(e.getCause().getMessage(), containsString("DummyClass1"));
}
public void testJarHellDuplicateClassAcrossDeps() throws Exception {
Path pluginDir = createTempDir();
Path pluginJar = pluginDir.resolve("plugin.jar");
makeJar(pluginJar, DummyClass1.class);
Path dep1Dir = createTempDir();
Path dep1Jar = dep1Dir.resolve("dep1.jar");
makeJar(dep1Jar, DummyClass2.class);
Path dep2Dir = createTempDir();
Path dep2Jar = dep2Dir.resolve("dep2.jar");
makeJar(dep2Jar, DummyClass2.class);
Map<String, Set<URL>> transitiveDeps = new HashMap<>();
transitiveDeps.put("dep1", Collections.singleton(dep1Jar.toUri().toURL()));
transitiveDeps.put("dep2", Collections.singleton(dep2Jar.toUri().toURL()));
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Arrays.asList("dep1", "dep2"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
IllegalStateException e = expectThrows(IllegalStateException.class, () ->
PluginsService.checkBundleJarHell(bundle, transitiveDeps));
assertEquals("failed to load plugin myplugin due to jar hell", e.getMessage());
assertThat(e.getCause().getMessage(), containsString("jar hell!"));
assertThat(e.getCause().getMessage(), containsString("DummyClass2"));
}
public void testJarHellTransitiveMap() throws Exception {
Path pluginDir = createTempDir();
Path pluginJar = pluginDir.resolve("plugin.jar");
makeJar(pluginJar, DummyClass1.class);
Path dep1Dir = createTempDir();
Path dep1Jar = dep1Dir.resolve("dep1.jar");
makeJar(dep1Jar, DummyClass2.class);
Path dep2Dir = createTempDir();
Path dep2Jar = dep2Dir.resolve("dep2.jar");
makeJar(dep2Jar, DummyClass3.class);
Map<String, Set<URL>> transitiveDeps = new HashMap<>();
transitiveDeps.put("dep1", Collections.singleton(dep1Jar.toUri().toURL()));
transitiveDeps.put("dep2", Collections.singleton(dep2Jar.toUri().toURL()));
PluginInfo info1 = new PluginInfo("myplugin", "desc", "1.0", "MyPlugin", Arrays.asList("dep1", "dep2"), false, false);
PluginsService.Bundle bundle = new PluginsService.Bundle(info1, pluginDir);
PluginsService.checkBundleJarHell(bundle, transitiveDeps);
Set<URL> deps = transitiveDeps.get("myplugin");
assertNotNull(deps);
assertThat(deps, containsInAnyOrder(pluginJar.toUri().toURL(), dep1Jar.toUri().toURL(), dep2Jar.toUri().toURL()));
}
public void testNonExtensibleDep() throws Exception {
// This test opens a child classloader, reading a jar under the test temp
// dir (a dummy plugin). Classloaders are closed by GC, so when test teardown
// occurs the jar is deleted while the classloader is still open. However, on
// windows, files cannot be deleted when they are still open by a process.
assumeFalse("windows deletion behavior is asinine", Constants.WINDOWS);
Path homeDir = createTempDir();
Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), homeDir).build();
Path pluginsDir = homeDir.resolve("plugins");
Path mypluginDir = pluginsDir.resolve("myplugin");
PluginTestUtil.writePluginProperties(
mypluginDir,
"description", "whatever",
"name", "myplugin",
"version", "1.0.0",
"elasticsearch.version", Version.CURRENT.toString(),
"java.version", System.getProperty("java.specification.version"),
"extended.plugins", "nonextensible",
"classname", "test.DummyPlugin");
try (InputStream jar = PluginsServiceTests.class.getResourceAsStream("dummy-plugin.jar")) {
Files.copy(jar, mypluginDir.resolve("plugin.jar"));
}
Path nonextensibleDir = pluginsDir.resolve("nonextensible");
PluginTestUtil.writePluginProperties(
nonextensibleDir,
"description", "whatever",
"name", "nonextensible",
"version", "1.0.0",
"elasticsearch.version", Version.CURRENT.toString(),
"java.version", System.getProperty("java.specification.version"),
"classname", "test.NonExtensiblePlugin");
try (InputStream jar = PluginsServiceTests.class.getResourceAsStream("non-extensible-plugin.jar")) {
Files.copy(jar, nonextensibleDir.resolve("plugin.jar"));
}
IllegalStateException e = expectThrows(IllegalStateException.class, () -> newPluginsService(settings));
assertEquals("Plugin [myplugin] cannot extend non-extensible plugin [nonextensible]", e.getMessage());
}
}
| |
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.EnumSet;
import java.util.SortedSet;
import java.util.TreeSet;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.lib.RepositoryCacheConfig;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.WindowCacheConfig;
import org.eclipse.jgit.util.FS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Manages Git repositories stored on the local filesystem. */
@Singleton
public class LocalDiskRepositoryManager implements GitRepositoryManager {
private static final Logger log = LoggerFactory.getLogger(LocalDiskRepositoryManager.class);
public static class Module extends LifecycleModule {
@Override
protected void configure() {
listener().to(LocalDiskRepositoryManager.Lifecycle.class);
}
}
public static class Lifecycle implements LifecycleListener {
private final Config serverConfig;
@Inject
Lifecycle(@GerritServerConfig Config cfg) {
this.serverConfig = cfg;
}
@Override
public void start() {
RepositoryCacheConfig repoCacheCfg = new RepositoryCacheConfig();
repoCacheCfg.fromConfig(serverConfig);
repoCacheCfg.install();
WindowCacheConfig cfg = new WindowCacheConfig();
cfg.fromConfig(serverConfig);
if (serverConfig.getString("core", null, "streamFileThreshold") == null) {
long mx = Runtime.getRuntime().maxMemory();
int limit =
(int)
Math.min(
mx / 4, // don't use more than 1/4 of the heap.
2047 << 20); // cannot exceed array length
if ((5 << 20) < limit && limit % (1 << 20) != 0) {
// If the limit is at least 5 MiB but is not a whole multiple
// of MiB round up to the next one full megabyte. This is a very
// tiny memory increase in exchange for nice round units.
limit = ((limit / (1 << 20)) + 1) << 20;
}
String desc;
if (limit % (1 << 20) == 0) {
desc = String.format("%dm", limit / (1 << 20));
} else if (limit % (1 << 10) == 0) {
desc = String.format("%dk", limit / (1 << 10));
} else {
desc = String.format("%d", limit);
}
log.info(String.format("Defaulting core.streamFileThreshold to %s", desc));
cfg.setStreamFileThreshold(limit);
}
cfg.install();
}
@Override
public void stop() {}
}
private final Path basePath;
@Inject
LocalDiskRepositoryManager(SitePaths site, @GerritServerConfig Config cfg) {
basePath = site.resolve(cfg.getString("gerrit", null, "basePath"));
if (basePath == null) {
throw new IllegalStateException("gerrit.basePath must be configured");
}
}
/**
* Return the basePath under which the specified project is stored.
*
* @param name the name of the project
* @return base directory
*/
public Path getBasePath(Project.NameKey name) {
return basePath;
}
@Override
public Repository openRepository(Project.NameKey name) throws RepositoryNotFoundException {
return openRepository(getBasePath(name), name);
}
private Repository openRepository(Path path, Project.NameKey name)
throws RepositoryNotFoundException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
FileKey loc = FileKey.lenient(path.resolve(name.get()).toFile(), FS.DETECTED);
try {
return RepositoryCache.open(loc);
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot open repository " + name);
e2.initCause(e1);
throw e2;
}
}
@Override
public Repository createRepository(Project.NameKey name)
throws RepositoryNotFoundException, RepositoryCaseMismatchException, IOException {
Path path = getBasePath(name);
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File dir = FileKey.resolve(path.resolve(name.get()).toFile(), FS.DETECTED);
if (dir != null) {
// Already exists on disk, use the repository we found.
//
Project.NameKey onDiskName = getProjectName(path, dir.getCanonicalFile().toPath());
if (!onDiskName.equals(name)) {
throw new RepositoryCaseMismatchException(name);
}
throw new IllegalStateException("Repository already exists: " + name);
}
// It doesn't exist under any of the standard permutations
// of the repository name, so prefer the standard bare name.
//
String n = name.get() + Constants.DOT_GIT_EXT;
FileKey loc = FileKey.exact(path.resolve(n).toFile(), FS.DETECTED);
try {
Repository db = RepositoryCache.open(loc, false);
db.create(true /* bare */);
StoredConfig config = db.getConfig();
config.setBoolean(
ConfigConstants.CONFIG_CORE_SECTION,
null,
ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES,
true);
config.save();
// JGit only writes to the reflog for refs/meta/config if the log file
// already exists.
//
File metaConfigLog = new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
log.error(
String.format(
"Failed to create ref log for %s in repository %s", RefNames.REFS_CONFIG, name));
}
return db;
} catch (IOException e1) {
final RepositoryNotFoundException e2;
e2 = new RepositoryNotFoundException("Cannot create repository " + name);
e2.initCause(e1);
throw e2;
}
}
private boolean isUnreasonableName(Project.NameKey nameKey) {
final String name = nameKey.get();
return name.length() == 0 // no empty paths
|| name.charAt(name.length() - 1) == '/' // no suffix
|| name.indexOf('\\') >= 0 // no windows/dos style paths
|| name.charAt(0) == '/' // no absolute paths
|| new File(name).isAbsolute() // no absolute paths
|| name.startsWith("../") // no "l../etc/passwd"
|| name.contains("/../") // no "foo/../etc/passwd"
|| name.contains("/./") // "foo/./foo" is insane to ask
|| name.contains("//") // windows UNC path can be "//..."
|| name.contains(".git/") // no path segments that end with '.git' as "foo.git/bar"
|| name.contains("?") // common unix wildcard
|| name.contains("%") // wildcard or string parameter
|| name.contains("*") // wildcard
|| name.contains(":") // Could be used for absolute paths in windows?
|| name.contains("<") // redirect input
|| name.contains(">") // redirect output
|| name.contains("|") // pipe
|| name.contains("$") // dollar sign
|| name.contains("\r") // carriage return
|| name.contains("/+") // delimiter in /changes/
|| name.contains("~"); // delimiter in /changes/
}
@Override
public SortedSet<Project.NameKey> list() {
ProjectVisitor visitor = new ProjectVisitor(basePath);
scanProjects(visitor);
return Collections.unmodifiableSortedSet(visitor.found);
}
protected void scanProjects(ProjectVisitor visitor) {
try {
Files.walkFileTree(
visitor.startFolder,
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE,
visitor);
} catch (IOException e) {
log.error("Error walking repository tree " + visitor.startFolder.toAbsolutePath(), e);
}
}
private static Project.NameKey getProjectName(Path startFolder, Path p) {
String projectName = startFolder.relativize(p).toString();
if (File.separatorChar != '/') {
projectName = projectName.replace(File.separatorChar, '/');
}
if (projectName.endsWith(Constants.DOT_GIT_EXT)) {
int newLen = projectName.length() - Constants.DOT_GIT_EXT.length();
projectName = projectName.substring(0, newLen);
}
return new Project.NameKey(projectName);
}
protected class ProjectVisitor extends SimpleFileVisitor<Path> {
private final SortedSet<Project.NameKey> found = new TreeSet<>();
private Path startFolder;
public ProjectVisitor(Path startFolder) {
setStartFolder(startFolder);
}
public void setStartFolder(Path startFolder) {
this.startFolder = startFolder;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
if (!dir.equals(startFolder) && isRepo(dir)) {
addProject(dir);
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
log.warn(e.getMessage());
return FileVisitResult.CONTINUE;
}
private boolean isRepo(Path p) {
String name = p.getFileName().toString();
return !name.equals(Constants.DOT_GIT)
&& (name.endsWith(Constants.DOT_GIT_EXT)
|| FileKey.isGitRepository(p.toFile(), FS.DETECTED));
}
private void addProject(Path p) {
Project.NameKey nameKey = getProjectName(startFolder, p);
if (getBasePath(nameKey).equals(startFolder)) {
if (isUnreasonableName(nameKey)) {
log.warn("Ignoring unreasonably named repository " + p.toAbsolutePath());
} else {
found.add(nameKey);
}
}
}
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.command.undo;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.actions.ReformatCodeProcessor;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.mock.Mock;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.impl.CurrentEditorProvider;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TestDialog;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.*;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.FutureTask;
public class GlobalUndoTest extends UndoTestCase implements TestDialog {
private TestDialog myOldTestDialogValue;
private PsiClass myClass;
private VirtualFile myDir;
private static final String myDirName = "dir1";
private VirtualFile myDir1;
private VirtualFile myDir2;
private VirtualFile myDirToMove;
private VirtualFile myDirToRename;
private static final String DIR_TO_RENAME_NAME = "dirToRename.txt";
private static final String NEW_NAME = "NewName";
private boolean myConfirmationWasRequested = false;
private static final String DIR_NAME = "dir.txt";
private PsiJavaFile myContainingFile;
@Override
protected void setUp() throws Exception {
super.setUp();
myOldTestDialogValue = Messages.setTestDialog(this);
}
@Override
protected void tearDown() throws Exception {
try {
Messages.setTestDialog(myOldTestDialogValue);
myContainingFile = null;
myClass = null;
}
finally {
super.tearDown();
}
}
@Override
public int show(String message) {
myConfirmationWasRequested = true;
return 0;
}
public void testCreateClassIsUndoableAction() {
createClass("Class");
globalUndo();
}
public void testUndoDeleteClass() {
String className = "TestClass";
createClass(className);
String contentBefore = getDocumentText(findFile(className, myRoot));
deleteClass();
for (int i = 0; i < 2; i++) {
globalUndo();
assertFileExists(className, contentBefore);
globalUndo();
assertFileDoesNotExist(className, myRoot);
globalRedo();
assertFileExists(className, contentBefore);
globalRedo();
assertFileDoesNotExist(className, myRoot);
}
}
public void testUndoCreateClassTwice() {
createClass("TestClass1");
createClass("TestClass2");
Editor editor = openEditor("TestClass2.java");
undo(editor);
globalUndo();
ApplicationManager.getApplication().saveAll();
checkAllFilesDeleted();
}
public void testUndoRenameClass() {
String firstClassName = "Class1";
String secondClassName = "Class223467234678234678236478263478";
createClass(firstClassName);
renameClassTo(secondClassName);
assertFileExists(myRoot, secondClassName);
assertFileDoesNotExist(firstClassName, myRoot);
for (int i = 0; i < 2; i++) {
globalUndo();
assertFileExists(myRoot, firstClassName);
assertFileDoesNotExist(secondClassName, myRoot);
globalRedo();
assertFileExists(myRoot, secondClassName);
assertFileDoesNotExist(firstClassName, myRoot);
}
}
public void testUndoRenameWithCaseChangeClass() {
final VirtualFile f = createChildData(myRoot, "Foo.txt");
executeCommand(() -> rename(f, "FOO.txt"));
assertEquals("FOO.txt", f.getName());
for (int i = 0; i < 2; i++) {
globalUndo();
assertEquals("Foo.txt", f.getName());
globalRedo();
assertEquals("FOO.txt", f.getName());
}
}
private void renameClassTo(final String newClassName) {
executeCommand((Command)() -> new RenameProcessor(myProject, myClass, newClassName, true, true).run(), "Rename Class");
}
public void testUndoAfterEmptyReformat() {
createClass("foo");
final PsiFile file = myContainingFile;
final Editor editor = openEditor("foo.java");
reformatFile(file);
undo(editor);
assertFileDoesNotExist("foo", myRoot);
}
private void reformatFile(final PsiFile file) throws IncorrectOperationException {
final Runnable r = new ReformatCodeProcessor(myProject, file, null, false) {
@Override
@NotNull
public FutureTask<Boolean> preprocessFile(@NotNull final PsiFile file, boolean processChangedTextOnly)
throws IncorrectOperationException {
return super.preprocessFile(file, false);
}
}.preprocessFile(file, false);
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(r), "Reformat", null,
UndoConfirmationPolicy.REQUEST_CONFIRMATION);
}
public void testUndoMoveFile() {
VirtualFile dir1 = createChildDirectory(myRoot, myDirName);
VirtualFile dir2 = createChildDirectory(myRoot, "dir2");
String className = "Class1";
createClass(className, dir1);
assertFileExists(dir1, className);
assertFileDoesNotExist(className, dir2);
moveClassTo(dir2);
assertFileExists(dir2, className);
assertFileDoesNotExist(className, dir1);
globalUndo();
assertFileExists(dir1, className);
assertFileDoesNotExist(className, dir2);
globalRedo();
assertFileExists(dir2, className);
assertFileDoesNotExist(className, dir1);
}
public void testRedoCreateAndMove() {
final VirtualFile dir = createChildDirectory(myRoot, "dir");
final VirtualFile[] f = new VirtualFile[1];
executeCommand(() -> {
f[0] = createChildData(myRoot, "foo.txt");
setDocumentText(f[0], "foo");
});
executeCommand(() -> {
move(f[0], dir);
setDocumentText(f[0], "foobar");
});
globalUndo();
globalUndo();
assertNull(myRoot.findChild("foo.txt"));
globalRedo();
f[0] = myRoot.findChild("foo.txt");
assertNotNull(f[0]);
assertEquals("foo", getDocumentText(f[0]));
globalRedo();
assertEquals(dir, f[0].getParent());
assertEquals("foobar", getDocumentText(f[0]));
}
public void testRestoringUndoStackForDocumentWhenItIsRecreatedWithSameName() {
final VirtualFile[] f = new VirtualFile[1];
executeCommand(() -> {
f[0] = createChildData(myRoot, "foo.txt");
setDocumentText(f[0], "foo");
});
executeCommand(() -> setDocumentText(f[0], "foofoo"));
undo(getEditor(f[0]));
undo(getEditor(f[0]));
assertNull(myRoot.findChild("foo.txt"));
globalRedo();
f[0] = myRoot.findChild("foo.txt");
assertNotNull(f[0]);
assertEquals("foo", getDocumentText(f[0]));
redo(getEditor(f[0]));
assertEquals("foofoo", getDocumentText(f[0]));
}
protected static VirtualFile createChildData(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) {
try {
return WriteAction.computeAndWait(() ->
// requestor must be notnull
dir.createChildData(dir, name));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
protected static void delete(@NotNull final VirtualFile file) {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
// requestor must be notnull
file.delete(file);
}
catch (IOException e) {
throw new RuntimeException();
}
});
}
public void testDoNotConfuseRecreatedFilesWithDeleted() {
final VirtualFile[] f = new VirtualFile[1];
executeCommand(() -> {
f[0] = createChildData(myRoot, "foo.txt");
setDocumentText(f[0], "foo");
});
executeCommand(() -> setDocumentText(f[0], "foofoo"));
executeCommand(() -> delete(f[0]));
executeCommand(() -> f[0] = createChildData(myRoot, "foo.txt"));
assertGlobalRedoNotAvailable();
assertRedoNotAvailable(getEditor(f[0]));
undo(getEditor(f[0])); // should undo creation, not editing of previous document
assertNull(myRoot.findChild("foo.txt"));
globalUndo();
f[0] = myRoot.findChild("foo.txt");
assertNotNull(f[0]);
assertEquals("foofoo", getDocumentText(f[0]));
undo(getEditor(f[0]));
assertEquals("foo", getDocumentText(f[0]));
}
public void testDeletionOfNoneJavaFiles() {
VirtualFile f = createChildData(myRoot, "f.xxx");
deleteInCommand(f);
assertGlobalUndoIsAvailable();
globalUndo();
assertNotNull(myRoot.findChild("f.xxx"));
}
public void testUndoDeleteDir() {
createDirectory(myDirName);
checkDirExists();
deleteDirectory();
checkDirDoesNotExist();
globalUndo();
checkDirExists();
globalRedo();
checkDirDoesNotExist();
}
protected static VirtualFile createChildDirectory(@NotNull final VirtualFile dir, @NotNull @NonNls final String name) {
try {
return WriteAction.computeAndWait(() ->
// requestor must be notnull
dir.createChildDirectory(dir, name));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public void testUndoRenameDirectoryWithFile() {
final VirtualFile[] dir = new VirtualFile[1];
final VirtualFile[] file = new VirtualFile[1];
executeCommand(() -> {
dir[0] = createChildDirectory(myRoot, "dir");
file[0] = createChildData(dir[0], "file.txt");
});
setDocumentText(file[0], "document");
executeCommand(() -> {
rename(dir[0], "dir2");
setDocumentText(file[0], "document2");
});
for (int i = 0; i < 2; i++) {
globalUndo();
assertNull(myRoot.findChild("dir2"));
dir[0] = myRoot.findChild("dir");
assertNotNull(dir);
file[0] = dir[0].findChild("file.txt");
assertNotNull(file[0]);
assertEquals("document", getDocumentText(file[0]));
globalRedo();
assertNull(myRoot.findChild("dir"));
dir[0] = myRoot.findChild("dir2");
assertNotNull(dir);
file[0] = dir[0].findChild("file.txt");
assertNotNull(file[0]);
assertEquals("document2", getDocumentText(file[0]));
}
}
public void testUndoDeleteDirectoryWithFile() {
final VirtualFile[] dir = new VirtualFile[1];
final VirtualFile[] file = new VirtualFile[1];
executeCommand(() -> {
dir[0] = createChildDirectory(myRoot, "dir");
file[0] = createChildData(dir[0], "file.txt");
});
setDocumentText(file[0], "document");
executeCommand(() -> delete(dir[0]));
for (int i = 0; i < 2; i++) {
globalUndo();
dir[0] = myRoot.findChild("dir");
assertNotNull(dir);
file[0] = dir[0].findChild("file.txt");
assertNotNull(file[0]);
assertEquals("document", getDocumentText(file[0]));
globalRedo();
assertNull(myRoot.findChild("dir"));
}
}
public void testUndoDirectoryMovingToExistingDirectory() throws IOException {
createTestProjectStructureAndMoveDirectory();
File ioDir = createDirOnTheDirToMovePlaceWithTheSameName();
checkSuccessfulMoveUndo(ioDir);
}
public void testUndoDirectoryMovingToExistingFile() throws IOException {
createTestProjectStructureAndMoveDirectory();
File ioDir = createFileOnTheDirToMovePlaceWithTheSameName();
checkSuccessfulMoveUndo(ioDir);
}
private void createTestProjectStructureAndMoveDirectory() throws IOException {
WriteCommandAction.writeCommandAction(getProject()).run(() -> {
createDirectory("parent");
myDir1 = myDir.createChildDirectory(this, "dir1");
myDir2 = myDir.createChildDirectory(this, "dir2");
myDirToMove = myDir1.createChildDirectory(this, DIR_NAME);
myDirToMove.createChildData(this, "file.txt");
});
CommandProcessor.getInstance().executeCommand(myProject, () -> move(myDirToMove, myDir2), "Moving", null);
}
private File createFileOnTheDirToMovePlaceWithTheSameName() throws IOException {
File ioDir = new File(VfsUtilCore.virtualToIoFile(myDir1), DIR_NAME);
ioDir.createNewFile();
refreshFileSystem();
return ioDir;
}
private File createDirOnTheDirToMovePlaceWithTheSameName() {
File ioDir = new File(VfsUtilCore.virtualToIoFile(myDir1), DIR_NAME);
ioDir.mkdir();
refreshFileSystem();
return ioDir;
}
private void checkSuccessfulMoveUndo(File ioDir) {
globalUndo();
assertTrue(new File(ioDir, "file.txt").exists());
assertNull(myDir2.findChild(DIR_NAME));
}
public void testUndoDirectoryRenamingToExistingDirectory() {
createTestProjectStructureAndRenameDirectory();
File ioDir = createDirOnTheDirToRenamePlaceWithTheSameName();
checkSuccessfulRenameUndo(ioDir);
}
public void testUndoDirectoryRenamingToExistingFile() throws IOException {
createTestProjectStructureAndRenameDirectory();
File ioDir = createFileOnTheDirToRenamePlaceWithTheSameName();
checkSuccessfulRenameUndo(ioDir);
}
// ignored because some problems with weak references in filedocumentmanager
public void testCanUndoDocumentAfterExternalChange() throws Exception {
final VirtualFile f = createChildData(myRoot, "f.txt");
executeCommand(() -> setDocumentText(f, "doc"));
Document doc = FileDocumentManager.getInstance().getDocument(f); // prevent weak refs from being collected
FileDocumentManager.getInstance().saveAllDocuments(); // prevent 'file has been changed dialog'
File ioFile = new File(f.getPath());
FileUtil.writeToFile(ioFile, "external".getBytes());
ioFile.setLastModified(f.getTimeStamp() + 2000);
LocalFileSystem.getInstance().refresh(false);
assertEquals("external", getDocumentText(f));
Editor editor = getEditor(f);
assertGlobalUndoNotAvailable();
assertUndoIsAvailable(editor);
undo(editor);
assertEquals("doc", getDocumentText(f));
undo(editor);
assertEquals("", getDocumentText(f));
redo(editor);
assertEquals("doc", getDocumentText(f));
redo(editor);
assertEquals("external", getDocumentText(f));
}
public void testCanUndoAfterFileWasDeletedAndWhenCreatedExternally() throws IOException {
VirtualFile f = createChildData(myRoot, "f.txt");
final VirtualFile finalF = f;
executeCommand(() -> setDocumentText(finalF, "doc"));
executeCommand(() -> delete(finalF));
File ioFile = new File(f.getPath());
FileUtil.writeToFile(ioFile, "external".getBytes());
LocalFileSystem.getInstance().refresh(false);
f = myRoot.findChild("f.txt");
assertNotNull(f);
assertEquals("external", getDocumentText(f));
Editor editor = getEditor(f);
assertGlobalUndoIsAvailable();
assertUndoIsAvailable(editor);
undo(editor);
assertEquals("doc", getDocumentText(f));
undo(editor);
assertEquals("", getDocumentText(f));
redo(editor);
assertEquals("doc", getDocumentText(f));
// todo
//redo(editor);
//assertEquals("external", getDocumentText(f));
}
public void testDoNotRecordDocumentChangesWhenFileChangedExternallyAndNoChangesRecordedYet() throws IOException {
VirtualFile f = createChildData(myRoot, "f.txt");
Document d = FileDocumentManager.getInstance().getDocument(f); // make sure the document is cached.
File ioFile = new File(f.getPath());
FileUtil.writeToFile(ioFile, "external".getBytes());
ioFile.setLastModified(f.getTimeStamp() + 2000);
LocalFileSystem.getInstance().refresh(false);
assertEquals("external", getDocumentText(f));
assertGlobalUndoNotAvailable();
assertUndoNotAvailable(getEditor(f));
}
public void testGlobalUndoIsAvaliableWhenFileChangedExternallyWithForceFlag() {
String fileName = "f.txt";
String projectFileName = "proj.txt";
VirtualFile f = createChildData(myRoot, projectFileName);
executeCommand(() -> {
createChildData(myRoot, fileName);
// Rider case, modify externally and refresh some file in a command
File ioFile = new File(f.getPath());
FileUtil.writeToFile(ioFile, "content".getBytes());
ioFile.setLastModified(f.getTimeStamp() + 2000);
f.putUserData(UndoConstants.FORCE_RECORD_UNDO, true);
f.refresh(false, true);
});
assertGlobalUndoIsAvailable();
assertNotNull(myRoot.findChild(fileName));
globalUndo();
assertNull(myRoot.findChild(fileName));
}
public void testRecordDocumentChangesWhenFileChangedExternallyAndAlreadyHasChanges() throws IOException {
final VirtualFile f = createChildData(myRoot, "f.txt");
executeCommand(() -> setDocumentText(f, "doc"));
assertGlobalUndoNotAvailable();
assertUndoIsAvailable(getEditor(f));
undo(getEditor(f)); // clear undo stack, but preserve the change in redo stack
File ioFile = new File(f.getPath());
FileUtil.writeToFile(ioFile, "external".getBytes());
ioFile.setLastModified(f.getTimeStamp() + 2000);
LocalFileSystem.getInstance().refresh(false);
assertEquals("external", getDocumentText(f));
assertGlobalUndoNotAvailable();
assertUndoIsAvailable(getEditor(f));
}
public void testUndoRedoNotAvailableAfterFileWasDeletedExternally() {
final VirtualFile f1 = createChildData(myRoot, "f1.txt");
final VirtualFile f2 = createChildData(myRoot, "f2.txt");
executeCommand(() -> {
rename(f1, "ff1.txt");
setDocumentText(f1, "ff1");
});
executeCommand(() -> {
rename(f2, "ff2.txt");
setDocumentText(f2, "ff2");
});
// <---- test point
executeCommand(() -> {
rename(f2, "fff2.txt");
setDocumentText(f2, "fff2");
});
executeCommand(() -> {
rename(f1, "fff1.txt");
setDocumentText(f1, "fff1");
});
globalUndo();
assertGlobalUndoIsAvailable();
assertGlobalRedoIsAvailable();
globalUndo();
assertGlobalUndoIsAvailable();
assertGlobalRedoIsAvailable();
delete(f1); // commands for f1 should be invalidated here
assertGlobalUndoIsAvailable();
assertGlobalRedoIsAvailable();
globalRedo();
assertGlobalUndoIsAvailable();
assertGlobalRedoNotAvailable();
globalUndo();
globalUndo(); // back to the 'test point'
assertGlobalUndoNotAvailable();
assertGlobalRedoIsAvailable();
}
public void testCanUndoDocumentsAfterSave() {
FileDocumentManager dm = FileDocumentManager.getInstance();
EditorFactory ef = EditorFactory.getInstance();
VirtualFile f = createChildData(myRoot, "f.java");
Document d = dm.getDocument(f);
Editor e = ef.createEditor(d);
assertEquals("", d.getText());
typeInText(e, "12345");
assertEquals("12345", d.getText());
dm.saveDocument(d);
undo(e);
ef.releaseEditor(e);
assertEquals("", d.getText());
}
public void testClearingRedoStackClearsGlobalCommandsCorrectly() {
final VirtualFile[] f1 = new VirtualFile[1];
final VirtualFile[] f2 = new VirtualFile[1];
final VirtualFile[] f3 = new VirtualFile[1];
executeCommand(() -> {
f1[0] = createChildData(myRoot, "f1.java");
f2[0] = createChildData(myRoot, "f2.java");
f3[0] = createChildData(myRoot, "f3.java");
});
for (VirtualFile each : FileEditorManager.getInstance(myProject).getOpenFiles()) {
FileEditorManager.getInstance(myProject).closeFile(each);
}
executeCommand(() -> {
setDocumentText(f1[0], "f1");
setDocumentText(f2[0], "f2");
});
executeCommand(() -> setDocumentText(f3[0], "f3"));
undo(getEditor(f3[0]));
undo(null);
assertEquals("", getDocumentText(f1[0]));
assertEquals("", getDocumentText(f3[0]));
assertRedoIsAvailable(null);
assertRedoIsAvailable(getEditor(f1[0]));
assertRedoIsAvailable(getEditor(f2[0]));
assertRedoIsAvailable(getEditor(f3[0]));
for (VirtualFile each : FileEditorManager.getInstance(myProject).getOpenFiles()) {
FileEditorManager.getInstance(myProject).closeFile(each);
}
executeCommand(() -> setDocumentText(f1[0], "ff1"));
assertRedoNotAvailable(null);
assertRedoNotAvailable(getEditor(f1[0]));
assertRedoNotAvailable(getEditor(f2[0]));
assertRedoIsAvailable(getEditor(f3[0]));
}
public void testRegisteringOpenDocumentWhenAnotherFileIsAffected() {
final VirtualFile[] f1 = new VirtualFile[1];
final VirtualFile[] f2 = new VirtualFile[1];
final VirtualFile[] f3 = new VirtualFile[1];
f1[0] = createChildData(myRoot, "f1.java");
f2[0] = createChildData(myRoot, "f2.java");
f3[0] = createChildData(myRoot, "f3.java");
executeCommand(() -> setDocumentText(f1[0], "f1"));
assertUndoNotAvailable(null);
assertUndoIsAvailable(getEditor(f1[0]));
assertUndoNotAvailable(getEditor(f2[0]));
assertUndoNotAvailable(getEditor(f3[0]));
myEditor = openEditor(f2[0]);
executeCommand(() -> setDocumentText(f1[0], "f1"));
assertUndoIsAvailable(null);
assertUndoIsAvailable(getEditor(f1[0]));
assertUndoIsAvailable(getEditor(f2[0]));
assertUndoNotAvailable(getEditor(f3[0]));
}
public void testRegisteringOpenDocumentForReadOnlyFileDoesNotBreakUndoChain() throws Exception {
final VirtualFile f1 = createChildData(myRoot, "f1.java");
final VirtualFile f2 = createChildData(myRoot, "f2.java");
final VirtualFile f3 = createChildData(myRoot, "f3.java");
WriteAction.runAndWait(() -> f2.setWritable(false));
executeCommand(() -> setDocumentText(f1, "initial"));
assertUndoNotAvailable(null);
assertUndoIsAvailable(getEditor(f1));
assertUndoNotAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
myEditor = openEditor(f2);
executeCommand(() -> setDocumentText(f1, "new content"));
assertUndoIsAvailable(null);
assertUndoIsAvailable(getEditor(f1));
assertUndoIsAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
undo(getEditor(f2));
assertEquals("initial", getDocumentText(f1));
}
public void testDoNotRegisterOpenDocumentWhenAnotherFileReloaded() throws Exception {
final VirtualFile f1 = createChildData(myRoot, "f1.java");
final VirtualFile f2 = createChildData(myRoot, "f2.java");
executeCommand(() -> setDocumentText(f1, "f1"));
executeCommand(() -> {
setDocumentText(f2, "f2");
FileDocumentManager.getInstance().saveDocument(getDocument(f2));
});
assertUndoNotAvailable(null);
assertUndoIsAvailable(getEditor(f1));
assertUndoIsAvailable(getEditor(f2));
myEditor = openEditor(f1);
File file = new File(f2.getPath());
FileUtil.writeToFile(file, "reloaded");
file.setLastModified(file.lastModified() + 10000);
LocalFileSystem.getInstance().refreshIoFiles(Collections.singletonList(file));
assertUndoNotAvailable(null);
assertUndoIsAvailable(getEditor(f1));
assertUndoIsAvailable(getEditor(f2));
// undo open document first
undo(getEditor(f1));
assertEquals("", getDocumentText(f1));
undo(getEditor(f2));
assertEquals("f2", getDocumentText(f2));
}
public void testClearingRedoStackClearsGlobalCommandsCorrectlyIntersectingStacks() {
final VirtualFile[] f1 = new VirtualFile[1];
final VirtualFile[] f2 = new VirtualFile[1];
final VirtualFile[] f3 = new VirtualFile[1];
final VirtualFile[] f4 = new VirtualFile[1];
executeCommand(() -> {
f1[0] = createChildData(myRoot, "f1.java");
f2[0] = createChildData(myRoot, "f2.java");
f3[0] = createChildData(myRoot, "f3.java");
f4[0] = createChildData(myRoot, "f4.java");
});
executeCommand(() -> {
setDocumentText(f1[0], "f1");
setDocumentText(f2[0], "f2");
});
executeCommand(() -> {
setDocumentText(f3[0], "f3");
setDocumentText(f4[0], "f4");
});
undo(null);
undo(null);
assertEquals("", getDocumentText(f1[0]));
assertEquals("", getDocumentText(f3[0]));
assertRedoIsAvailable(null);
assertRedoIsAvailable(getEditor(f1[0]));
assertRedoIsAvailable(getEditor(f2[0]));
assertRedoIsAvailable(getEditor(f3[0]));
assertRedoIsAvailable(getEditor(f4[0]));
executeCommand(() -> setDocumentText(f1[0], "ff1"));
assertRedoNotAvailable(null);
assertRedoNotAvailable(getEditor(f1[0]));
assertRedoNotAvailable(getEditor(f2[0]));
assertRedoNotAvailable(getEditor(f3[0]));
assertRedoNotAvailable(getEditor(f4[0]));
}
public void testClearingRedoStackClearsStackNotTooMuch() {
final VirtualFile[] f1 = new VirtualFile[1];
final VirtualFile[] f2 = new VirtualFile[1];
executeCommand(() -> {
f1[0] = createChildData(myRoot, "f1.java");
f2[0] = createChildData(myRoot, "f2.java");
});
executeCommand(() -> setDocumentText(f1[0], "f1"));
executeCommand(() -> {
setDocumentText(f1[0], "ff1");
setDocumentText(f2[0], "ff2");
});
undo(getEditor(f1[0]));
undo(getEditor(f1[0]));
assertEquals("", getDocumentText(f1[0]));
assertEquals("", getDocumentText(f2[0]));
assertRedoIsAvailable(null);
assertRedoIsAvailable(getEditor(f1[0]));
assertRedoIsAvailable(getEditor(f2[0]));
executeCommand(() -> setDocumentText(f2[0], "fff2"));
assertRedoNotAvailable(null);
assertRedoIsAvailable(getEditor(f1[0]));
assertRedoNotAvailable(getEditor(f2[0]));
redo(getEditor(f1[0]));
assertEquals("f1", getDocumentText(f1[0]));
}
public void testAddingAffectedDocumentOrFile() {
final VirtualFile f1 = createChildData(myRoot, "f1.java");
final VirtualFile f2 = createChildData(myRoot, "f2.java");
final VirtualFile f3 = createChildData(myRoot, "f3.java");
assertUndoNotAvailable(getEditor(f1));
assertUndoNotAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
CommandProcessor.getInstance().executeCommand(myProject, () -> {
setDocumentText(f1, "foo");
CommandProcessor.getInstance().addAffectedDocuments(myProject, FileDocumentManager.getInstance().getDocument(f2));
CommandProcessor.getInstance().addAffectedFiles(myProject, f3);
}, null, null);
assertUndoIsAvailable(getEditor(f1));
assertUndoIsAvailable(getEditor(f2));
assertUndoIsAvailable(getEditor(f3));
myManager.flushCurrentCommandMerger();
assertUndoIsAvailable(getEditor(f1));
assertUndoIsAvailable(getEditor(f2));
assertUndoIsAvailable(getEditor(f3));
}
public void testAddingAffectedDocumentWhenNoOtherChangesDoesntChangeUndoRedoStacks() {
final VirtualFile f1 = createChildData(myRoot, "f1.java");
final VirtualFile f2 = createChildData(myRoot, "f2.java");
final VirtualFile f3 = createChildData(myRoot, "f3.java");
assertUndoNotAvailable(getEditor(f1));
assertUndoNotAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
CommandProcessor.getInstance().executeCommand(myProject, () -> {
CommandProcessor.getInstance().addAffectedDocuments(myProject, FileDocumentManager.getInstance().getDocument(f2));
CommandProcessor.getInstance().addAffectedFiles(myProject, f3);
}, null, null);
assertUndoNotAvailable(getEditor(f1));
assertUndoNotAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
myManager.flushCurrentCommandMerger();
assertUndoNotAvailable(getEditor(f1));
assertUndoNotAvailable(getEditor(f2));
assertUndoNotAvailable(getEditor(f3));
}
public void testFixRIDER10340() {
createClass("TestClass1");
Editor editor = openEditor("TestClass1.java");
WriteAction.runAndWait(() -> executeCommand(() -> editor.getDocument().insertString(27, "public class Aaa {}")));
PsiDocumentManager instance = PsiDocumentManager.getInstance(myProject);
instance.commitAllDocuments();
PsiFile file = instance.getPsiFile(editor.getDocument());
PsiClass aaaClass = (PsiClass)(file.getViewProvider().findElementAt(41).getParent());
IntentionAction fix = QuickFixFactory.getInstance().createMoveClassToSeparateFileFix(aaaClass);
WriteAction.runAndWait(() -> executeCommand(() -> fix.invoke(myProject, editor, file)));
instance.commitAllDocuments();
VirtualFile aaaFile = file.getVirtualFile().getParent().findChild("Aaa.java");
deleteInCommand(aaaFile);
undo(editor);
undo(editor);
assertEquals("public class TestClass1 {\n}public class Aaa {}\n", editor.getDocument().getText());
}
public void testPerformance() {
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
@Override
public void run() {
try {
VirtualFile dir1 = myRoot.createChildDirectory(this, "dir1");
VirtualFile dir2 = myRoot.createChildDirectory(this, "dir2");
dir1.createChildData(this, "f.java");
dir1.move(this, dir2);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
PlatformTestUtil.assertTiming("", 2000, 1, () -> {
redoUndo();
redoUndo();
redoUndo();
});
}
private void redoUndo() {
globalUndo();
globalRedo();
}
public void testRedoIsNotAvailableAfterFileChanges() {
final VirtualFile f = createChildData(myRoot, "f.java");
renameInCommand(f, "ff.java");
globalUndo();
assertGlobalRedoIsAvailable();
renameInCommand(f, "fff.java");
assertGlobalRedoNotAvailable();
}
public void testUndoRedoFileWithChangedDocument() throws Exception {
File directory = createTempDirectory(true);
VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(directory);
assertNotNull(file);
final String[] path = new String[1];
executeCommand(() -> {
PsiFile f = createFile(myModule, file, "foo.txt", "initial");
Document doc = PsiDocumentManager.getInstance(myProject).getDocument(f);
setDocumentText(doc, "document");
path[0] = f.getVirtualFile().getPath();
});
globalUndo();
globalRedo();
VirtualFile f = LocalFileSystem.getInstance().findFileByPath(path[0]);
assertNotNull(f);
assertEquals("initial", VfsUtilCore.loadText(f));
Document doc = FileDocumentManager.getInstance().getDocument(f);
assertEquals("document", doc.getText());
}
public void testUndoRedoFileWithChangedDocumentWithSeveralAffectedFiles() throws Exception {
final String[] path = new String[2];
executeCommand(() -> {
VirtualFile f = createChildData(myRoot, "foo1.txt");
setBinaryContent(f, "initial1".getBytes());
Document doc = FileDocumentManager.getInstance().getDocument(f);
setDocumentText(doc, "document1");
path[0] = f.getPath();
f = createChildData(myRoot, "foo2.txt");
setBinaryContent(f, "initial2".getBytes());
doc = FileDocumentManager.getInstance().getDocument(f);
setDocumentText(doc, "document2");
path[1] = f.getPath();
});
globalUndo();
globalRedo();
VirtualFile f = LocalFileSystem.getInstance().findFileByPath(path[0]);
assertNotNull(f);
assertEquals("initial1", VfsUtilCore.loadText(f));
Document doc = FileDocumentManager.getInstance().getDocument(f);
assertEquals("document1", doc.getText());
f = LocalFileSystem.getInstance().findFileByPath(path[1]);
assertNotNull(f);
assertEquals("initial2", VfsUtilCore.loadText(f));
doc = FileDocumentManager.getInstance().getDocument(f);
assertEquals("document2", doc.getText());
}
private static void setDocumentText(final Document doc, final String document2) {
ApplicationManager.getApplication().runWriteAction(() -> doc.setText(document2));
}
public void testUndoRedoFileMoveAndDeleteWithChangedDocument() throws Exception {
final String[] path = new String[1];
final VirtualFile[] dir = new VirtualFile[1];
final VirtualFile[] f = new VirtualFile[1];
executeCommand(() -> {
dir[0] = createChildDirectory(myRoot, "dir");
f[0] = createChildData(myRoot, "foo.txt");
setBinaryContent(f[0], "initial".getBytes());
setDocumentText(f[0], "document");
path[0] = f[0].getPath();
});
executeCommand(() -> {
move(f[0], dir[0]);
setDocumentText(f[0], "moved");
});
executeCommand(() -> delete(dir[0]));
globalUndo();
f[0] = LocalFileSystem.getInstance().findFileByPath(f[0].getPath());
dir[0] = LocalFileSystem.getInstance().findFileByPath(dir[0].getPath());
assertNotNull(f[0]);
assertNotNull(dir[0]);
assertEquals(dir[0], f[0].getParent());
assertEquals("moved", VfsUtilCore.loadText(f[0]));
Document doc = FileDocumentManager.getInstance().getDocument(f[0]);
assertEquals("moved", doc.getText());
globalUndo();
assertEquals(myRoot, f[0].getParent());
assertEquals("moved", VfsUtilCore.loadText(f[0]));
doc = FileDocumentManager.getInstance().getDocument(f[0]);
assertEquals("document", doc.getText());
globalUndo();
globalRedo();
f[0] = LocalFileSystem.getInstance().findFileByPath(f[0].getPath());
dir[0] = LocalFileSystem.getInstance().findFileByPath(dir[0].getPath());
assertEquals(myRoot, f[0].getParent());
assertEquals("initial", VfsUtilCore.loadText(f[0]));
doc = FileDocumentManager.getInstance().getDocument(f[0]);
assertEquals("document", doc.getText());
globalRedo();
assertEquals(dir[0], f[0].getParent());
assertEquals("initial", VfsUtilCore.loadText(f[0]));
doc = FileDocumentManager.getInstance().getDocument(f[0]);
assertEquals("moved", doc.getText());
}
private void renameInCommand(final VirtualFile f, final String name) {
executeCommand(() -> rename(f, name));
}
private void checkSuccessfulRenameUndo(File ioDir) {
try {
globalUndo();
}
catch (Exception ex) {
fail("Unexpected exception: " + ex.getLocalizedMessage());
}
assertTrue(new File(ioDir, "file.txt").exists());
assertNull(myDir.findChild(NEW_NAME));
}
private File createDirOnTheDirToRenamePlaceWithTheSameName() {
File result = new File(VfsUtilCore.virtualToIoFile(myDirToRename.getParent()), DIR_TO_RENAME_NAME);
result.mkdir();
refreshFileSystem();
return result;
}
private File createFileOnTheDirToRenamePlaceWithTheSameName() throws IOException {
File result = new File(VfsUtilCore.virtualToIoFile(myDirToRename.getParent()), DIR_TO_RENAME_NAME);
result.createNewFile();
refreshFileSystem();
return result;
}
private void createTestProjectStructureAndRenameDirectory() {
createDirectory("parent");
myDirToRename = createChildDirectory(myDir, DIR_TO_RENAME_NAME);
createChildData(myDirToRename, "file.txt");
CommandProcessor.getInstance().executeCommand(myProject, () -> rename(myDirToRename, NEW_NAME), "Renaming", null);
}
private static void refreshFileSystem() {
VirtualFileManager.getInstance().syncRefresh();
}
private void deleteInCommand(final VirtualFile f) {
executeCommand((Command)() -> delete(f), "Delete file");
}
private void checkDirDoesNotExist() {
assertNull(myRoot.findChild(myDirName));
}
private void checkDirExists() {
VirtualFile file = myRoot.findChild(myDirName);
assertNotNull(file);
assertTrue(file.isValid());
}
private void createDirectory(final String name) {
executeCommand((Command)() -> myDir = createChildDirectory(myRoot, name), "Create Directory");
}
private void deleteDirectory() {
Command command = () -> delete(myDir);
executeCommand(command, "Delete Directory");
}
private void moveClassTo(final VirtualFile dirTo) {
Command command = () -> {
VirtualFile file = myClass.getContainingFile().getVirtualFile();
move(file, dirTo);
};
executeCommand(command, "Move class to a new dir");
}
public void testSCR5784() throws Exception {
myFile = createFile("Test.java", "abcd efgh ijk");
myEditor = createEditor(myFile.getVirtualFile());
myManager.setEditorProvider(new CurrentEditorProvider() {
@Override
public FileEditor getCurrentEditor() {
return TextEditorProvider.getInstance().getTextEditor(myEditor);
}
});
final SelectionModel selectionModel = myEditor.getSelectionModel();
final CaretModel caretModel = myEditor.getCaretModel();
final Document document = myEditor.getDocument();
selectionModel.setSelection(0, 4);
caretModel.moveToOffset(4);
String text0 = document.getText();
int caret0 = caretModel.getOffset();
int selStart0 = selectionModel.getSelectionStart();
int selEnd0 = selectionModel.getSelectionEnd();
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
selectionModel.removeSelection();
document.insertString(document.getTextLength(), "abcd");
selectionModel.setSelection(document.getTextLength() - "abcd".length(), document.getTextLength());
}), "Command 1", "DndGroup");
CommandProcessor.getInstance()
.executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> document.deleteString(0, "abcd".length())),
"Command 2", "DndGroup");
CommandProcessor.getInstance().executeCommand(myProject, EmptyRunnable.getInstance(), "Command 3", null);
String text1 = document.getText();
int caret1 = caretModel.getOffset();
int selStart1 = selectionModel.getSelectionStart();
int selEnd1 = selectionModel.getSelectionEnd();
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
selectionModel.removeSelection();
document.insertString(4, "abcd");
selectionModel.setSelection(4, 4 + "abcd".length());
}), "Command 4", "DndGroup");
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication()
.runWriteAction(() -> document.deleteString(document.getTextLength() - "abcd".length(), document.getTextLength())), "Command 5",
"DndGroup");
undo(myEditor);
assertEquals(text1, document.getText());
assertEquals(caret1, caretModel.getOffset());
assertEquals(selStart1, selectionModel.getSelectionStart());
assertEquals(selEnd1, selectionModel.getSelectionEnd());
undo(myEditor);
assertEquals(text0, document.getText());
assertEquals(caret0, caretModel.getOffset());
assertEquals(selStart0, selectionModel.getSelectionStart());
assertEquals(selEnd0, selectionModel.getSelectionEnd());
}
public void testEditorWithSeveralDocumentsUndo() {
final VirtualFile file1 = createChildData(myRoot, "file1.txt");
final VirtualFile file2 = createChildData(myRoot, "file2.txt");
final Document document1 = FileDocumentManager.getInstance().getDocument(file1);
final Document document2 = FileDocumentManager.getInstance().getDocument(file2);
Mock.MyFileEditor fileEditor = new Mock.MyFileEditor();
fileEditor.DOCUMENTS = new Document[]{document1, document2};
UndoManager undoManager = UndoManager.getInstance(myProject);
CommandProcessor.getInstance()
.executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> document2.replaceString(0, 0, "text2")),
"test_command", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
assertTrue(undoManager.isUndoAvailable(fileEditor));
undoManager.undo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("", document2.getText());
undoManager.redo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("text2", document2.getText());
changeText(document1, "");
changeText(document2, "");
changeText(document1, "text1");
changeText(document2, "text2");
assertTrue(undoManager.isUndoAvailable(fileEditor));
undoManager.undo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("text1", document1.getText());
assertEquals("", document2.getText());
undoManager.undo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("", document2.getText());
undoManager.redo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("text1", document1.getText());
assertEquals("", document2.getText());
undoManager.redo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("text1", document1.getText());
assertEquals("text2", document2.getText());
//check documents changes backward
changeText(document1, "");
changeText(document2, "");
changeText(document2, "text2");
changeText(document1, "text1");
assertTrue(undoManager.isUndoAvailable(fileEditor));
undoManager.undo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("text2", document2.getText());
assertEquals("", document1.getText());
undoManager.undo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("", document2.getText());
undoManager.redo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("text2", document2.getText());
undoManager.redo(fileEditor);
assertFalse(myConfirmationWasRequested);
assertEquals("text1", document1.getText());
assertEquals("text2", document2.getText());
}
public void testMergingSeveralDocumentCommands() {
final VirtualFile[] files = new VirtualFile[3];
files[0] = createChildData(myRoot, "f1.txt");
files[1] = createChildData(myRoot, "f2.txt");
files[2] = createChildData(myRoot, "f3.txt");
executeCommand(() -> setDocumentText(files[0], "text1"), "command", "ID");
executeCommand(() -> setDocumentText(files[1], "text2"), "command", "ID");
executeCommand(() -> setDocumentText(files[2], "text3"), "command", "ID");
//assertGlobalUndoIsAvailable();
assertUndoIsAvailable(getEditor(files[0]));
assertUndoIsAvailable(getEditor(files[1]));
assertUndoIsAvailable(getEditor(files[2]));
//globalUndo();
undo(getEditor(files[0]));
assertEquals("", getDocumentText(files[0]));
assertEquals("", getDocumentText(files[1]));
assertEquals("", getDocumentText(files[2]));
//assertGlobalUndoNotAvailable();
assertUndoNotAvailable(getEditor(files[0]));
assertUndoNotAvailable(getEditor(files[1]));
assertUndoNotAvailable(getEditor(files[2]));
//assertGlobalRedoIsAvailable();
assertRedoIsAvailable(getEditor(files[0]));
assertRedoIsAvailable(getEditor(files[1]));
assertRedoIsAvailable(getEditor(files[2]));
//globalRedo();
redo(getEditor(files[0]));
assertEquals("text1", getDocumentText(files[0]));
assertEquals("text2", getDocumentText(files[1]));
assertEquals("text3", getDocumentText(files[2]));
}
public void testUndoConfirmationPolicy() {
doTest(UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, false);
doTest(UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, UndoConfirmationPolicy.REQUEST_CONFIRMATION, true);
doTest(UndoConfirmationPolicy.REQUEST_CONFIRMATION, UndoConfirmationPolicy.REQUEST_CONFIRMATION, true);
doTest(UndoConfirmationPolicy.REQUEST_CONFIRMATION, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, true);
doTest(UndoConfirmationPolicy.DEFAULT, UndoConfirmationPolicy.DEFAULT, true);
doTest(UndoConfirmationPolicy.REQUEST_CONFIRMATION, UndoConfirmationPolicy.DEFAULT, true);
doTest(UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, UndoConfirmationPolicy.DEFAULT, false);
doTest(UndoConfirmationPolicy.DEFAULT, UndoConfirmationPolicy.REQUEST_CONFIRMATION, true);
doTest(UndoConfirmationPolicy.DEFAULT, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, false);
}
private void doTest(UndoConfirmationPolicy policy1, UndoConfirmationPolicy policy2, boolean expected) {
final VirtualFile file1 = createChildData(myRoot, "file1.txt");
final VirtualFile file2 = createChildData(myRoot, "file2.txt");
final Document document1 = FileDocumentManager.getInstance().getDocument(file1);
final Document document2 = FileDocumentManager.getInstance().getDocument(file2);
String groupId = "ID";
changeText(document1, "text1", policy1, groupId);
changeText(document2, "text2", policy2, groupId);
UndoManager undoManager = UndoManager.getInstance(myProject);
Mock.MyFileEditor fileEditor = new Mock.MyFileEditor();
fileEditor.DOCUMENTS = new Document[]{document1, document2};
assertTrue(undoManager.isUndoAvailable(fileEditor));
undoManager.undo(fileEditor);
assertEquals(expected, myConfirmationWasRequested);
assertEquals("", document1.getText());
assertEquals("", document2.getText());
delete(file1);
delete(file2);
myConfirmationWasRequested = false;
}
private void changeText(final Document document1, final String text) {
changeText(document1, text, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION, null);
}
private void changeText(final Document document1, final String text, UndoConfirmationPolicy policy, String groupId) {
CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication()
.runWriteAction(() -> document1.replaceString(0, document1.getTextLength(), text)), "test_command", groupId, policy);
}
protected void assertFileExists(String fileName, String content) {
assertFileExists(myRoot, fileName, content);
}
private void assertFileExists(VirtualFile dir, String fileName, String content) {
assertFileExists(dir, fileName);
assertEquals(content, getDocumentText(findFile(fileName, dir)));
}
private void assertFileDoesNotExist(String fileName, VirtualFile dir) {
assertNull(findFile(fileName, dir));
}
private void assertFileExists(VirtualFile dir, String fileName) {
ApplicationManager.getApplication().saveAll();
assertNotNull(findFile(fileName, dir));
}
protected VirtualFile findFile(String className, VirtualFile dir) {
return dir.findChild(className + ".java");
}
public void setDocumentText(final VirtualFile f, final String text) {
ApplicationManager.getApplication().runWriteAction(() -> FileDocumentManager.getInstance().getDocument(f).setText(text));
}
public String getDocumentText(VirtualFile f) {
return FileDocumentManager.getInstance().getDocument(f).getText();
}
private void checkAllFilesDeleted() {
assertEquals(0, myRoot.getChildren().length);
}
private Editor openEditor(String fileName) {
return openEditor(myRoot.findChild(fileName));
}
private Editor openEditor(VirtualFile file) {
assertNotNull(file);
return FileEditorManager.getInstance(myProject).openTextEditor(new OpenFileDescriptor(myProject, file), false);
}
protected void deleteClass() {
executeCommand((Command)() -> ApplicationManager.getApplication().runWriteAction(() -> myClass.delete()), "Delete Class");
}
protected void createClass(@NonNls final String name) {
createClass(name, myRoot);
}
protected PsiJavaFile createClass(final String name, final VirtualFile dir) {
executeCommand((Command)() -> {
ApplicationManager.getApplication().runWriteAction(() -> {
myClass = JavaDirectoryService.getInstance().createClass(myPsiManager.findDirectory(dir), name);
myClass = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myClass);
});
myContainingFile = (PsiJavaFile)myClass.getContainingFile();
}, "Create Class" + name);
return myContainingFile;
}
}
| |
package com.github.dieterdepaepe.jsearch.datastructure.collection;
import com.google.common.collect.ForwardingNavigableSet;
import java.util.*;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A {@link NavigableSet} implementation based on a {@link TreeSet} with
* capacity constraints. The elements are ordered using their natural ordering,
* or by a {@link Comparator} provided at set creation time, depending
* on which constructor is used. The set has a maximum size and will
* preserve the highest or lowest elements that have been added to it,
* depending on the {@link Conserve} criteria specified during creation.
* This means that adding an element might include an implicit removal of
* another element.
*
* <p>This implementation provides guaranteed log(n) time cost for the basic
* operations ({@code add}, {@code remove} and {@code contains}).</p>
*
* <p>Note that the ordering maintained by a set (whether or not an explicit
* comparator is provided) must be <i>consistent with equals</i> if it is to
* correctly implement the {@code Set} interface. (See {@code Comparable}
* or {@code Comparator} for a precise definition of <i>consistent with
* equals</i>.) This is so because the {@code Set} interface is defined in
* terms of the {@code equals} operation, but a {@code TreeSet} instance
* performs all element comparisons using its {@code compareTo} (or
* {@code compare}) method, so two elements that are deemed equal by this method
* are, from the standpoint of the set, equal. The behavior of a set
* <i>is</i> well-defined even if its ordering is inconsistent with equals; it
* just fails to obey the general contract of the {@code Set} interface.</p>
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access the set concurrently, and at least one
* of the threads modifies the set, it <i>must</i> be synchronized
* externally.</p>
*
* <p>The iterators returned by this class's {@code iterator} method are
* <i>fail-fast</i>: if the set is modified at any time after the iterator is
* created, in any way except through the iterator's own {@code remove}
* method, the iterator will throw a {@link ConcurrentModificationException}.
* Thus, in the face of concurrent modification, the iterator fails quickly
* and cleanly, rather than risking arbitrary, non-deterministic behavior at
* an undetermined time in the future.</p>
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i></p>
*
* @param <E> the type of elements maintained by this set
* @author Dieter De Paepe
*/
public class DroppingTreeSet<E> extends ForwardingNavigableSet<E> {
private TreeSet<E> innerSet;
private int maximumSize;
private Conserve conserve;
/**
* Constructs a new, empty, capacity-constrained tree set, sorted according to the specified
* comparator. All elements inserted into the set must be <i>mutually
* comparable</i> by the specified comparator: {@code comparator.compare(e1, e2)}
* must not throw a {@code ClassCastException} for any elements
* {@code e1} and {@code e2} in the set. If the user attempts to add
* an element to the set that violates this constraint, the
* {@code add} call will throw a {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this set.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the elements will be used.
* @param maximumSize the maximum capacity of this set
* @param conserve the specification of which elements should be dropped when
* the set would grow beyond its {@code maximumSize}
* @throws IllegalArgumentException if {@code maximumSize < 0}
* @throws NullPointerException if {@code discardStrategy} is {@code null}
*/
public DroppingTreeSet(Comparator<? super E> comparator, int maximumSize, Conserve conserve) {
checkArgument(maximumSize >= 0, "Maximum size should be >= 0.");
checkNotNull(conserve);
this.innerSet = new TreeSet<>(comparator);
this.maximumSize = maximumSize;
this.conserve = conserve;
}
/**
* Constructs a new, empty, capacity-constrained tree set, sorted according to the
* natural ordering of its elements. All elements inserted into
* the set must implement the {@link Comparable} interface.
* Furthermore, all such elements must be <i>mutually
* comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set. If the user attempts to add an element
* to the set that violates this constraint (for example, the user
* attempts to add a string element to a set whose elements are
* integers), the {@code add} call will throw a
* {@code ClassCastException}.
*
* @param maximumSize the maximum capacity of this set
* @param conserve the specification of which elements should be dropped when
* the set would grow beyond its {@code maximumSize}
* @throws IllegalArgumentException if {@code maximumSize < 0}
* @throws NullPointerException if {@code discardStrategy} is {@code null}
*/
public DroppingTreeSet(int maximumSize, Conserve conserve) {
this((Comparator<E>) null, maximumSize, conserve);
}
/**
* Constructs a new, capacity-constrained tree set containing the same elements and
* using the same ordering as the specified sorted set.
*
* @param sortedSet sorted set whose elements will comprise the new set
* @param maximumSize the maximum capacity of this set
* @param conserve the specification of which elements should be dropped when
* the set would grow beyond its {@code maximumSize}
* @throws NullPointerException if the specified sorted set or {@code discardStrategy} is {@code null}
* @throws IllegalArgumentException if {@code maximumSize < 0} or
* if the specified sorted set is larger than {@code maximumSize}
*/
public DroppingTreeSet(SortedSet<E> sortedSet, int maximumSize, Conserve conserve) throws IllegalArgumentException {
this(sortedSet.comparator(), maximumSize, conserve);
checkArgument(maximumSize >= sortedSet.size(), "Specified set is larger than allowed capacity: (%d > %d).", sortedSet.size(), maximumSize);
this.addAll(sortedSet);
}
/**
* Constructs a new, limited-capacity tree set containing the elements in the specified
* collection, sorted according to the <i>natural ordering</i> of its
* elements. All elements inserted into the set must implement the
* {@link Comparable} interface. Furthermore, all such elements must be
* <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set.
*
* @param collection collection whose elements will comprise the new set
* @param maximumSize the maximum capacity of this set
* @param conserve the specification of which elements should be dropped when
* the set would grow beyond its {@code maximumSize}
* @throws ClassCastException if the elements in {@code c} are
* not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException if the specified collection or {@code discardStrategy} is null
* @throws IllegalArgumentException if {@code maximumSize < 0} or if the specified
* collection has more than {@code maximumSize} equal objects
*/
public DroppingTreeSet(Collection<? extends E> collection, int maximumSize, Conserve conserve) {
this(maximumSize, conserve);
for (E element : collection) {
boolean maxSizeWasReached = size() == maximumSize;
if (innerAdd(element) != AdditionResult.SET_NOT_MODIFIED && maxSizeWasReached)
throw new IllegalArgumentException("Specified collection cannot fit in this set.");
}
}
/**
* Inserts the specified element into the set if it is not already present.
* Since this set tracks only a limited set of items, another item might be
* dropped from the set as a result, or the specified element itself may not
* end up in the set.
* This method is generally preferable to the {@link #add(Object)} method,
* because is returns {@code false} rather than throwing an exception when
* the item is refused by the set due to capacity constraints.
*
* @param element the element to add
* @return <tt>true</tt> if the element was added to this set, else <tt>false</tt>
* @throws ClassCastException if the specified object cannot be compared
* with the elements currently in this set
* @throws NullPointerException if the specified element is null
* and this set uses natural ordering, or its comparator
* does not permit null elements
* @see #add(Object)
*/
public boolean offer(E element) {
AdditionResult result = innerAdd(element);
return result == AdditionResult.ITEM_ADDED;
}
/**
* Offers all of the elements in the specified collection to this set.
*
* @param collection collection containing elements to be offered to this set
* @return {@code true} if this set changed as a result of the call
* @throws ClassCastException if the elements provided cannot be compared
* with the elements currently in the set
* @throws NullPointerException if the specified collection is null or
* if any element is null and this set uses natural ordering, or
* its comparator does not permit null elements
*/
public boolean offerAll(Collection<? extends E> collection) {
boolean isModified = false;
for (E element : collection)
isModified |= offer(element);
return isModified;
}
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element {@code e} to this set if
* the set contains no element {@code e2} such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns {@code false}. Since this set tracks only a
* limited set of elements, another stored element might be dropped or the
* specified element itself may be refused by the set. In the latter case
* an {@link IllegalArgumentException} is thrown, as specified
* in {@link Collection#add(Object)}.
*
* @param element element to be added to this set
* @return {@code true} if this set did not already contain the specified
* element
* @throws ClassCastException if the specified object cannot be compared
* with the elements currently in this set
* @throws NullPointerException if the specified element is null
* and this set uses natural ordering, or its comparator
* does not permit null elements
* @throws IllegalArgumentException if the element is refused by the set due to its maximum capacity
* @see #offer(Object)
*/
@Override
public boolean add(E element) {
AdditionResult result = innerAdd(element);
if (result == AdditionResult.ITEM_ADDED)
return true;
else if (result == AdditionResult.SET_NOT_MODIFIED)
return false;
else
throw new IllegalArgumentException("Element refused due to size constraints.");
}
/**
* Adds all of the elements in the specified collection to this set by calling {@link #add(Object)}
* for each element. Because a specific element might be refused by the set when the set
* has reached its maximum capacity, resulting in an exception, this method may or may not
* throw an exception depending on the iteration order of the specified collection.
* Because of this, it is typically preferred to use {@link #offerAll(java.util.Collection)} instead.
*
* @param collection collection containing elements to be added to this set
* @return {@code true} if this set changed as a result of the call
* @throws ClassCastException if the elements provided cannot be compared
* with the elements currently in the set
* @throws NullPointerException if the specified collection is null or
* if any element is null and this set uses natural ordering, or
* its comparator does not permit null elements
* @throws IllegalArgumentException if any element was immediately refused by the set due to size constraints
* @see #offerAll(java.util.Collection)
*/
@Override
public boolean addAll(Collection<? extends E> collection) {
return standardAddAll(collection);
}
private AdditionResult innerAdd(E element) {
boolean added = innerSet.add(element);
if (!added)
return AdditionResult.SET_NOT_MODIFIED;
if (innerSet.size() <= maximumSize)
return AdditionResult.ITEM_ADDED;
E elementRemoved;
if (conserve == Conserve.HIGHEST)
elementRemoved = innerSet.pollFirst();
else
elementRemoved = innerSet.pollLast();
if (elementRemoved == element)
return AdditionResult.ITEM_REFUSED;
else
return AdditionResult.ITEM_ADDED;
}
@Override
protected NavigableSet<E> delegate() {
return innerSet;
}
/**
* Definition of which items to conserve when items have to be purged due to capacity constraints.
*/
public enum Conserve {
HIGHEST,
LOWEST
}
private enum AdditionResult {
SET_NOT_MODIFIED,
ITEM_ADDED,
ITEM_REFUSED
}
}
| |
package com.abstractthis.consoul;
//The MIT License (MIT)
//
//Copyright (c) 2013 David Smith <www.abstractthis.com>
//
//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.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import com.abstractthis.consoul.commands.ConsoleCommand;
import com.abstractthis.consoul.commands.DefaultConsoleCommand;
import com.abstractthis.consoul.widgets.Widget;
final class ConsoleDisplay {
private final ExecutorService outputExec = Executors.newSingleThreadExecutor();
private final ExecutorService inputExec = Executors.newSingleThreadExecutor();
private final ConsoleApplication app;
private final ConsoleInputParser inputParser;
private String promptText;
public ConsoleDisplay(ConsoleApplication app, ConsoleInputParser parser) {
this.app = app;
this.inputParser = parser == null ? new DefaultConsoleInputParser() : parser;
}
public ConsoleOutPipe getNewOutPipe() {
return new ConsoleOutPipe(this);
}
public String getPromptText() {
return this.promptText;
}
public void attach() {
try {
inputExec.submit(new ConsoleInputTask());
}
catch(RejectedExecutionException ignored) {
System.out.println("attach task rejected.");
}
}
public void detach() throws InterruptedException {
inputExec.shutdownNow();
outputExec.shutdown();
outputExec.awaitTermination(2000, TimeUnit.MILLISECONDS);
}
public void render(String output) {
try {
outputExec.submit(new StringOutputTask(output));
}
catch(RejectedExecutionException ignored) {}
}
public void render(char c) {
try {
outputExec.submit(new CharOutputTask(c));
}
catch(RejectedExecutionException ignored) {}
}
public void render(String output, boolean useNewline) {
try {
outputExec.submit(new StringOutputTask(output, useNewline));
}
catch(RejectedExecutionException ignored) {}
}
public void render(Widget widget) {
try {
outputExec.submit(new WidgetOutputTask(widget));
}
catch(RejectedExecutionException ignored) {}
}
public void render(String[] output) {
try {
List<String> outputList = Arrays.asList(output);
outputExec.submit(new StringOutputTask(outputList));
}
catch(RejectedExecutionException ignored) {}
}
public void render(String[] output, boolean useNewline) {
try {
List<String> outputList = Arrays.asList(output);
outputExec.submit(new StringOutputTask(outputList, useNewline));
}
catch(RejectedExecutionException ignored) {}
}
public void render(Widget[] widgets) {
try {
List<Widget> outputList = Arrays.asList(widgets);
outputExec.submit(new WidgetOutputTask(outputList));
}
catch(RejectedExecutionException ignored) {}
}
public void setPromptText(String promptTxt) {
this.promptText = promptTxt;
}
private class ConsoleInputTask implements Callable<Void> {
public Void call() throws Exception {
Scanner inputScan = new Scanner(System.in);
String input = inputScan.nextLine();
ConsoleCommand cmd = ConsoleDisplay.this.inputParser.parse(input);
if( cmd != null ) ConsoleDisplay.this.app.executeCommand(cmd);
else ConsoleDisplay.this.render(new PromptWidget(ConsoleDisplay.this));
return null;
}
}
private static class CharOutputTask implements Callable<Void> {
private final char ch;
public CharOutputTask(char c) {
this.ch = c;
}
public Void call() throws Exception {
System.out.print(ch);
return null;
}
}
private static class StringOutputTask implements Callable<Void> {
private final List<String> multipleOutput;
private final String output;
private final boolean newline;
public StringOutputTask(String outMsg) {
this.output = outMsg;
this.multipleOutput = null;
this.newline = true;
}
public StringOutputTask(String outMsg, boolean useNewline) {
this.output = outMsg;
this.multipleOutput = null;
this.newline = useNewline;
}
public StringOutputTask(List<String> outMsgs) {
this.multipleOutput = new ArrayList<String>(outMsgs);
this.output = null;
this.newline = true;
}
public StringOutputTask(List<String> outMsgs, boolean useNewline) {
this.multipleOutput = new ArrayList<String>(outMsgs);
this.output = null;
this.newline = useNewline;
}
public Void call() throws Exception {
if( this.output == null ) {
for(String outMsg : multipleOutput) {
if( this.newline ) {
System.out.println(outMsg);
}
else {
System.out.print(outMsg);
}
}
}
else {
if( this.newline ) {
System.out.println(this.output);
}
else {
System.out.print(this.output);
}
}
return null;
}
}
private static class WidgetOutputTask implements Callable<Void> {
private final List<Widget> widgets;
private final Widget widget;
public WidgetOutputTask(Widget widget) {
this.widget = widget;
this.widgets = null;
}
public WidgetOutputTask(List<Widget> widgets) {
this.widgets = widgets;
this.widget = null;
}
public Void call() throws Exception {
if( this.widget == null ) {
for(Widget w : widgets) {
w.render(System.out);
}
}
else {
widget.render(System.out);
}
return null;
}
}
private class DefaultConsoleInputParser implements ConsoleInputParser {
public ConsoleCommand parse(String cmdStr) {
ConsoleCommand cc = null;
if( cmdStr != null ) {
cmdStr = cmdStr.trim();
if( cmdStr.length() > 0 ) {
String[] splitCmd = cmdStr.split(" ");
if( splitCmd.length == 1 ) {
cc = new DefaultConsoleCommand(splitCmd[0], new String[0]);
}
else {
String[] params = this.copyParameters(splitCmd);
cc = new DefaultConsoleCommand(splitCmd[0], params);
}
}
}
return cc;
}
private String[] copyParameters(String[] orig) {
String[] copy = new String[orig.length - 1];
for(int i = 0; i < copy.length; i++) {
copy[i] = orig[i + 1];
}
return copy;
}
}
}
| |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.engine.requests;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.overhead.OverheadProducer;
import com.intellij.debugger.ui.overhead.OverheadTimings;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.SimpleColoredComponent;
import com.sun.jdi.*;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.MethodEntryEvent;
import com.sun.jdi.event.MethodExitEvent;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.MethodEntryRequest;
import com.sun.jdi.request.MethodExitRequest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Eugene Zhuravlev
*/
public class MethodReturnValueWatcher implements OverheadProducer {
private static final Logger LOG = Logger.getInstance(MethodReturnValueWatcher.class);
private @Nullable Method myLastExecutedMethod;
private @Nullable Value myLastMethodReturnValue;
private ThreadReference myThread;
private @Nullable MethodEntryRequest myEntryRequest;
private @Nullable Method myEntryMethod;
private @Nullable MethodExitRequest myExitRequest;
private volatile boolean myTrackingEnabled;
private final EventRequestManager myRequestManager;
private final DebugProcess myProcess;
public MethodReturnValueWatcher(EventRequestManager requestManager, DebugProcess process) {
myRequestManager = requestManager;
myProcess = process;
}
private void processMethodExitEvent(MethodExitEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("<- " + event.method());
}
try {
if (Registry.is("debugger.watch.return.speedup") && myEntryMethod != null) {
if (myEntryMethod.equals(event.method())) {
LOG.debug("Now watching all");
enableEntryWatching(true);
myEntryMethod = null;
createExitRequest().enable();
}
else {
return;
}
}
final Method method = event.method();
final Value retVal = event.returnValue();
if (method == null || !DebuggerUtilsEx.isVoid(method)) {
// remember methods with non-void return types only
myLastExecutedMethod = method;
myLastMethodReturnValue = retVal;
}
}
catch (UnsupportedOperationException ex) {
LOG.error(ex);
}
}
private void processMethodEntryEvent(MethodEntryEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("-> " + event.method());
}
try {
if (myEntryRequest != null && myEntryRequest.isEnabled()) {
myExitRequest = createExitRequest();
myExitRequest.addClassFilter(event.method().declaringType());
myEntryMethod = event.method();
myExitRequest.enable();
if (LOG.isDebugEnabled()) {
LOG.debug("Now watching only " + event.method());
}
enableEntryWatching(false);
}
}
catch (VMDisconnectedException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
}
}
private void enableEntryWatching(boolean enable) {
if (myEntryRequest != null) {
myEntryRequest.setEnabled(enable);
}
}
@Nullable
public Method getLastExecutedMethod() {
return myLastExecutedMethod;
}
@Nullable
public Value getLastMethodReturnValue() {
return myLastMethodReturnValue;
}
@Override
public boolean isEnabled() {
return DebuggerSettings.getInstance().WATCH_RETURN_VALUES;
}
@Override
public void setEnabled(final boolean enabled) {
DebuggerSettings.getInstance().WATCH_RETURN_VALUES = enabled;
clear();
}
public boolean isTrackingEnabled() {
return myTrackingEnabled;
}
public void enable(ThreadReference thread) {
setTrackingEnabled(true, thread);
}
public void disable() {
setTrackingEnabled(false, null);
}
private void setTrackingEnabled(boolean trackingEnabled, final ThreadReference thread) {
myTrackingEnabled = trackingEnabled;
updateRequestState(trackingEnabled && isEnabled(), thread);
}
public void clear() {
myLastExecutedMethod = null;
myLastMethodReturnValue = null;
myThread = null;
}
private void updateRequestState(final boolean enabled, @Nullable final ThreadReference thread) {
DebuggerManagerThreadImpl.assertIsManagerThread();
try {
if (myEntryRequest != null) {
myRequestManager.deleteEventRequest(myEntryRequest);
myEntryRequest = null;
}
if (myExitRequest != null) {
myRequestManager.deleteEventRequest(myExitRequest);
myExitRequest = null;
}
if (enabled) {
OverheadTimings.add(myProcess, this, 1, null);
clear();
myThread = thread;
if (Registry.is("debugger.watch.return.speedup")) {
createEntryRequest().enable();
}
createExitRequest().enable();
}
}
catch (ObjectCollectedException ignored) {
}
}
private static final String WATCHER_REQUEST_KEY = "WATCHER_REQUEST_KEY";
private MethodEntryRequest createEntryRequest() {
DebuggerManagerThreadImpl.assertIsManagerThread(); // to ensure EventRequestManager synchronization
myEntryRequest = prepareRequest(myRequestManager.createMethodEntryRequest());
return myEntryRequest;
}
@NotNull
private MethodExitRequest createExitRequest() {
DebuggerManagerThreadImpl.assertIsManagerThread(); // to ensure EventRequestManager synchronization
if (myExitRequest != null) {
myRequestManager.deleteEventRequest(myExitRequest);
}
myExitRequest = prepareRequest(myRequestManager.createMethodExitRequest());
return myExitRequest;
}
@NotNull
private <T extends EventRequest> T prepareRequest(T request) {
request.setSuspendPolicy(Registry.is("debugger.watch.return.speedup") ? EventRequest.SUSPEND_EVENT_THREAD : EventRequest.SUSPEND_NONE);
if (myThread != null) {
if (request instanceof MethodEntryRequest) {
((MethodEntryRequest)request).addThreadFilter(myThread);
}
else if (request instanceof MethodExitRequest) {
((MethodExitRequest)request).addThreadFilter(myThread);
}
}
request.putProperty(WATCHER_REQUEST_KEY, true);
return request;
}
public boolean processEvent(Event event) {
EventRequest request = event.request();
if (request == null || request.getProperty(WATCHER_REQUEST_KEY) == null) {
return false;
}
if (event instanceof MethodEntryEvent) {
processMethodEntryEvent(((MethodEntryEvent)event));
}
else if (event instanceof MethodExitEvent) {
processMethodExitEvent(((MethodExitEvent)event));
}
return true;
}
@Override
public void customizeRenderer(SimpleColoredComponent renderer) {
renderer.setIcon(AllIcons.Debugger.WatchLastReturnValue);
renderer.append(DebuggerBundle.message("action.watches.method.return.value.enable"));
}
}
| |
package com.amee.platform.science;
import javax.measure.Measure;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* An AMEE abstraction of an amount. An Amount has a value and a unit.
* This class provides unit conversion.
*/
public class Amount {
public final static Amount ZERO = new Amount(0.0);
/** The value */
private double value = 0.0;
/** The unit (default to the dimensionless unit, ONE) */
private AmountUnit unit = AmountUnit.ONE;
/**
* A Amount representing the supplied value and unit.
*
* @param value - the String representation of the value value
* @param unit - the unit of the value value
*/
public Amount(String value, AmountUnit unit) {
this(value);
this.unit = unit;
}
/**
* An Amount representing the supplied unit-less value.
*
* @param value - the String representation of the value.
*/
public Amount(String value) {
if (value == null) {
throw new IllegalArgumentException("The String value must be non-null");
}
// Many value DataItem values in the DB have values of "-" so we need to handle this here.
if (value.isEmpty() || value.equals("-")) {
this.value = 0.0;
} else {
this.value = Double.parseDouble(value);
}
}
public Amount(double value, AmountUnit unit) {
this(value);
this.unit = unit;
}
public Amount(double value) {
this.value = value;
}
/**
* Convert and return a new Amount instance in the target AmountUnit.
*
* @param targetUnit - the target unit
* @return the value in the target unit
* @see AmountUnit
*/
@SuppressWarnings("unchecked")
public Amount convert(AmountUnit targetUnit) {
if (value == 0.0 || unit.equals(targetUnit)) {
return new Amount(getValue(), unit);
} else {
Measure measure = Measure.valueOf(value, unit.toUnit());
double valueInTargetUnit = measure.doubleValue(targetUnit.toUnit());
return new Amount(valueInTargetUnit, targetUnit);
}
}
/**
* Convert and return a new Amount instance in the target AmountPerUnit.
*
* @param targetPerUnit - the target perUnit
* @return the Amount in the target perUnit
* @see AmountPerUnit
*/
@SuppressWarnings("unchecked")
public Amount convert(AmountPerUnit targetPerUnit) {
if (!(unit instanceof AmountCompoundUnit)) return new Amount(value);
AmountCompoundUnit cUnit = (AmountCompoundUnit) unit;
if (cUnit.hasDifferentPerUnit(targetPerUnit)) {
Measure measure = Measure.valueOf(value, cUnit.getPerUnit().toUnit().inverse());
return new Amount(measure.doubleValue(targetPerUnit.toUnit().inverse()), targetPerUnit);
} else {
return new Amount(getValue(), unit);
}
}
/**
* Compares this Amount's unit with the specified AmountUnit for equality.
*
* @param unit - the unit to compare
* @return returns true if the supplied AmountUnit is not considered equal to the unit of the current instance.
*/
public boolean hasDifferentUnits(AmountUnit unit) {
return !this.unit.equals(unit);
}
/**
* Tests if the units of the two Amounts permit the operation.
* Amounts may only be operated upon if they have the same unit or if the given Amount's unit is the dimensionless unit.
*
* @param amount the Amount to be tested.
* @return true if the operation can be performed.
*/
private boolean canOperateOnAmount(Amount amount) {
return amount.unit.equals(unit) || amount.unit.equals(AmountUnit.ONE);
}
public double getValue() {
return value;
}
public AmountUnit getUnit() {
return unit;
}
/**
* Returns the string representation of the value of this Amount in standard decimal notation with a precision
* of up to 17 decimal places. Note that the unit is NOT returned.
*
* @return string representation of this Amount.
*/
@Override
public String toString() {
NumberFormat f = NumberFormat.getInstance();
if (f instanceof DecimalFormat) {
((DecimalFormat) f).applyPattern("0.0################");
}
return f.format(value);
}
/**
* Compares this Amount with the specified Object for equality.
* This method considers two Amount objects equal only if they are equal in value and unit.
*
* @param o Object to which this Amount is to be compared.
* @return true if and only if the specified Object is an Amount whose value and unit are equal to this Amount's.
*/
@Override
public final boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Amount)) {
return false;
}
Amount d = (Amount) o;
return Double.doubleToLongBits(d.value) == Double.doubleToLongBits(this.value)
&& d.unit.equals(this.unit);
}
/**
* Returns the hash code for this Amount.
* Note that two Amount objects that are numerically equal in value but differ in unit will not have the same hash code.
*
* @return hash code for this Amount.
*/
@Override
public int hashCode() {
int result = 17;
// value
Long bits = Double.doubleToLongBits(value);
int valueCode = (int) (bits ^ (bits >>> 32));
result = 37 * result + valueCode;
// unit
int unitCode = unit.hashCode();
result = 37 * result + unitCode;
return result;
}
/**
* Returns an Amount whose value is (this + amount).
*
* @param amount value to be added to this Amount.
* @return this + amount.
* @throws IllegalArgumentException if the unit of amount differs from this unit or AmountUnit.ONE.
*/
public Amount add(Amount amount) {
if (canOperateOnAmount(amount)) {
return new Amount(getValue() + (amount.getValue()), unit);
} else {
throw new IllegalArgumentException("Cannot add unit " + amount.unit + " to unit " + unit);
}
}
/**
* Returns an Amount whose value is (this - amount).
*
* @param amount value to be subtracted from this Amount.
* @return this - amount.
* @throws IllegalArgumentException if the unit of amount differs from this unit or AmountUnit.ONE.
*/
public Amount subtract(Amount amount) {
if (canOperateOnAmount(amount)) {
return new Amount(getValue() - (amount.getValue()), unit);
} else {
throw new IllegalArgumentException("Cannot subtract unit " + amount.unit + " from unit " + unit);
}
}
/**
* Returns an Amount whose value is (this / amount).
*
* @param amount value by which this Amount is to be divided.
* @return this / amount.
* @throws IllegalArgumentException if the unit of amount differs from this unit or AmountUnit.ONE.
*/
public Amount divide(Amount amount) {
if (canOperateOnAmount(amount)) {
return new Amount(getValue() / (amount.getValue()), unit);
} else {
throw new IllegalArgumentException("Cannot divide unit " + amount.unit + " with unit " + unit);
}
}
/**
* Returns an Amount whose value is (this * amount).
*
* @param amount value to be multiplied by this Amount.
* @return this * amount.
* @throws IllegalArgumentException if the unit of amount differs from this unit or AmountUnit.ONE.
*/
public Amount multiply(Amount amount) {
if (canOperateOnAmount(amount)) {
return new Amount(getValue() * (amount.getValue()), unit);
} else {
throw new IllegalArgumentException("Cannot multiply unit " + amount.unit + " with unit " + unit);
}
}
}
| |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.Iterators.advance;
import static com.google.common.collect.Iterators.get;
import static com.google.common.collect.Iterators.getLast;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.testing.NullPointerTester;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.Set;
import java.util.Vector;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for {@code Iterators}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class IteratorsTest extends TestCase {
@GwtIncompatible // suite
public static Test suite() {
TestSuite suite = new TestSuite(IteratorsTest.class.getSimpleName());
suite.addTest(testsForRemoveAllAndRetainAll());
suite.addTestSuite(IteratorsTest.class);
return suite;
}
public void testEmptyIterator() {
Iterator<String> iterator = Iterators.emptyIterator();
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("no exception thrown");
} catch (NoSuchElementException expected) {
}
try {
iterator.remove();
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
}
public void testEmptyListIterator() {
ListIterator<String> iterator = Iterators.emptyListIterator();
assertFalse(iterator.hasNext());
assertFalse(iterator.hasPrevious());
assertEquals(0, iterator.nextIndex());
assertEquals(-1, iterator.previousIndex());
try {
iterator.next();
fail("no exception thrown");
} catch (NoSuchElementException expected) {
}
try {
iterator.previous();
fail("no exception thrown");
} catch (NoSuchElementException expected) {
}
try {
iterator.remove();
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
try {
iterator.set("a");
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
try {
iterator.add("a");
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
}
public void testEmptyModifiableIterator() {
Iterator<String> iterator = Iterators.emptyModifiableIterator();
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expected) {
}
try {
iterator.remove();
fail("Expected IllegalStateException");
} catch (IllegalStateException expected) {
}
}
public void testSize0() {
Iterator<String> iterator = Iterators.emptyIterator();
assertEquals(0, Iterators.size(iterator));
}
public void testSize1() {
Iterator<Integer> iterator = Collections.singleton(0).iterator();
assertEquals(1, Iterators.size(iterator));
}
public void testSize_partiallyConsumed() {
Iterator<Integer> iterator = asList(1, 2, 3, 4, 5).iterator();
iterator.next();
iterator.next();
assertEquals(3, Iterators.size(iterator));
}
public void test_contains_nonnull_yes() {
Iterator<String> set = asList("a", null, "b").iterator();
assertTrue(Iterators.contains(set, "b"));
}
public void test_contains_nonnull_no() {
Iterator<String> set = asList("a", "b").iterator();
assertFalse(Iterators.contains(set, "c"));
}
public void test_contains_null_yes() {
Iterator<String> set = asList("a", null, "b").iterator();
assertTrue(Iterators.contains(set, null));
}
public void test_contains_null_no() {
Iterator<String> set = asList("a", "b").iterator();
assertFalse(Iterators.contains(set, null));
}
public void testGetOnlyElement_noDefault_valid() {
Iterator<String> iterator = Collections.singletonList("foo").iterator();
assertEquals("foo", Iterators.getOnlyElement(iterator));
}
public void testGetOnlyElement_noDefault_empty() {
Iterator<String> iterator = Iterators.emptyIterator();
try {
Iterators.getOnlyElement(iterator);
fail();
} catch (NoSuchElementException expected) {
}
}
public void testGetOnlyElement_noDefault_moreThanOneLessThanFiveElements() {
Iterator<String> iterator = asList("one", "two").iterator();
try {
Iterators.getOnlyElement(iterator);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: <one, two>");
}
}
public void testGetOnlyElement_noDefault_fiveElements() {
Iterator<String> iterator = asList("one", "two", "three", "four", "five").iterator();
try {
Iterators.getOnlyElement(iterator);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo("expected one element but was: <one, two, three, four, five>");
}
}
public void testGetOnlyElement_noDefault_moreThanFiveElements() {
Iterator<String> iterator = asList("one", "two", "three", "four", "five", "six").iterator();
try {
Iterators.getOnlyElement(iterator);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo("expected one element but was: <one, two, three, four, five, ...>");
}
}
public void testGetOnlyElement_withDefault_singleton() {
Iterator<String> iterator = Collections.singletonList("foo").iterator();
assertEquals("foo", Iterators.getOnlyElement(iterator, "bar"));
}
public void testGetOnlyElement_withDefault_empty() {
Iterator<String> iterator = Iterators.emptyIterator();
assertEquals("bar", Iterators.getOnlyElement(iterator, "bar"));
}
public void testGetOnlyElement_withDefault_empty_null() {
Iterator<String> iterator = Iterators.emptyIterator();
assertNull(Iterators.getOnlyElement(iterator, null));
}
public void testGetOnlyElement_withDefault_two() {
Iterator<String> iterator = asList("foo", "bar").iterator();
try {
Iterators.getOnlyElement(iterator, "x");
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: <foo, bar>");
}
}
@GwtIncompatible // Iterators.toArray(Iterator, Class)
public void testToArrayEmpty() {
Iterator<String> iterator = Collections.<String>emptyList().iterator();
String[] array = Iterators.toArray(iterator, String.class);
assertTrue(Arrays.equals(new String[0], array));
}
@GwtIncompatible // Iterators.toArray(Iterator, Class)
public void testToArraySingleton() {
Iterator<String> iterator = Collections.singletonList("a").iterator();
String[] array = Iterators.toArray(iterator, String.class);
assertTrue(Arrays.equals(new String[] {"a"}, array));
}
@GwtIncompatible // Iterators.toArray(Iterator, Class)
public void testToArray() {
String[] sourceArray = new String[] {"a", "b", "c"};
Iterator<String> iterator = asList(sourceArray).iterator();
String[] newArray = Iterators.toArray(iterator, String.class);
assertTrue(Arrays.equals(sourceArray, newArray));
}
public void testFilterSimple() {
Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator();
Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.equalTo("foo"));
List<String> expected = Collections.singletonList("foo");
List<String> actual = Lists.newArrayList(filtered);
assertEquals(expected, actual);
}
public void testFilterNoMatch() {
Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator();
Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysFalse());
List<String> expected = Collections.emptyList();
List<String> actual = Lists.newArrayList(filtered);
assertEquals(expected, actual);
}
public void testFilterMatchAll() {
Iterator<String> unfiltered = Lists.newArrayList("foo", "bar").iterator();
Iterator<String> filtered = Iterators.filter(unfiltered, Predicates.alwaysTrue());
List<String> expected = Lists.newArrayList("foo", "bar");
List<String> actual = Lists.newArrayList(filtered);
assertEquals(expected, actual);
}
public void testFilterNothing() {
Iterator<String> unfiltered = Collections.<String>emptyList().iterator();
Iterator<String> filtered =
Iterators.filter(
unfiltered,
new Predicate<String>() {
@Override
public boolean apply(String s) {
throw new AssertionFailedError("Should never be evaluated");
}
});
List<String> expected = Collections.emptyList();
List<String> actual = Lists.newArrayList(filtered);
assertEquals(expected, actual);
}
@GwtIncompatible // unreasonably slow
public void testFilterUsingIteratorTester() {
final List<Integer> list = asList(1, 2, 3, 4, 5);
final Predicate<Integer> isEven =
new Predicate<Integer>() {
@Override
public boolean apply(Integer integer) {
return integer % 2 == 0;
}
};
new IteratorTester<Integer>(
5, UNMODIFIABLE, asList(2, 4), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.filter(list.iterator(), isEven);
}
}.test();
}
public void testAny() {
List<String> list = Lists.newArrayList();
Predicate<String> predicate = Predicates.equalTo("pants");
assertFalse(Iterators.any(list.iterator(), predicate));
list.add("cool");
assertFalse(Iterators.any(list.iterator(), predicate));
list.add("pants");
assertTrue(Iterators.any(list.iterator(), predicate));
}
public void testAll() {
List<String> list = Lists.newArrayList();
Predicate<String> predicate = Predicates.equalTo("cool");
assertTrue(Iterators.all(list.iterator(), predicate));
list.add("cool");
assertTrue(Iterators.all(list.iterator(), predicate));
list.add("pants");
assertFalse(Iterators.all(list.iterator(), predicate));
}
public void testFind_firstElement() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool")));
assertEquals("pants", iterator.next());
}
public void testFind_lastElement() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants")));
assertFalse(iterator.hasNext());
}
public void testFind_notPresent() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
try {
Iterators.find(iterator, Predicates.alwaysFalse());
fail();
} catch (NoSuchElementException e) {
}
assertFalse(iterator.hasNext());
}
public void testFind_matchAlways() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue()));
}
public void testFind_withDefault_first() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("cool", Iterators.find(iterator, Predicates.equalTo("cool"), "woot"));
assertEquals("pants", iterator.next());
}
public void testFind_withDefault_last() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("pants", Iterators.find(iterator, Predicates.equalTo("pants"), "woot"));
assertFalse(iterator.hasNext());
}
public void testFind_withDefault_notPresent() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("woot", Iterators.find(iterator, Predicates.alwaysFalse(), "woot"));
assertFalse(iterator.hasNext());
}
public void testFind_withDefault_notPresent_nullReturn() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertNull(Iterators.find(iterator, Predicates.alwaysFalse(), null));
assertFalse(iterator.hasNext());
}
public void testFind_withDefault_matchAlways() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("cool", Iterators.find(iterator, Predicates.alwaysTrue(), "woot"));
assertEquals("pants", iterator.next());
}
public void testTryFind_firstElement() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertThat(Iterators.tryFind(iterator, Predicates.equalTo("cool"))).hasValue("cool");
}
public void testTryFind_lastElement() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertThat(Iterators.tryFind(iterator, Predicates.equalTo("pants"))).hasValue("pants");
}
public void testTryFind_alwaysTrue() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertThat(Iterators.tryFind(iterator, Predicates.alwaysTrue())).hasValue("cool");
}
public void testTryFind_alwaysFalse_orDefault() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertEquals("woot", Iterators.tryFind(iterator, Predicates.alwaysFalse()).or("woot"));
assertFalse(iterator.hasNext());
}
public void testTryFind_alwaysFalse_isPresent() {
Iterable<String> list = Lists.newArrayList("cool", "pants");
Iterator<String> iterator = list.iterator();
assertThat(Iterators.tryFind(iterator, Predicates.alwaysFalse())).isAbsent();
assertFalse(iterator.hasNext());
}
public void testTransform() {
Iterator<String> input = asList("1", "2", "3").iterator();
Iterator<Integer> result =
Iterators.transform(
input,
new Function<String, Integer>() {
@Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
});
List<Integer> actual = Lists.newArrayList(result);
List<Integer> expected = asList(1, 2, 3);
assertEquals(expected, actual);
}
public void testTransformRemove() {
List<String> list = Lists.newArrayList("1", "2", "3");
Iterator<String> input = list.iterator();
Iterator<Integer> iterator =
Iterators.transform(
input,
new Function<String, Integer>() {
@Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
});
assertEquals(Integer.valueOf(1), iterator.next());
assertEquals(Integer.valueOf(2), iterator.next());
iterator.remove();
assertEquals(asList("1", "3"), list);
}
public void testPoorlyBehavedTransform() {
Iterator<String> input = asList("1", null, "3").iterator();
Iterator<Integer> result =
Iterators.transform(
input,
new Function<String, Integer>() {
@Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
});
result.next();
try {
result.next();
fail("Expected NFE");
} catch (NumberFormatException expected) {
}
}
public void testNullFriendlyTransform() {
Iterator<Integer> input = asList(1, 2, null, 3).iterator();
Iterator<String> result =
Iterators.transform(
input,
new Function<Integer, String>() {
@Override
public String apply(Integer from) {
return String.valueOf(from);
}
});
List<String> actual = Lists.newArrayList(result);
List<String> expected = asList("1", "2", "null", "3");
assertEquals(expected, actual);
}
public void testCycleOfEmpty() {
// "<String>" for javac 1.5.
Iterator<String> cycle = Iterators.<String>cycle();
assertFalse(cycle.hasNext());
}
public void testCycleOfOne() {
Iterator<String> cycle = Iterators.cycle("a");
for (int i = 0; i < 3; i++) {
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
}
}
public void testCycleOfOneWithRemove() {
Iterable<String> iterable = Lists.newArrayList("a");
Iterator<String> cycle = Iterators.cycle(iterable);
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
cycle.remove();
assertEquals(Collections.emptyList(), iterable);
assertFalse(cycle.hasNext());
}
public void testCycleOfTwo() {
Iterator<String> cycle = Iterators.cycle("a", "b");
for (int i = 0; i < 3; i++) {
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
assertTrue(cycle.hasNext());
assertEquals("b", cycle.next());
}
}
public void testCycleOfTwoWithRemove() {
Iterable<String> iterable = Lists.newArrayList("a", "b");
Iterator<String> cycle = Iterators.cycle(iterable);
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
assertTrue(cycle.hasNext());
assertEquals("b", cycle.next());
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
cycle.remove();
assertEquals(Collections.singletonList("b"), iterable);
assertTrue(cycle.hasNext());
assertEquals("b", cycle.next());
assertTrue(cycle.hasNext());
assertEquals("b", cycle.next());
cycle.remove();
assertEquals(Collections.emptyList(), iterable);
assertFalse(cycle.hasNext());
}
public void testCycleRemoveWithoutNext() {
Iterator<String> cycle = Iterators.cycle("a", "b");
assertTrue(cycle.hasNext());
try {
cycle.remove();
fail("no exception thrown");
} catch (IllegalStateException expected) {
}
}
public void testCycleRemoveSameElementTwice() {
Iterator<String> cycle = Iterators.cycle("a", "b");
cycle.next();
cycle.remove();
try {
cycle.remove();
fail("no exception thrown");
} catch (IllegalStateException expected) {
}
}
public void testCycleWhenRemoveIsNotSupported() {
Iterable<String> iterable = asList("a", "b");
Iterator<String> cycle = Iterators.cycle(iterable);
cycle.next();
try {
cycle.remove();
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
}
public void testCycleRemoveAfterHasNext() {
Iterable<String> iterable = Lists.newArrayList("a");
Iterator<String> cycle = Iterators.cycle(iterable);
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
assertTrue(cycle.hasNext());
cycle.remove();
assertEquals(Collections.emptyList(), iterable);
assertFalse(cycle.hasNext());
}
/** An Iterable whose Iterator is rigorous in checking for concurrent modification. */
private static final class PickyIterable<E> implements Iterable<E> {
final List<E> elements;
int modCount = 0;
PickyIterable(E... elements) {
this.elements = new ArrayList<E>(asList(elements));
}
@Override
public Iterator<E> iterator() {
return new PickyIterator();
}
final class PickyIterator implements Iterator<E> {
int expectedModCount = modCount;
int index = 0;
boolean canRemove;
@Override
public boolean hasNext() {
checkConcurrentModification();
return index < elements.size();
}
@Override
public E next() {
checkConcurrentModification();
if (!hasNext()) {
throw new NoSuchElementException();
}
canRemove = true;
return elements.get(index++);
}
@Override
public void remove() {
checkConcurrentModification();
checkRemove(canRemove);
elements.remove(--index);
expectedModCount = ++modCount;
canRemove = false;
}
void checkConcurrentModification() {
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
}
public void testCycleRemoveAfterHasNextExtraPicky() {
PickyIterable<String> iterable = new PickyIterable("a");
Iterator<String> cycle = Iterators.cycle(iterable);
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
assertTrue(cycle.hasNext());
cycle.remove();
assertTrue(iterable.elements.isEmpty());
assertFalse(cycle.hasNext());
}
public void testCycleNoSuchElementException() {
Iterable<String> iterable = Lists.newArrayList("a");
Iterator<String> cycle = Iterators.cycle(iterable);
assertTrue(cycle.hasNext());
assertEquals("a", cycle.next());
cycle.remove();
assertFalse(cycle.hasNext());
try {
cycle.next();
fail();
} catch (NoSuchElementException expected) {
}
}
@GwtIncompatible // unreasonably slow
public void testCycleUsingIteratorTester() {
new IteratorTester<Integer>(
5,
UNMODIFIABLE,
asList(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.cycle(asList(1, 2));
}
}.test();
}
@GwtIncompatible // slow (~5s)
public void testConcatNoIteratorsYieldsEmpty() {
new EmptyIteratorTester() {
@SuppressWarnings("unchecked")
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat();
}
}.test();
}
@GwtIncompatible // slow (~5s)
public void testConcatOneEmptyIteratorYieldsEmpty() {
new EmptyIteratorTester() {
@SuppressWarnings("unchecked")
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver());
}
}.test();
}
@GwtIncompatible // slow (~5s)
public void testConcatMultipleEmptyIteratorsYieldsEmpty() {
new EmptyIteratorTester() {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver(), iterateOver());
}
}.test();
}
@GwtIncompatible // slow (~3s)
public void testConcatSingletonYieldsSingleton() {
new SingletonIteratorTester() {
@SuppressWarnings("unchecked")
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver(1));
}
}.test();
}
@GwtIncompatible // slow (~5s)
public void testConcatEmptyAndSingletonAndEmptyYieldsSingleton() {
new SingletonIteratorTester() {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver(), iterateOver(1), iterateOver());
}
}.test();
}
@GwtIncompatible // fairly slow (~40s)
public void testConcatSingletonAndSingletonYieldsDoubleton() {
new DoubletonIteratorTester() {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver(1), iterateOver(2));
}
}.test();
}
@GwtIncompatible // fairly slow (~40s)
public void testConcatSingletonAndSingletonWithEmptiesYieldsDoubleton() {
new DoubletonIteratorTester() {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(iterateOver(1), iterateOver(), iterateOver(), iterateOver(2));
}
}.test();
}
@GwtIncompatible // fairly slow (~50s)
public void testConcatUnmodifiable() {
new IteratorTester<Integer>(
5, UNMODIFIABLE, asList(1, 2), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.concat(
asList(1).iterator(), Arrays.<Integer>asList().iterator(), asList(2).iterator());
}
}.test();
}
public void testConcatPartiallyAdvancedSecond() {
Iterator<String> itr1 =
Iterators.concat(Iterators.singletonIterator("a"), Iterators.forArray("b", "c"));
assertEquals("a", itr1.next());
assertEquals("b", itr1.next());
Iterator<String> itr2 = Iterators.concat(Iterators.singletonIterator("d"), itr1);
assertEquals("d", itr2.next());
assertEquals("c", itr2.next());
}
public void testConcatPartiallyAdvancedFirst() {
Iterator<String> itr1 =
Iterators.concat(Iterators.singletonIterator("a"), Iterators.forArray("b", "c"));
assertEquals("a", itr1.next());
assertEquals("b", itr1.next());
Iterator<String> itr2 = Iterators.concat(itr1, Iterators.singletonIterator("d"));
assertEquals("c", itr2.next());
assertEquals("d", itr2.next());
}
/** Illustrates the somewhat bizarre behavior when a null is passed in. */
public void testConcatContainingNull() {
@SuppressWarnings("unchecked")
Iterator<Iterator<Integer>> input = asList(iterateOver(1, 2), null, iterateOver(3)).iterator();
Iterator<Integer> result = Iterators.concat(input);
assertEquals(1, (int) result.next());
assertEquals(2, (int) result.next());
try {
result.hasNext();
fail("no exception thrown");
} catch (NullPointerException e) {
}
try {
result.next();
fail("no exception thrown");
} catch (NullPointerException e) {
}
// There is no way to get "through" to the 3. Buh-bye
}
@SuppressWarnings("unchecked")
public void testConcatVarArgsContainingNull() {
try {
Iterators.concat(iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5));
fail("no exception thrown");
} catch (NullPointerException e) {
}
}
public void testConcatNested_appendToEnd() {
final int nestingDepth = 128;
Iterator<Integer> iterator = iterateOver();
for (int i = 0; i < nestingDepth; i++) {
iterator = Iterators.concat(iterator, iterateOver(1));
}
assertEquals(nestingDepth, Iterators.size(iterator));
}
public void testConcatNested_appendToBeginning() {
final int nestingDepth = 128;
Iterator<Integer> iterator = iterateOver();
for (int i = 0; i < nestingDepth; i++) {
iterator = Iterators.concat(iterateOver(1), iterator);
}
assertEquals(nestingDepth, Iterators.size(iterator));
}
public void testAddAllWithEmptyIterator() {
List<String> alreadyThere = Lists.newArrayList("already", "there");
boolean changed = Iterators.addAll(alreadyThere, Iterators.<String>emptyIterator());
assertThat(alreadyThere).containsExactly("already", "there").inOrder();
assertFalse(changed);
}
public void testAddAllToList() {
List<String> alreadyThere = Lists.newArrayList("already", "there");
List<String> freshlyAdded = Lists.newArrayList("freshly", "added");
boolean changed = Iterators.addAll(alreadyThere, freshlyAdded.iterator());
assertThat(alreadyThere).containsExactly("already", "there", "freshly", "added");
assertTrue(changed);
}
public void testAddAllToSet() {
Set<String> alreadyThere = Sets.newLinkedHashSet(asList("already", "there"));
List<String> oneMore = Lists.newArrayList("there");
boolean changed = Iterators.addAll(alreadyThere, oneMore.iterator());
assertThat(alreadyThere).containsExactly("already", "there").inOrder();
assertFalse(changed);
}
@GwtIncompatible // NullPointerTester
public void testNullPointerExceptions() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(Iterators.class);
}
@GwtIncompatible // Only used by @GwtIncompatible code
private abstract static class EmptyIteratorTester extends IteratorTester<Integer> {
protected EmptyIteratorTester() {
super(3, MODIFIABLE, Collections.<Integer>emptySet(), IteratorTester.KnownOrder.KNOWN_ORDER);
}
}
@GwtIncompatible // Only used by @GwtIncompatible code
private abstract static class SingletonIteratorTester extends IteratorTester<Integer> {
protected SingletonIteratorTester() {
super(3, MODIFIABLE, singleton(1), IteratorTester.KnownOrder.KNOWN_ORDER);
}
}
@GwtIncompatible // Only used by @GwtIncompatible code
private abstract static class DoubletonIteratorTester extends IteratorTester<Integer> {
protected DoubletonIteratorTester() {
super(5, MODIFIABLE, newArrayList(1, 2), IteratorTester.KnownOrder.KNOWN_ORDER);
}
}
private static Iterator<Integer> iterateOver(final Integer... values) {
return newArrayList(values).iterator();
}
public void testElementsEqual() {
Iterable<?> a;
Iterable<?> b;
// Base case.
a = Lists.newArrayList();
b = Collections.emptySet();
assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator()));
// A few elements.
a = asList(4, 8, 15, 16, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator()));
// The same, but with nulls.
a = asList(4, 8, null, 16, 23, 42);
b = asList(4, 8, null, 16, 23, 42);
assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator()));
// Different Iterable types (still equal elements, though).
a = ImmutableList.of(4, 8, 15, 16, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertTrue(Iterators.elementsEqual(a.iterator(), b.iterator()));
// An element differs.
a = asList(4, 8, 15, 12, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator()));
// null versus non-null.
a = asList(4, 8, 15, null, 23, 42);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator()));
assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator()));
// Different lengths.
a = asList(4, 8, 15, 16, 23);
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator()));
assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator()));
// Different lengths, one is empty.
a = Collections.emptySet();
b = asList(4, 8, 15, 16, 23, 42);
assertFalse(Iterators.elementsEqual(a.iterator(), b.iterator()));
assertFalse(Iterators.elementsEqual(b.iterator(), a.iterator()));
}
public void testPartition_badSize() {
Iterator<Integer> source = Iterators.singletonIterator(1);
try {
Iterators.partition(source, 0);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testPartition_empty() {
Iterator<Integer> source = Iterators.emptyIterator();
Iterator<List<Integer>> partitions = Iterators.partition(source, 1);
assertFalse(partitions.hasNext());
}
public void testPartition_singleton1() {
Iterator<Integer> source = Iterators.singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.partition(source, 1);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
public void testPartition_singleton2() {
Iterator<Integer> source = Iterators.singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.partition(source, 2);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
@GwtIncompatible // fairly slow (~50s)
public void testPartition_general() {
new IteratorTester<List<Integer>>(
5,
IteratorFeature.UNMODIFIABLE,
ImmutableList.of(asList(1, 2, 3), asList(4, 5, 6), asList(7)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<List<Integer>> newTargetIterator() {
Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7);
return Iterators.partition(source, 3);
}
}.test();
}
public void testPartition_view() {
List<Integer> list = asList(1, 2);
Iterator<List<Integer>> partitions = Iterators.partition(list.iterator(), 1);
// Changes before the partition is retrieved are reflected
list.set(0, 3);
List<Integer> first = partitions.next();
// Changes after are not
list.set(0, 4);
assertEquals(ImmutableList.of(3), first);
}
@GwtIncompatible // ?
// TODO: Figure out why this is failing in GWT.
public void testPartitionRandomAccess() {
Iterator<Integer> source = asList(1, 2, 3).iterator();
Iterator<List<Integer>> partitions = Iterators.partition(source, 2);
assertTrue(partitions.next() instanceof RandomAccess);
assertTrue(partitions.next() instanceof RandomAccess);
}
public void testPaddedPartition_badSize() {
Iterator<Integer> source = Iterators.singletonIterator(1);
try {
Iterators.paddedPartition(source, 0);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testPaddedPartition_empty() {
Iterator<Integer> source = Iterators.emptyIterator();
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1);
assertFalse(partitions.hasNext());
}
public void testPaddedPartition_singleton1() {
Iterator<Integer> source = Iterators.singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 1);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(ImmutableList.of(1), partitions.next());
assertFalse(partitions.hasNext());
}
public void testPaddedPartition_singleton2() {
Iterator<Integer> source = Iterators.singletonIterator(1);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2);
assertTrue(partitions.hasNext());
assertTrue(partitions.hasNext());
assertEquals(asList(1, null), partitions.next());
assertFalse(partitions.hasNext());
}
@GwtIncompatible // fairly slow (~50s)
public void testPaddedPartition_general() {
new IteratorTester<List<Integer>>(
5,
IteratorFeature.UNMODIFIABLE,
ImmutableList.of(asList(1, 2, 3), asList(4, 5, 6), asList(7, null, null)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<List<Integer>> newTargetIterator() {
Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7);
return Iterators.paddedPartition(source, 3);
}
}.test();
}
public void testPaddedPartition_view() {
List<Integer> list = asList(1, 2);
Iterator<List<Integer>> partitions = Iterators.paddedPartition(list.iterator(), 1);
// Changes before the PaddedPartition is retrieved are reflected
list.set(0, 3);
List<Integer> first = partitions.next();
// Changes after are not
list.set(0, 4);
assertEquals(ImmutableList.of(3), first);
}
public void testPaddedPartitionRandomAccess() {
Iterator<Integer> source = asList(1, 2, 3).iterator();
Iterator<List<Integer>> partitions = Iterators.paddedPartition(source, 2);
assertTrue(partitions.next() instanceof RandomAccess);
assertTrue(partitions.next() instanceof RandomAccess);
}
public void testForArrayEmpty() {
String[] array = new String[0];
Iterator<String> iterator = Iterators.forArray(array);
assertFalse(iterator.hasNext());
try {
iterator.next();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testForArrayTypical() {
String[] array = {"foo", "bar"};
Iterator<String> iterator = Iterators.forArray(array);
assertTrue(iterator.hasNext());
assertEquals("foo", iterator.next());
assertTrue(iterator.hasNext());
try {
iterator.remove();
fail();
} catch (UnsupportedOperationException expected) {
}
assertEquals("bar", iterator.next());
assertFalse(iterator.hasNext());
try {
iterator.next();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testForArrayOffset() {
String[] array = {"foo", "bar", "cat", "dog"};
Iterator<String> iterator = Iterators.forArray(array, 1, 2, 0);
assertTrue(iterator.hasNext());
assertEquals("bar", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("cat", iterator.next());
assertFalse(iterator.hasNext());
try {
Iterators.forArray(array, 2, 3, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testForArrayLength0() {
String[] array = {"foo", "bar"};
assertFalse(Iterators.forArray(array, 0, 0, 0).hasNext());
assertFalse(Iterators.forArray(array, 1, 0, 0).hasNext());
assertFalse(Iterators.forArray(array, 2, 0, 0).hasNext());
try {
Iterators.forArray(array, -1, 0, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
}
try {
Iterators.forArray(array, 3, 0, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
@GwtIncompatible // unreasonably slow
public void testForArrayUsingTester() {
new IteratorTester<Integer>(
6, UNMODIFIABLE, asList(1, 2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.forArray(1, 2, 3);
}
}.test();
}
@GwtIncompatible // unreasonably slow
public void testForArrayWithOffsetUsingTester() {
new IteratorTester<Integer>(
6, UNMODIFIABLE, asList(1, 2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.forArray(new Integer[] {0, 1, 2, 3, 4}, 1, 3, 0);
}
}.test();
}
public void testForEnumerationEmpty() {
Enumeration<Integer> enumer = enumerate();
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertFalse(iter.hasNext());
try {
iter.next();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testForEnumerationSingleton() {
Enumeration<Integer> enumer = enumerate(1);
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertTrue(iter.hasNext());
assertTrue(iter.hasNext());
assertEquals(1, (int) iter.next());
try {
iter.remove();
fail();
} catch (UnsupportedOperationException expected) {
}
assertFalse(iter.hasNext());
try {
iter.next();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testForEnumerationTypical() {
Enumeration<Integer> enumer = enumerate(1, 2, 3);
Iterator<Integer> iter = Iterators.forEnumeration(enumer);
assertTrue(iter.hasNext());
assertEquals(1, (int) iter.next());
assertTrue(iter.hasNext());
assertEquals(2, (int) iter.next());
assertTrue(iter.hasNext());
assertEquals(3, (int) iter.next());
assertFalse(iter.hasNext());
}
public void testAsEnumerationEmpty() {
Iterator<Integer> iter = Iterators.emptyIterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertFalse(enumer.hasMoreElements());
try {
enumer.nextElement();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testAsEnumerationSingleton() {
Iterator<Integer> iter = ImmutableList.of(1).iterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertTrue(enumer.hasMoreElements());
assertTrue(enumer.hasMoreElements());
assertEquals(1, (int) enumer.nextElement());
assertFalse(enumer.hasMoreElements());
try {
enumer.nextElement();
fail();
} catch (NoSuchElementException expected) {
}
}
public void testAsEnumerationTypical() {
Iterator<Integer> iter = ImmutableList.of(1, 2, 3).iterator();
Enumeration<Integer> enumer = Iterators.asEnumeration(iter);
assertTrue(enumer.hasMoreElements());
assertEquals(1, (int) enumer.nextElement());
assertTrue(enumer.hasMoreElements());
assertEquals(2, (int) enumer.nextElement());
assertTrue(enumer.hasMoreElements());
assertEquals(3, (int) enumer.nextElement());
assertFalse(enumer.hasMoreElements());
}
private static Enumeration<Integer> enumerate(Integer... ints) {
Vector<Integer> vector = new Vector<>();
vector.addAll(asList(ints));
return vector.elements();
}
public void testToString() {
Iterator<String> iterator = Lists.newArrayList("yam", "bam", "jam", "ham").iterator();
assertEquals("[yam, bam, jam, ham]", Iterators.toString(iterator));
}
public void testToStringWithNull() {
Iterator<String> iterator = Lists.newArrayList("hello", null, "world").iterator();
assertEquals("[hello, null, world]", Iterators.toString(iterator));
}
public void testToStringEmptyIterator() {
Iterator<String> iterator = Collections.<String>emptyList().iterator();
assertEquals("[]", Iterators.toString(iterator));
}
public void testLimit() {
List<String> list = newArrayList();
try {
Iterators.limit(list.iterator(), -1);
fail("expected exception");
} catch (IllegalArgumentException expected) {
}
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertFalse(Iterators.limit(list.iterator(), 1).hasNext());
list.add("cool");
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 1)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2)));
list.add("pants");
assertFalse(Iterators.limit(list.iterator(), 0).hasNext());
assertEquals(ImmutableList.of("cool"), newArrayList(Iterators.limit(list.iterator(), 1)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 2)));
assertEquals(list, newArrayList(Iterators.limit(list.iterator(), 3)));
}
public void testLimitRemove() {
List<String> list = newArrayList();
list.add("cool");
list.add("pants");
Iterator<String> iterator = Iterators.limit(list.iterator(), 1);
iterator.next();
iterator.remove();
assertFalse(iterator.hasNext());
assertEquals(1, list.size());
assertEquals("pants", list.get(0));
}
@GwtIncompatible // fairly slow (~30s)
public void testLimitUsingIteratorTester() {
final List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
new IteratorTester<Integer>(
5, MODIFIABLE, newArrayList(1, 2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.limit(Lists.newArrayList(list).iterator(), 3);
}
}.test();
}
public void testGetNext_withDefault_singleton() {
Iterator<String> iterator = Collections.singletonList("foo").iterator();
assertEquals("foo", Iterators.getNext(iterator, "bar"));
}
public void testGetNext_withDefault_empty() {
Iterator<String> iterator = Iterators.emptyIterator();
assertEquals("bar", Iterators.getNext(iterator, "bar"));
}
public void testGetNext_withDefault_empty_null() {
Iterator<String> iterator = Iterators.emptyIterator();
assertNull(Iterators.getNext(iterator, null));
}
public void testGetNext_withDefault_two() {
Iterator<String> iterator = asList("foo", "bar").iterator();
assertEquals("foo", Iterators.getNext(iterator, "x"));
}
public void testGetLast_basic() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
assertEquals("b", getLast(list.iterator()));
}
public void testGetLast_exception() {
List<String> list = newArrayList();
try {
getLast(list.iterator());
fail();
} catch (NoSuchElementException expected) {
}
}
public void testGetLast_withDefault_singleton() {
Iterator<String> iterator = Collections.singletonList("foo").iterator();
assertEquals("foo", Iterators.getLast(iterator, "bar"));
}
public void testGetLast_withDefault_empty() {
Iterator<String> iterator = Iterators.emptyIterator();
assertEquals("bar", Iterators.getLast(iterator, "bar"));
}
public void testGetLast_withDefault_empty_null() {
Iterator<String> iterator = Iterators.emptyIterator();
assertNull(Iterators.getLast(iterator, null));
}
public void testGetLast_withDefault_two() {
Iterator<String> iterator = asList("foo", "bar").iterator();
assertEquals("bar", Iterators.getLast(iterator, "x"));
}
public void testGet_basic() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("b", get(iterator, 1));
assertFalse(iterator.hasNext());
}
public void testGet_atSize() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
try {
get(iterator, 2);
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertFalse(iterator.hasNext());
}
public void testGet_pastEnd() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
try {
get(iterator, 5);
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertFalse(iterator.hasNext());
}
public void testGet_empty() {
List<String> list = newArrayList();
Iterator<String> iterator = list.iterator();
try {
get(iterator, 0);
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertFalse(iterator.hasNext());
}
public void testGet_negativeIndex() {
List<String> list = newArrayList("a", "b", "c");
Iterator<String> iterator = list.iterator();
try {
get(iterator, -1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testGet_withDefault_basic() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("a", get(iterator, 0, "c"));
assertTrue(iterator.hasNext());
}
public void testGet_withDefault_atSize() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("c", get(iterator, 2, "c"));
assertFalse(iterator.hasNext());
}
public void testGet_withDefault_pastEnd() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
assertEquals("c", get(iterator, 3, "c"));
assertFalse(iterator.hasNext());
}
public void testGet_withDefault_negativeIndex() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
try {
get(iterator, -1, "c");
fail();
} catch (IndexOutOfBoundsException expected) {
// pass
}
assertTrue(iterator.hasNext());
}
public void testAdvance_basic() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
advance(iterator, 1);
assertEquals("b", iterator.next());
}
public void testAdvance_pastEnd() {
List<String> list = newArrayList();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
advance(iterator, 5);
assertFalse(iterator.hasNext());
}
public void testAdvance_illegalArgument() {
List<String> list = newArrayList("a", "b", "c");
Iterator<String> iterator = list.iterator();
try {
advance(iterator, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testFrequency() {
List<String> list = newArrayList("a", null, "b", null, "a", null);
assertEquals(2, Iterators.frequency(list.iterator(), "a"));
assertEquals(1, Iterators.frequency(list.iterator(), "b"));
assertEquals(0, Iterators.frequency(list.iterator(), "c"));
assertEquals(0, Iterators.frequency(list.iterator(), 4.2));
assertEquals(3, Iterators.frequency(list.iterator(), null));
}
@GwtIncompatible // slow (~4s)
public void testSingletonIterator() {
new IteratorTester<Integer>(
3, UNMODIFIABLE, singleton(1), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<Integer> newTargetIterator() {
return Iterators.singletonIterator(1);
}
}.test();
}
public void testRemoveAll() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(Iterators.removeAll(list.iterator(), newArrayList("b", "d", "f")));
assertEquals(newArrayList("a", "c", "e"), list);
assertFalse(Iterators.removeAll(list.iterator(), newArrayList("x", "y", "z")));
assertEquals(newArrayList("a", "c", "e"), list);
}
public void testRemoveIf() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(
Iterators.removeIf(
list.iterator(),
new Predicate<String>() {
@Override
public boolean apply(String s) {
return s.equals("b") || s.equals("d") || s.equals("f");
}
}));
assertEquals(newArrayList("a", "c", "e"), list);
assertFalse(
Iterators.removeIf(
list.iterator(),
new Predicate<String>() {
@Override
public boolean apply(String s) {
return s.equals("x") || s.equals("y") || s.equals("z");
}
}));
assertEquals(newArrayList("a", "c", "e"), list);
}
public void testRetainAll() {
List<String> list = newArrayList("a", "b", "c", "d", "e");
assertTrue(Iterators.retainAll(list.iterator(), newArrayList("b", "d", "f")));
assertEquals(newArrayList("b", "d"), list);
assertFalse(Iterators.retainAll(list.iterator(), newArrayList("b", "e", "d")));
assertEquals(newArrayList("b", "d"), list);
}
@GwtIncompatible // ListTestSuiteBuilder
private static Test testsForRemoveAllAndRetainAll() {
return ListTestSuiteBuilder.using(
new TestStringListGenerator() {
@Override
public List<String> create(final String[] elements) {
final List<String> delegate = newArrayList(elements);
return new ForwardingList<String>() {
@Override
protected List<String> delegate() {
return delegate;
}
@Override
public boolean removeAll(Collection<?> c) {
return Iterators.removeAll(iterator(), c);
}
@Override
public boolean retainAll(Collection<?> c) {
return Iterators.retainAll(iterator(), c);
}
};
}
})
.named("ArrayList with Iterators.removeAll and retainAll")
.withFeatures(
ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY)
.createTestSuite();
}
public void testConsumingIterator() {
// Test data
List<String> list = Lists.newArrayList("a", "b");
// Test & Verify
Iterator<String> consumingIterator = Iterators.consumingIterator(list.iterator());
assertEquals("Iterators.consumingIterator(...)", consumingIterator.toString());
assertThat(list).containsExactly("a", "b").inOrder();
assertTrue(consumingIterator.hasNext());
assertThat(list).containsExactly("a", "b").inOrder();
assertEquals("a", consumingIterator.next());
assertThat(list).contains("b");
assertTrue(consumingIterator.hasNext());
assertEquals("b", consumingIterator.next());
assertThat(list).isEmpty();
assertFalse(consumingIterator.hasNext());
}
@GwtIncompatible // ?
// TODO: Figure out why this is failing in GWT.
public void testConsumingIterator_duelingIterators() {
// Test data
List<String> list = Lists.newArrayList("a", "b");
// Test & Verify
Iterator<String> i1 = Iterators.consumingIterator(list.iterator());
Iterator<String> i2 = Iterators.consumingIterator(list.iterator());
i1.next();
try {
i2.next();
fail("Concurrent modification should throw an exception.");
} catch (ConcurrentModificationException cme) {
// Pass
}
}
public void testIndexOf_consumedData() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "jack").iterator();
assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo")));
assertEquals("jack", iterator.next());
assertFalse(iterator.hasNext());
}
public void testIndexOf_consumedDataWithDuplicates() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator();
assertEquals(1, Iterators.indexOf(iterator, Predicates.equalTo("mo")));
assertEquals("mo", iterator.next());
assertEquals("jack", iterator.next());
assertFalse(iterator.hasNext());
}
public void testIndexOf_consumedDataNoMatch() {
Iterator<String> iterator = Lists.newArrayList("manny", "mo", "mo", "jack").iterator();
assertEquals(-1, Iterators.indexOf(iterator, Predicates.equalTo("bob")));
assertFalse(iterator.hasNext());
}
@SuppressWarnings("deprecation")
public void testUnmodifiableIteratorShortCircuit() {
Iterator<String> mod = Lists.newArrayList("a", "b", "c").iterator();
UnmodifiableIterator<String> unmod = Iterators.unmodifiableIterator(mod);
assertNotSame(mod, unmod);
assertSame(unmod, Iterators.unmodifiableIterator(unmod));
assertSame(unmod, Iterators.unmodifiableIterator((Iterator<String>) unmod));
}
@SuppressWarnings("deprecation")
public void testPeekingIteratorShortCircuit() {
Iterator<String> nonpeek = Lists.newArrayList("a", "b", "c").iterator();
PeekingIterator<String> peek = Iterators.peekingIterator(nonpeek);
assertNotSame(peek, nonpeek);
assertSame(peek, Iterators.peekingIterator(peek));
assertSame(peek, Iterators.peekingIterator((Iterator<String>) peek));
}
}
| |
package graphene.dao.solr;
import graphene.util.FastNumberUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.slf4j.Logger;
public class SolrService {
// Thresold to check double value
public static final double DEFAULT_THRESHOLD = 0.00000001;
private SolrRequestParameters defaultSolrParams;
private Logger logger;
private SolrServer server;
private double threshold = DEFAULT_THRESHOLD;
private String url;
public SolrService(String url, Logger log) {
logger = log;
loadDefaultConfigProps();
server = new HttpSolrServer(url);
}
/**
* @return the defaultSolrParams
*/
public SolrRequestParameters getDefaultSolrParams() {
return defaultSolrParams;
}
/**
* @return the logger
*/
public Logger getLogger() {
return logger;
}
/**
* @return the server
*/
public SolrServer getServer() {
return server;
}
/**
* @return the threshold
*/
public double getThreshold() {
return threshold;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* load default configuration for the service
*/
void loadDefaultConfigProps() {
try {
// look at local directory first, if it doesn't exist, look at
// classloader classpath
InputStream is = null;
try {
is = new FileInputStream("./solrConfig.properties");
} catch (Exception ex) {
}
if (is == null) {
logger.info("can't find .property in local directory.. load property from class loader..");
is = getClass().getClassLoader().getResourceAsStream(
"solrConfig.properties");
} else {
logger.info("load .property from local directory..");
}
Properties props = new Properties();
props.load(is);
is.close();
url = props.getProperty("URL");
logger.debug("using URL: " + url);
defaultSolrParams = new SolrRequestParameters();
defaultSolrParams.setStartRow(FastNumberUtils
.parseIntWithCheck(props.getProperty("STARTING_ROW", "0")));
defaultSolrParams.setNumberOfRows(FastNumberUtils
.parseIntWithCheck(props.getProperty(
"NUMBER_OF_ROWS_PER_QUERY", "10")));
String defaultFields = props.getProperty("DEFAULT_RETURN_FIELDS");
if (defaultFields != null) {
if (defaultFields.indexOf(",") > 0) {
String[] fields = defaultFields.split(",");
defaultSolrParams.setResultFields(Arrays.asList(fields));
} else {
List<String> fields = new ArrayList<String>();
fields.add(defaultFields);
defaultSolrParams.setResultFields(fields);
}
}
if (props.getProperty("THRESOLD") != null) {
threshold = Double.parseDouble(props.getProperty("THRESOLD"));
}
String orderFields = props.getProperty("ORDER_FIELDS");
if (orderFields != null) {
String[] fields = null;
if (orderFields.indexOf(",") > 0) {
fields = orderFields.split(",");
} else {
fields = new String[1];
fields[0] = orderFields;
}
for (String field : fields) {
String[] pair = field.split(" ");
if (pair.length < 2
|| !(pair[1].equalsIgnoreCase("asc") || pair[1]
.equalsIgnoreCase("desc"))) {
logger.error("ORDER_FIELDS property for field"
+ field
+ " is invalid, "
+ "\n valid syntax: \"fieldname asc|desc, fieldname2 asc|desc\", order entry will be ignore");
} else {
ORDER order = ORDER.asc;
if (pair[1].equalsIgnoreCase("desc")) {
order = ORDER.desc;
}
defaultSolrParams.addSortField(pair[0].trim(), order);
}
}
}
} catch (IOException ioe) {
logger.error("IOException in loadProps");
for (StackTraceElement ste : ioe.getStackTrace())
logger.error(ste.toString());
}
}
/**
* @param defaultSolrParams
* the defaultSolrParams to set
*/
public void setDefaultSolrParams(SolrRequestParameters defaultSolrParams) {
this.defaultSolrParams = defaultSolrParams;
}
/**
* @param logger
* the logger to set
*/
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* @param server
* the server to set
*/
public void setServer(SolrServer server) {
this.server = server;
}
/**
* @param threshold
* the threshold to set
*/
public void setThreshold(double threshold) {
this.threshold = threshold;
}
/**
* @param url
* the url to set
*/
public void setUrl(String url) {
this.url = url;
}
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.accessibility.CaptioningManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/** @hide */
public class TtmlRenderer extends SubtitleController.Renderer {
private final Context mContext;
private static final String MEDIA_MIMETYPE_TEXT_TTML = "application/ttml+xml";
private TtmlRenderingWidget mRenderingWidget;
public TtmlRenderer(Context context) {
mContext = context;
}
@Override
public boolean supports(MediaFormat format) {
if (format.containsKey(MediaFormat.KEY_MIME)) {
return format.getString(MediaFormat.KEY_MIME).equals(MEDIA_MIMETYPE_TEXT_TTML);
}
return false;
}
@Override
public SubtitleTrack createTrack(MediaFormat format) {
if (mRenderingWidget == null) {
mRenderingWidget = new TtmlRenderingWidget(mContext);
}
return new TtmlTrack(mRenderingWidget, format);
}
}
/**
* A class which provides utillity methods for TTML parsing.
*
* @hide
*/
final class TtmlUtils {
public static final String TAG_TT = "tt";
public static final String TAG_HEAD = "head";
public static final String TAG_BODY = "body";
public static final String TAG_DIV = "div";
public static final String TAG_P = "p";
public static final String TAG_SPAN = "span";
public static final String TAG_BR = "br";
public static final String TAG_STYLE = "style";
public static final String TAG_STYLING = "styling";
public static final String TAG_LAYOUT = "layout";
public static final String TAG_REGION = "region";
public static final String TAG_METADATA = "metadata";
public static final String TAG_SMPTE_IMAGE = "smpte:image";
public static final String TAG_SMPTE_DATA = "smpte:data";
public static final String TAG_SMPTE_INFORMATION = "smpte:information";
public static final String PCDATA = "#pcdata";
public static final String ATTR_BEGIN = "begin";
public static final String ATTR_DURATION = "dur";
public static final String ATTR_END = "end";
public static final long INVALID_TIMESTAMP = Long.MAX_VALUE;
/**
* Time expression RE according to the spec:
* http://www.w3.org/TR/ttaf1-dfxp/#timing-value-timeExpression
*/
private static final Pattern CLOCK_TIME = Pattern.compile(
"^([0-9][0-9]+):([0-9][0-9]):([0-9][0-9])"
+ "(?:(\\.[0-9]+)|:([0-9][0-9])(?:\\.([0-9]+))?)?$");
private static final Pattern OFFSET_TIME = Pattern.compile(
"^([0-9]+(?:\\.[0-9]+)?)(h|m|s|ms|f|t)$");
private TtmlUtils() {
}
/**
* Parses the given time expression and returns a timestamp in millisecond.
* <p>
* For the format of the time expression, please refer <a href=
* "http://www.w3.org/TR/ttaf1-dfxp/#timing-value-timeExpression">timeExpression</a>
*
* @param time A string which includes time expression.
* @param frameRate the framerate of the stream.
* @param subframeRate the sub-framerate of the stream
* @param tickRate the tick rate of the stream.
* @return the parsed timestamp in micro-second.
* @throws NumberFormatException if the given string does not match to the
* format.
*/
public static long parseTimeExpression(String time, int frameRate, int subframeRate,
int tickRate) throws NumberFormatException {
Matcher matcher = CLOCK_TIME.matcher(time);
if (matcher.matches()) {
String hours = matcher.group(1);
double durationSeconds = Long.parseLong(hours) * 3600;
String minutes = matcher.group(2);
durationSeconds += Long.parseLong(minutes) * 60;
String seconds = matcher.group(3);
durationSeconds += Long.parseLong(seconds);
String fraction = matcher.group(4);
durationSeconds += (fraction != null) ? Double.parseDouble(fraction) : 0;
String frames = matcher.group(5);
durationSeconds += (frames != null) ? ((double)Long.parseLong(frames)) / frameRate : 0;
String subframes = matcher.group(6);
durationSeconds += (subframes != null) ? ((double)Long.parseLong(subframes))
/ subframeRate / frameRate
: 0;
return (long)(durationSeconds * 1000);
}
matcher = OFFSET_TIME.matcher(time);
if (matcher.matches()) {
String timeValue = matcher.group(1);
double value = Double.parseDouble(timeValue);
String unit = matcher.group(2);
if (unit.equals("h")) {
value *= 3600L * 1000000L;
} else if (unit.equals("m")) {
value *= 60 * 1000000;
} else if (unit.equals("s")) {
value *= 1000000;
} else if (unit.equals("ms")) {
value *= 1000;
} else if (unit.equals("f")) {
value = value / frameRate * 1000000;
} else if (unit.equals("t")) {
value = value / tickRate * 1000000;
}
return (long)value;
}
throw new NumberFormatException("Malformed time expression : " + time);
}
/**
* Applies <a href
* src="http://www.w3.org/TR/ttaf1-dfxp/#content-attribute-space">the
* default space policy</a> to the given string.
*
* @param in A string to apply the policy.
*/
public static String applyDefaultSpacePolicy(String in) {
return applySpacePolicy(in, true);
}
/**
* Applies the space policy to the given string. This applies <a href
* src="http://www.w3.org/TR/ttaf1-dfxp/#content-attribute-space">the
* default space policy</a> with linefeed-treatment as treat-as-space
* or preserve.
*
* @param in A string to apply the policy.
* @param treatLfAsSpace Whether convert line feeds to spaces or not.
*/
public static String applySpacePolicy(String in, boolean treatLfAsSpace) {
// Removes CR followed by LF. ref:
// http://www.w3.org/TR/xml/#sec-line-ends
String crRemoved = in.replaceAll("\r\n", "\n");
// Apply suppress-at-line-break="auto" and
// white-space-treatment="ignore-if-surrounding-linefeed"
String spacesNeighboringLfRemoved = crRemoved.replaceAll(" *\n *", "\n");
// Apply linefeed-treatment="treat-as-space"
String lfToSpace = treatLfAsSpace ? spacesNeighboringLfRemoved.replaceAll("\n", " ")
: spacesNeighboringLfRemoved;
// Apply white-space-collapse="true"
String spacesCollapsed = lfToSpace.replaceAll("[ \t\\x0B\f\r]+", " ");
return spacesCollapsed;
}
/**
* Returns the timed text for the given time period.
*
* @param root The root node of the TTML document.
* @param startUs The start time of the time period in microsecond.
* @param endUs The end time of the time period in microsecond.
*/
public static String extractText(TtmlNode root, long startUs, long endUs) {
StringBuilder text = new StringBuilder();
extractText(root, startUs, endUs, text, false);
return text.toString().replaceAll("\n$", "");
}
private static void extractText(TtmlNode node, long startUs, long endUs, StringBuilder out,
boolean inPTag) {
if (node.mName.equals(TtmlUtils.PCDATA) && inPTag) {
out.append(node.mText);
} else if (node.mName.equals(TtmlUtils.TAG_BR) && inPTag) {
out.append("\n");
} else if (node.mName.equals(TtmlUtils.TAG_METADATA)) {
// do nothing.
} else if (node.isActive(startUs, endUs)) {
boolean pTag = node.mName.equals(TtmlUtils.TAG_P);
int length = out.length();
for (int i = 0; i < node.mChildren.size(); ++i) {
extractText(node.mChildren.get(i), startUs, endUs, out, pTag || inPTag);
}
if (pTag && length != out.length()) {
out.append("\n");
}
}
}
/**
* Returns a TTML fragment string for the given time period.
*
* @param root The root node of the TTML document.
* @param startUs The start time of the time period in microsecond.
* @param endUs The end time of the time period in microsecond.
*/
public static String extractTtmlFragment(TtmlNode root, long startUs, long endUs) {
StringBuilder fragment = new StringBuilder();
extractTtmlFragment(root, startUs, endUs, fragment);
return fragment.toString();
}
private static void extractTtmlFragment(TtmlNode node, long startUs, long endUs,
StringBuilder out) {
if (node.mName.equals(TtmlUtils.PCDATA)) {
out.append(node.mText);
} else if (node.mName.equals(TtmlUtils.TAG_BR)) {
out.append("<br/>");
} else if (node.isActive(startUs, endUs)) {
out.append("<");
out.append(node.mName);
out.append(node.mAttributes);
out.append(">");
for (int i = 0; i < node.mChildren.size(); ++i) {
extractTtmlFragment(node.mChildren.get(i), startUs, endUs, out);
}
out.append("</");
out.append(node.mName);
out.append(">");
}
}
}
/**
* A container class which represents a cue in TTML.
* @hide
*/
class TtmlCue extends SubtitleTrack.Cue {
public String mText;
public String mTtmlFragment;
public TtmlCue(long startTimeMs, long endTimeMs, String text, String ttmlFragment) {
this.mStartTimeMs = startTimeMs;
this.mEndTimeMs = endTimeMs;
this.mText = text;
this.mTtmlFragment = ttmlFragment;
}
}
/**
* A container class which represents a node in TTML.
*
* @hide
*/
class TtmlNode {
public final String mName;
public final String mAttributes;
public final TtmlNode mParent;
public final String mText;
public final List<TtmlNode> mChildren = new ArrayList<TtmlNode>();
public final long mRunId;
public final long mStartTimeMs;
public final long mEndTimeMs;
public TtmlNode(String name, String attributes, String text, long startTimeMs, long endTimeMs,
TtmlNode parent, long runId) {
this.mName = name;
this.mAttributes = attributes;
this.mText = text;
this.mStartTimeMs = startTimeMs;
this.mEndTimeMs = endTimeMs;
this.mParent = parent;
this.mRunId = runId;
}
/**
* Check if this node is active in the given time range.
*
* @param startTimeMs The start time of the range to check in microsecond.
* @param endTimeMs The end time of the range to check in microsecond.
* @return return true if the given range overlaps the time range of this
* node.
*/
public boolean isActive(long startTimeMs, long endTimeMs) {
return this.mEndTimeMs > startTimeMs && this.mStartTimeMs < endTimeMs;
}
}
/**
* A simple TTML parser (http://www.w3.org/TR/ttaf1-dfxp/) which supports DFXP
* presentation profile.
* <p>
* Supported features in this parser are:
* <ul>
* <li>content
* <li>core
* <li>presentation
* <li>profile
* <li>structure
* <li>time-offset
* <li>timing
* <li>tickRate
* <li>time-clock-with-frames
* <li>time-clock
* <li>time-offset-with-frames
* <li>time-offset-with-ticks
* </ul>
* </p>
*
* @hide
*/
class TtmlParser {
static final String TAG = "TtmlParser";
// TODO: read and apply the following attributes if specified.
private static final int DEFAULT_FRAMERATE = 30;
private static final int DEFAULT_SUBFRAMERATE = 1;
private static final int DEFAULT_TICKRATE = 1;
private XmlPullParser mParser;
private final TtmlNodeListener mListener;
private long mCurrentRunId;
public TtmlParser(TtmlNodeListener listener) {
mListener = listener;
}
/**
* Parse TTML data. Once this is called, all the previous data are
* reset and it starts parsing for the given text.
*
* @param ttmlText TTML text to parse.
* @throws XmlPullParserException
* @throws IOException
*/
public void parse(String ttmlText, long runId) throws XmlPullParserException, IOException {
mParser = null;
mCurrentRunId = runId;
loadParser(ttmlText);
parseTtml();
}
private void loadParser(String ttmlFragment) throws XmlPullParserException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
mParser = factory.newPullParser();
StringReader in = new StringReader(ttmlFragment);
mParser.setInput(in);
}
private void extractAttribute(XmlPullParser parser, int i, StringBuilder out) {
out.append(" ");
out.append(parser.getAttributeName(i));
out.append("=\"");
out.append(parser.getAttributeValue(i));
out.append("\"");
}
private void parseTtml() throws XmlPullParserException, IOException {
LinkedList<TtmlNode> nodeStack = new LinkedList<TtmlNode>();
int depthInUnsupportedTag = 0;
boolean active = true;
while (!isEndOfDoc()) {
int eventType = mParser.getEventType();
TtmlNode parent = nodeStack.peekLast();
if (active) {
if (eventType == XmlPullParser.START_TAG) {
if (!isSupportedTag(mParser.getName())) {
Log.w(TAG, "Unsupported tag " + mParser.getName() + " is ignored.");
depthInUnsupportedTag++;
active = false;
} else {
TtmlNode node = parseNode(parent);
nodeStack.addLast(node);
if (parent != null) {
parent.mChildren.add(node);
}
}
} else if (eventType == XmlPullParser.TEXT) {
String text = TtmlUtils.applyDefaultSpacePolicy(mParser.getText());
if (!TextUtils.isEmpty(text)) {
parent.mChildren.add(new TtmlNode(
TtmlUtils.PCDATA, "", text, 0, TtmlUtils.INVALID_TIMESTAMP,
parent, mCurrentRunId));
}
} else if (eventType == XmlPullParser.END_TAG) {
if (mParser.getName().equals(TtmlUtils.TAG_P)) {
mListener.onTtmlNodeParsed(nodeStack.getLast());
} else if (mParser.getName().equals(TtmlUtils.TAG_TT)) {
mListener.onRootNodeParsed(nodeStack.getLast());
}
nodeStack.removeLast();
}
} else {
if (eventType == XmlPullParser.START_TAG) {
depthInUnsupportedTag++;
} else if (eventType == XmlPullParser.END_TAG) {
depthInUnsupportedTag--;
if (depthInUnsupportedTag == 0) {
active = true;
}
}
}
mParser.next();
}
}
private TtmlNode parseNode(TtmlNode parent) throws XmlPullParserException, IOException {
int eventType = mParser.getEventType();
if (!(eventType == XmlPullParser.START_TAG)) {
return null;
}
StringBuilder attrStr = new StringBuilder();
long start = 0;
long end = TtmlUtils.INVALID_TIMESTAMP;
long dur = 0;
for (int i = 0; i < mParser.getAttributeCount(); ++i) {
String attr = mParser.getAttributeName(i);
String value = mParser.getAttributeValue(i);
// TODO: check if it's safe to ignore the namespace of attributes as follows.
attr = attr.replaceFirst("^.*:", "");
if (attr.equals(TtmlUtils.ATTR_BEGIN)) {
start = TtmlUtils.parseTimeExpression(value, DEFAULT_FRAMERATE,
DEFAULT_SUBFRAMERATE, DEFAULT_TICKRATE);
} else if (attr.equals(TtmlUtils.ATTR_END)) {
end = TtmlUtils.parseTimeExpression(value, DEFAULT_FRAMERATE, DEFAULT_SUBFRAMERATE,
DEFAULT_TICKRATE);
} else if (attr.equals(TtmlUtils.ATTR_DURATION)) {
dur = TtmlUtils.parseTimeExpression(value, DEFAULT_FRAMERATE, DEFAULT_SUBFRAMERATE,
DEFAULT_TICKRATE);
} else {
extractAttribute(mParser, i, attrStr);
}
}
if (parent != null) {
start += parent.mStartTimeMs;
if (end != TtmlUtils.INVALID_TIMESTAMP) {
end += parent.mStartTimeMs;
}
}
if (dur > 0) {
if (end != TtmlUtils.INVALID_TIMESTAMP) {
Log.e(TAG, "'dur' and 'end' attributes are defined at the same time." +
"'end' value is ignored.");
}
end = start + dur;
}
if (parent != null) {
// If the end time remains unspecified, then the end point is
// interpreted as the end point of the external time interval.
if (end == TtmlUtils.INVALID_TIMESTAMP &&
parent.mEndTimeMs != TtmlUtils.INVALID_TIMESTAMP &&
end > parent.mEndTimeMs) {
end = parent.mEndTimeMs;
}
}
TtmlNode node = new TtmlNode(mParser.getName(), attrStr.toString(), null, start, end,
parent, mCurrentRunId);
return node;
}
private boolean isEndOfDoc() throws XmlPullParserException {
return (mParser.getEventType() == XmlPullParser.END_DOCUMENT);
}
private static boolean isSupportedTag(String tag) {
if (tag.equals(TtmlUtils.TAG_TT) || tag.equals(TtmlUtils.TAG_HEAD) ||
tag.equals(TtmlUtils.TAG_BODY) || tag.equals(TtmlUtils.TAG_DIV) ||
tag.equals(TtmlUtils.TAG_P) || tag.equals(TtmlUtils.TAG_SPAN) ||
tag.equals(TtmlUtils.TAG_BR) || tag.equals(TtmlUtils.TAG_STYLE) ||
tag.equals(TtmlUtils.TAG_STYLING) || tag.equals(TtmlUtils.TAG_LAYOUT) ||
tag.equals(TtmlUtils.TAG_REGION) || tag.equals(TtmlUtils.TAG_METADATA) ||
tag.equals(TtmlUtils.TAG_SMPTE_IMAGE) || tag.equals(TtmlUtils.TAG_SMPTE_DATA) ||
tag.equals(TtmlUtils.TAG_SMPTE_INFORMATION)) {
return true;
}
return false;
}
}
/** @hide */
interface TtmlNodeListener {
void onTtmlNodeParsed(TtmlNode node);
void onRootNodeParsed(TtmlNode node);
}
/** @hide */
class TtmlTrack extends SubtitleTrack implements TtmlNodeListener {
private static final String TAG = "TtmlTrack";
private final TtmlParser mParser = new TtmlParser(this);
private final TtmlRenderingWidget mRenderingWidget;
private String mParsingData;
private Long mCurrentRunID;
private final LinkedList<TtmlNode> mTtmlNodes;
private final TreeSet<Long> mTimeEvents;
private TtmlNode mRootNode;
TtmlTrack(TtmlRenderingWidget renderingWidget, MediaFormat format) {
super(format);
mTtmlNodes = new LinkedList<TtmlNode>();
mTimeEvents = new TreeSet<Long>();
mRenderingWidget = renderingWidget;
mParsingData = "";
}
@Override
public TtmlRenderingWidget getRenderingWidget() {
return mRenderingWidget;
}
@Override
public void onData(byte[] data, boolean eos, long runID) {
try {
// TODO: handle UTF-8 conversion properly
String str = new String(data, "UTF-8");
// implement intermixing restriction for TTML.
synchronized(mParser) {
if (mCurrentRunID != null && runID != mCurrentRunID) {
throw new IllegalStateException(
"Run #" + mCurrentRunID +
" in progress. Cannot process run #" + runID);
}
mCurrentRunID = runID;
mParsingData += str;
if (eos) {
try {
mParser.parse(mParsingData, mCurrentRunID);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finishedRun(runID);
mParsingData = "";
mCurrentRunID = null;
}
}
} catch (java.io.UnsupportedEncodingException e) {
Log.w(TAG, "subtitle data is not UTF-8 encoded: " + e);
}
}
@Override
public void onTtmlNodeParsed(TtmlNode node) {
mTtmlNodes.addLast(node);
addTimeEvents(node);
}
@Override
public void onRootNodeParsed(TtmlNode node) {
mRootNode = node;
TtmlCue cue = null;
while ((cue = getNextResult()) != null) {
addCue(cue);
}
mRootNode = null;
mTtmlNodes.clear();
mTimeEvents.clear();
}
@Override
public void updateView(Vector<SubtitleTrack.Cue> activeCues) {
if (!mVisible) {
// don't keep the state if we are not visible
return;
}
if (DEBUG && mTimeProvider != null) {
try {
Log.d(TAG, "at " +
(mTimeProvider.getCurrentTimeUs(false, true) / 1000) +
" ms the active cues are:");
} catch (IllegalStateException e) {
Log.d(TAG, "at (illegal state) the active cues are:");
}
}
mRenderingWidget.setActiveCues(activeCues);
}
/**
* Returns a {@link TtmlCue} in the presentation time order.
* {@code null} is returned if there is no more timed text to show.
*/
public TtmlCue getNextResult() {
while (mTimeEvents.size() >= 2) {
long start = mTimeEvents.pollFirst();
long end = mTimeEvents.first();
List<TtmlNode> activeCues = getActiveNodes(start, end);
if (!activeCues.isEmpty()) {
return new TtmlCue(start, end,
TtmlUtils.applySpacePolicy(TtmlUtils.extractText(
mRootNode, start, end), false),
TtmlUtils.extractTtmlFragment(mRootNode, start, end));
}
}
return null;
}
private void addTimeEvents(TtmlNode node) {
mTimeEvents.add(node.mStartTimeMs);
mTimeEvents.add(node.mEndTimeMs);
for (int i = 0; i < node.mChildren.size(); ++i) {
addTimeEvents(node.mChildren.get(i));
}
}
private List<TtmlNode> getActiveNodes(long startTimeUs, long endTimeUs) {
List<TtmlNode> activeNodes = new ArrayList<TtmlNode>();
for (int i = 0; i < mTtmlNodes.size(); ++i) {
TtmlNode node = mTtmlNodes.get(i);
if (node.isActive(startTimeUs, endTimeUs)) {
activeNodes.add(node);
}
}
return activeNodes;
}
}
/**
* Widget capable of rendering TTML captions.
*
* @hide
*/
class TtmlRenderingWidget extends LinearLayout implements SubtitleTrack.RenderingWidget {
/** Callback for rendering changes. */
private OnChangedListener mListener;
private final TextView mTextView;
public TtmlRenderingWidget(Context context) {
this(context, null);
}
public TtmlRenderingWidget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TtmlRenderingWidget(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public TtmlRenderingWidget(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
// Cannot render text over video when layer type is hardware.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
CaptioningManager captionManager = (CaptioningManager) context.getSystemService(
Context.CAPTIONING_SERVICE);
mTextView = new TextView(context);
mTextView.setTextColor(captionManager.getUserStyle().foregroundColor);
addView(mTextView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mTextView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
}
@Override
public void setOnChangedListener(OnChangedListener listener) {
mListener = listener;
}
@Override
public void setSize(int width, int height) {
final int widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
measure(widthSpec, heightSpec);
layout(0, 0, width, height);
}
@Override
public void setVisible(boolean visible) {
if (visible) {
setVisibility(View.VISIBLE);
} else {
setVisibility(View.GONE);
}
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
public void setActiveCues(Vector<SubtitleTrack.Cue> activeCues) {
final int count = activeCues.size();
String subtitleText = "";
for (int i = 0; i < count; i++) {
TtmlCue cue = (TtmlCue) activeCues.get(i);
subtitleText += cue.mText + "\n";
}
mTextView.setText(subtitleText);
if (mListener != null) {
mListener.onChanged(this);
}
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.apigateway.model;
import java.io.Serializable;
/**
* <p>
* Represents a method.
* </p>
*/
public class PutMethodResult implements Serializable, Cloneable {
/**
* <p>
* The HTTP method.
* </p>
*/
private String httpMethod;
/**
* <p>
* The method's authorization type.
* </p>
*/
private String authorizationType;
/**
* <p>
* Specifies whether the method requires a valid <a>ApiKey</a>.
* </p>
*/
private Boolean apiKeyRequired;
/**
* <p>
* Represents request parameters that can be accepted by Amazon API Gateway.
* Request parameters are represented as a key/value map, with a source as
* the key and a Boolean flag as the value. The Boolean flag is used to
* specify whether the parameter is required. A source must match the
* pattern <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources specified
* here are available to the integration for mapping to integration request
* parameters or templates.
* </p>
*/
private java.util.Map<String, Boolean> requestParameters;
/**
* <p>
* Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as
* the key and a <a>Model</a> name as the value.
* </p>
*/
private java.util.Map<String, String> requestModels;
/**
* <p>
* Represents available responses that can be sent to the caller. Method
* responses are represented as a key/value map, with an HTTP status code as
* the key and a <a>MethodResponse</a> as the value. The status codes are
* available for the <a>Integration</a> responses to map to.
* </p>
*/
private java.util.Map<String, MethodResponse> methodResponses;
/**
* <p>
* The method's integration.
* </p>
*/
private Integration methodIntegration;
/**
* <p>
* The HTTP method.
* </p>
*
* @param httpMethod
* The HTTP method.
*/
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
/**
* <p>
* The HTTP method.
* </p>
*
* @return The HTTP method.
*/
public String getHttpMethod() {
return this.httpMethod;
}
/**
* <p>
* The HTTP method.
* </p>
*
* @param httpMethod
* The HTTP method.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withHttpMethod(String httpMethod) {
setHttpMethod(httpMethod);
return this;
}
/**
* <p>
* The method's authorization type.
* </p>
*
* @param authorizationType
* The method's authorization type.
*/
public void setAuthorizationType(String authorizationType) {
this.authorizationType = authorizationType;
}
/**
* <p>
* The method's authorization type.
* </p>
*
* @return The method's authorization type.
*/
public String getAuthorizationType() {
return this.authorizationType;
}
/**
* <p>
* The method's authorization type.
* </p>
*
* @param authorizationType
* The method's authorization type.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withAuthorizationType(String authorizationType) {
setAuthorizationType(authorizationType);
return this;
}
/**
* <p>
* Specifies whether the method requires a valid <a>ApiKey</a>.
* </p>
*
* @param apiKeyRequired
* Specifies whether the method requires a valid <a>ApiKey</a>.
*/
public void setApiKeyRequired(Boolean apiKeyRequired) {
this.apiKeyRequired = apiKeyRequired;
}
/**
* <p>
* Specifies whether the method requires a valid <a>ApiKey</a>.
* </p>
*
* @return Specifies whether the method requires a valid <a>ApiKey</a>.
*/
public Boolean getApiKeyRequired() {
return this.apiKeyRequired;
}
/**
* <p>
* Specifies whether the method requires a valid <a>ApiKey</a>.
* </p>
*
* @param apiKeyRequired
* Specifies whether the method requires a valid <a>ApiKey</a>.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withApiKeyRequired(Boolean apiKeyRequired) {
setApiKeyRequired(apiKeyRequired);
return this;
}
/**
* <p>
* Specifies whether the method requires a valid <a>ApiKey</a>.
* </p>
*
* @return Specifies whether the method requires a valid <a>ApiKey</a>.
*/
public Boolean isApiKeyRequired() {
return this.apiKeyRequired;
}
/**
* <p>
* Represents request parameters that can be accepted by Amazon API Gateway.
* Request parameters are represented as a key/value map, with a source as
* the key and a Boolean flag as the value. The Boolean flag is used to
* specify whether the parameter is required. A source must match the
* pattern <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources specified
* here are available to the integration for mapping to integration request
* parameters or templates.
* </p>
*
* @return Represents request parameters that can be accepted by Amazon API
* Gateway. Request parameters are represented as a key/value map,
* with a source as the key and a Boolean flag as the value. The
* Boolean flag is used to specify whether the parameter is
* required. A source must match the pattern
* <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources
* specified here are available to the integration for mapping to
* integration request parameters or templates.
*/
public java.util.Map<String, Boolean> getRequestParameters() {
return requestParameters;
}
/**
* <p>
* Represents request parameters that can be accepted by Amazon API Gateway.
* Request parameters are represented as a key/value map, with a source as
* the key and a Boolean flag as the value. The Boolean flag is used to
* specify whether the parameter is required. A source must match the
* pattern <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources specified
* here are available to the integration for mapping to integration request
* parameters or templates.
* </p>
*
* @param requestParameters
* Represents request parameters that can be accepted by Amazon API
* Gateway. Request parameters are represented as a key/value map,
* with a source as the key and a Boolean flag as the value. The
* Boolean flag is used to specify whether the parameter is required.
* A source must match the pattern
* <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources
* specified here are available to the integration for mapping to
* integration request parameters or templates.
*/
public void setRequestParameters(
java.util.Map<String, Boolean> requestParameters) {
this.requestParameters = requestParameters;
}
/**
* <p>
* Represents request parameters that can be accepted by Amazon API Gateway.
* Request parameters are represented as a key/value map, with a source as
* the key and a Boolean flag as the value. The Boolean flag is used to
* specify whether the parameter is required. A source must match the
* pattern <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources specified
* here are available to the integration for mapping to integration request
* parameters or templates.
* </p>
*
* @param requestParameters
* Represents request parameters that can be accepted by Amazon API
* Gateway. Request parameters are represented as a key/value map,
* with a source as the key and a Boolean flag as the value. The
* Boolean flag is used to specify whether the parameter is required.
* A source must match the pattern
* <code>method.request.{location}.{name}</code>, where
* <code>location</code> is either querystring, path, or header.
* <code>name</code> is a valid, unique parameter name. Sources
* specified here are available to the integration for mapping to
* integration request parameters or templates.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withRequestParameters(
java.util.Map<String, Boolean> requestParameters) {
setRequestParameters(requestParameters);
return this;
}
public PutMethodResult addRequestParametersEntry(String key, Boolean value) {
if (null == this.requestParameters) {
this.requestParameters = new java.util.HashMap<String, Boolean>();
}
if (this.requestParameters.containsKey(key))
throw new IllegalArgumentException("Duplicated keys ("
+ key.toString() + ") are provided.");
this.requestParameters.put(key, value);
return this;
}
/**
* Removes all the entries added into RequestParameters. <p> Returns a
* reference to this object so that method calls can be chained together.
*/
public PutMethodResult clearRequestParametersEntries() {
this.requestParameters = null;
return this;
}
/**
* <p>
* Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as
* the key and a <a>Model</a> name as the value.
* </p>
*
* @return Specifies the <a>Model</a> resources used for the request's
* content type. Request models are represented as a key/value map,
* with a content type as the key and a <a>Model</a> name as the
* value.
*/
public java.util.Map<String, String> getRequestModels() {
return requestModels;
}
/**
* <p>
* Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as
* the key and a <a>Model</a> name as the value.
* </p>
*
* @param requestModels
* Specifies the <a>Model</a> resources used for the request's
* content type. Request models are represented as a key/value map,
* with a content type as the key and a <a>Model</a> name as the
* value.
*/
public void setRequestModels(java.util.Map<String, String> requestModels) {
this.requestModels = requestModels;
}
/**
* <p>
* Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as
* the key and a <a>Model</a> name as the value.
* </p>
*
* @param requestModels
* Specifies the <a>Model</a> resources used for the request's
* content type. Request models are represented as a key/value map,
* with a content type as the key and a <a>Model</a> name as the
* value.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withRequestModels(
java.util.Map<String, String> requestModels) {
setRequestModels(requestModels);
return this;
}
public PutMethodResult addRequestModelsEntry(String key, String value) {
if (null == this.requestModels) {
this.requestModels = new java.util.HashMap<String, String>();
}
if (this.requestModels.containsKey(key))
throw new IllegalArgumentException("Duplicated keys ("
+ key.toString() + ") are provided.");
this.requestModels.put(key, value);
return this;
}
/**
* Removes all the entries added into RequestModels. <p> Returns a
* reference to this object so that method calls can be chained together.
*/
public PutMethodResult clearRequestModelsEntries() {
this.requestModels = null;
return this;
}
/**
* <p>
* Represents available responses that can be sent to the caller. Method
* responses are represented as a key/value map, with an HTTP status code as
* the key and a <a>MethodResponse</a> as the value. The status codes are
* available for the <a>Integration</a> responses to map to.
* </p>
*
* @return Represents available responses that can be sent to the caller.
* Method responses are represented as a key/value map, with an HTTP
* status code as the key and a <a>MethodResponse</a> as the value.
* The status codes are available for the <a>Integration</a>
* responses to map to.
*/
public java.util.Map<String, MethodResponse> getMethodResponses() {
return methodResponses;
}
/**
* <p>
* Represents available responses that can be sent to the caller. Method
* responses are represented as a key/value map, with an HTTP status code as
* the key and a <a>MethodResponse</a> as the value. The status codes are
* available for the <a>Integration</a> responses to map to.
* </p>
*
* @param methodResponses
* Represents available responses that can be sent to the caller.
* Method responses are represented as a key/value map, with an HTTP
* status code as the key and a <a>MethodResponse</a> as the value.
* The status codes are available for the <a>Integration</a>
* responses to map to.
*/
public void setMethodResponses(
java.util.Map<String, MethodResponse> methodResponses) {
this.methodResponses = methodResponses;
}
/**
* <p>
* Represents available responses that can be sent to the caller. Method
* responses are represented as a key/value map, with an HTTP status code as
* the key and a <a>MethodResponse</a> as the value. The status codes are
* available for the <a>Integration</a> responses to map to.
* </p>
*
* @param methodResponses
* Represents available responses that can be sent to the caller.
* Method responses are represented as a key/value map, with an HTTP
* status code as the key and a <a>MethodResponse</a> as the value.
* The status codes are available for the <a>Integration</a>
* responses to map to.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withMethodResponses(
java.util.Map<String, MethodResponse> methodResponses) {
setMethodResponses(methodResponses);
return this;
}
public PutMethodResult addMethodResponsesEntry(String key,
MethodResponse value) {
if (null == this.methodResponses) {
this.methodResponses = new java.util.HashMap<String, MethodResponse>();
}
if (this.methodResponses.containsKey(key))
throw new IllegalArgumentException("Duplicated keys ("
+ key.toString() + ") are provided.");
this.methodResponses.put(key, value);
return this;
}
/**
* Removes all the entries added into MethodResponses. <p> Returns a
* reference to this object so that method calls can be chained together.
*/
public PutMethodResult clearMethodResponsesEntries() {
this.methodResponses = null;
return this;
}
/**
* <p>
* The method's integration.
* </p>
*
* @param methodIntegration
* The method's integration.
*/
public void setMethodIntegration(Integration methodIntegration) {
this.methodIntegration = methodIntegration;
}
/**
* <p>
* The method's integration.
* </p>
*
* @return The method's integration.
*/
public Integration getMethodIntegration() {
return this.methodIntegration;
}
/**
* <p>
* The method's integration.
* </p>
*
* @param methodIntegration
* The method's integration.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public PutMethodResult withMethodIntegration(Integration methodIntegration) {
setMethodIntegration(methodIntegration);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHttpMethod() != null)
sb.append("HttpMethod: " + getHttpMethod() + ",");
if (getAuthorizationType() != null)
sb.append("AuthorizationType: " + getAuthorizationType() + ",");
if (getApiKeyRequired() != null)
sb.append("ApiKeyRequired: " + getApiKeyRequired() + ",");
if (getRequestParameters() != null)
sb.append("RequestParameters: " + getRequestParameters() + ",");
if (getRequestModels() != null)
sb.append("RequestModels: " + getRequestModels() + ",");
if (getMethodResponses() != null)
sb.append("MethodResponses: " + getMethodResponses() + ",");
if (getMethodIntegration() != null)
sb.append("MethodIntegration: " + getMethodIntegration());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof PutMethodResult == false)
return false;
PutMethodResult other = (PutMethodResult) obj;
if (other.getHttpMethod() == null ^ this.getHttpMethod() == null)
return false;
if (other.getHttpMethod() != null
&& other.getHttpMethod().equals(this.getHttpMethod()) == false)
return false;
if (other.getAuthorizationType() == null
^ this.getAuthorizationType() == null)
return false;
if (other.getAuthorizationType() != null
&& other.getAuthorizationType().equals(
this.getAuthorizationType()) == false)
return false;
if (other.getApiKeyRequired() == null
^ this.getApiKeyRequired() == null)
return false;
if (other.getApiKeyRequired() != null
&& other.getApiKeyRequired().equals(this.getApiKeyRequired()) == false)
return false;
if (other.getRequestParameters() == null
^ this.getRequestParameters() == null)
return false;
if (other.getRequestParameters() != null
&& other.getRequestParameters().equals(
this.getRequestParameters()) == false)
return false;
if (other.getRequestModels() == null ^ this.getRequestModels() == null)
return false;
if (other.getRequestModels() != null
&& other.getRequestModels().equals(this.getRequestModels()) == false)
return false;
if (other.getMethodResponses() == null
^ this.getMethodResponses() == null)
return false;
if (other.getMethodResponses() != null
&& other.getMethodResponses().equals(this.getMethodResponses()) == false)
return false;
if (other.getMethodIntegration() == null
^ this.getMethodIntegration() == null)
return false;
if (other.getMethodIntegration() != null
&& other.getMethodIntegration().equals(
this.getMethodIntegration()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getHttpMethod() == null) ? 0 : getHttpMethod().hashCode());
hashCode = prime
* hashCode
+ ((getAuthorizationType() == null) ? 0
: getAuthorizationType().hashCode());
hashCode = prime
* hashCode
+ ((getApiKeyRequired() == null) ? 0 : getApiKeyRequired()
.hashCode());
hashCode = prime
* hashCode
+ ((getRequestParameters() == null) ? 0
: getRequestParameters().hashCode());
hashCode = prime
* hashCode
+ ((getRequestModels() == null) ? 0 : getRequestModels()
.hashCode());
hashCode = prime
* hashCode
+ ((getMethodResponses() == null) ? 0 : getMethodResponses()
.hashCode());
hashCode = prime
* hashCode
+ ((getMethodIntegration() == null) ? 0
: getMethodIntegration().hashCode());
return hashCode;
}
@Override
public PutMethodResult clone() {
try {
return (PutMethodResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.jvm.java.abi;
import com.facebook.buck.javacd.model.AbiGenerationMode;
import com.facebook.buck.jvm.java.abi.kotlin.KotlinMetadataReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InnerClassNode;
class StubJarClassEntry extends StubJarEntry {
private static final String DEFAULT_METHOD_SUFFIX = "$default";
private static final int DEFAULT_METHOD_SUFFIX_LENGTH = DEFAULT_METHOD_SUFFIX.length();
@Nullable private final Set<String> referencedClassNames;
private final List<String> methodBodiesToRetain;
private final Path path;
private final ClassNode stub;
private final boolean retainEverything;
@Nullable
public static StubJarClassEntry of(
LibraryReader input,
Path path,
@Nullable AbiGenerationMode compatibilityMode,
boolean isKotlinModule,
Map<String, List<String>> inlineFunctionsMap)
throws IOException {
ClassNode stub = new ClassNode(Opcodes.ASM7);
// Kotlin has the concept of "inline functions", which means that we need to retain the body
// of these functions so that the compiler is able to inline them.
List<String> methodBodiesToRetain = Collections.emptyList();
boolean isKotlinClass = false;
boolean retainAllMethodBodies = false;
if (isKotlinModule) {
AnnotationNode kotlinMetadataAnnotation = findKotlinMetadataAnnotation(input, path);
if (kotlinMetadataAnnotation != null) {
isKotlinClass = true;
if (path.toString().contains("$sam$i")) {
// These classes are created when we have a Single Abstract Method (SAM) interface that is
// used within an inline function, and in these cases we need to retain the whole class.
input.visitClass(path, stub, false);
return new StubJarClassEntry(
path, stub, Collections.emptySet(), Collections.emptyList(), true);
}
ClassNode dummyStub = new ClassNode(Opcodes.ASM7);
input.visitClass(path, dummyStub, true);
retainAllMethodBodies =
retainAllMethodBodies(
inlineFunctionsMap, path, dummyStub.outerClass, dummyStub.outerMethod);
if (retainAllMethodBodies) {
methodBodiesToRetain =
dummyStub.methods.stream()
.map(methodNode -> methodNode.name)
.collect(Collectors.toList());
} else {
methodBodiesToRetain = KotlinMetadataReader.getInlineFunctions(kotlinMetadataAnnotation);
}
}
}
// As we read the class in, we create a partial stub that removes non-ABI methods and fields
// but leaves the entire InnerClasses table. We record all classes that are referenced from
// ABI methods and fields, and will use that information later to filter the InnerClasses table.
ClassReferenceTracker referenceTracker = new ClassReferenceTracker(stub);
ClassVisitor firstLevelFiltering =
new AbiFilteringClassVisitor(referenceTracker, methodBodiesToRetain);
// If we want ABIs that are compatible with those generated from source, we add a visitor
// at the very start of the chain which transforms the event stream coming out of `ClassNode`
// to look like what ClassVisitorDriverFromElement would have produced.
if (compatibilityMode != null && compatibilityMode != AbiGenerationMode.CLASS) {
firstLevelFiltering = new SourceAbiCompatibleVisitor(firstLevelFiltering, compatibilityMode);
}
input.visitClass(path, firstLevelFiltering, /* skipCode */ !isKotlinClass);
// The synthetic package-info class is how package annotations are recorded; that one is
// actually used by the compiler
if (!isAnonymousOrLocalOrSyntheticClass(stub)
|| retainAllMethodBodies
|| stub.name.endsWith("/package-info")) {
return new StubJarClassEntry(
path, stub, referenceTracker.getReferencedClassNames(), methodBodiesToRetain, false);
}
return null;
}
private StubJarClassEntry(
Path path,
ClassNode stub,
Set<String> referencedClassNames,
List<String> methodBodiesToRetain,
boolean retainEverything) {
this.path = path;
this.stub = stub;
this.referencedClassNames = referencedClassNames;
this.methodBodiesToRetain = methodBodiesToRetain;
this.retainEverything = retainEverything;
}
@Override
public void write(StubJarWriter writer) {
writer.writeEntry(path, this::openInputStream);
}
@Override
public List<String> getInlineMethods() {
return methodBodiesToRetain;
}
private InputStream openInputStream() {
ClassWriter writer = new ClassWriter(0);
ClassVisitor visitor = writer;
if (!retainEverything) {
visitor = new InnerClassSortingClassVisitor(stub.name, visitor);
visitor = new AbiFilteringClassVisitor(visitor, methodBodiesToRetain, referencedClassNames);
}
stub.accept(visitor);
return new ByteArrayInputStream(writer.toByteArray());
}
private static boolean isAnonymousOrLocalOrSyntheticClass(ClassNode node) {
if ((node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC) {
return true;
}
InnerClassNode innerClass = getInnerClassMetadata(node);
while (innerClass != null) {
if (innerClass.outerName == null) {
return true;
}
innerClass = getInnerClassMetadata(node, innerClass.outerName);
}
return false;
}
/**
* If this is a class that was created for a method that needs to be inlined, then we need to make
* sure that we retain its methods.
*/
private static boolean retainAllMethodBodies(
Map<String, List<String>> inlineFunctionsMap,
Path path,
String outerClass,
String outerMethod) {
if (path.toString().contains("$$inlined$")) {
// These classes are created when a function calls an inline function with a crossinline
// parameter.
return true;
}
final List<String> inlineFunctions = inlineFunctionsMap.get(outerClass);
if (inlineFunctions == null || outerMethod == null) {
return false;
}
return inlineFunctions.contains(sanitizeMethodName(outerMethod));
}
private static String sanitizeMethodName(String methodName) {
if (methodName.endsWith(DEFAULT_METHOD_SUFFIX)) {
return methodName.substring(0, methodName.length() - DEFAULT_METHOD_SUFFIX_LENGTH);
}
return methodName;
}
@Nullable
private static InnerClassNode getInnerClassMetadata(ClassNode node) {
String name = node.name;
return getInnerClassMetadata(node, name);
}
@Nullable
private static AnnotationNode findKotlinMetadataAnnotation(LibraryReader input, Path relativePath)
throws IOException {
final List<AnnotationNode> annotations = getVisibleAnnotations(input, relativePath);
if (annotations == null) {
return null;
}
return annotations.stream()
.filter(annotation -> "Lkotlin/Metadata;".equals(annotation.desc))
.findFirst()
.orElse(null);
}
private static List<AnnotationNode> getVisibleAnnotations(LibraryReader input, Path relativePath)
throws IOException {
ClassNode node = new ClassNode();
input.visitClass(relativePath, node, /* skipCode */ true);
return node.visibleAnnotations;
}
@Nullable
private static InnerClassNode getInnerClassMetadata(ClassNode node, String className) {
for (InnerClassNode innerClass : node.innerClasses) {
if (innerClass.name.equals(className)) {
return innerClass;
}
}
return null;
}
private static class InnerClassSortingClassVisitor extends ClassVisitor {
private final String className;
private final List<InnerClassNode> innerClasses = new ArrayList<>();
private final List<String> nestMembers = new ArrayList<>();
private InnerClassSortingClassVisitor(String className, ClassVisitor cv) {
super(Opcodes.ASM7, cv);
this.className = className;
}
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
innerClasses.add(new InnerClassNode(name, outerName, innerName, access));
}
@Override
public void visitNestMember(String nestMember) {
nestMembers.add(nestMember);
}
@Override
public void visitEnd() {
innerClasses.sort(
(o1, o2) -> {
// Enclosing classes and member classes should come first, with their order preserved
boolean o1IsEnclosingOrMember = isEnclosingOrMember(o1);
boolean o2IsEnclosingOrMember = isEnclosingOrMember(o2);
if (o1IsEnclosingOrMember && o2IsEnclosingOrMember) {
// Preserve order among these
return 0;
} else if (o1IsEnclosingOrMember) {
return -1;
} else if (o2IsEnclosingOrMember) {
return 1;
}
// References to other classes get sorted.
return o1.name.compareTo(o2.name);
});
for (InnerClassNode innerClass : innerClasses) {
innerClass.accept(cv);
}
nestMembers.stream().sorted().forEach(nestMember -> cv.visitNestMember(nestMember));
super.visitEnd();
}
private boolean isEnclosingOrMember(InnerClassNode innerClass) {
if (className.equals(innerClass.name)) {
// Self!
return true;
}
if (className.equals(innerClass.outerName)) {
// Member class
return true;
}
// Enclosing class
return className.startsWith(innerClass.name + "$");
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper;
import com.carrotsearch.hppc.ObjectObjectHashMap;
import com.carrotsearch.hppc.ObjectObjectMap;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LegacyIntField;
import org.apache.lucene.document.LegacyLongField;
import org.apache.lucene.document.LegacyFloatField;
import org.apache.lucene.document.LegacyDoubleField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.lucene.all.AllEntries;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.mapper.object.RootObjectMapper;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
*/
public abstract class ParseContext {
/** Fork of {@link org.apache.lucene.document.Document} with additional functionality. */
public static class Document implements Iterable<IndexableField> {
private final Document parent;
private final String path;
private final String prefix;
private final List<IndexableField> fields;
private ObjectObjectMap<Object, IndexableField> keyedFields;
private Document(String path, Document parent) {
fields = new ArrayList<>();
this.path = path;
this.prefix = path.isEmpty() ? "" : path + ".";
this.parent = parent;
}
public Document() {
this("", null);
}
/**
* Return the path associated with this document.
*/
public String getPath() {
return path;
}
/**
* Return a prefix that all fields in this document should have.
*/
public String getPrefix() {
return prefix;
}
/**
* Return the parent document, or null if this is the root document.
*/
public Document getParent() {
return parent;
}
@Override
public Iterator<IndexableField> iterator() {
return fields.iterator();
}
public List<IndexableField> getFields() {
return fields;
}
public void add(IndexableField field) {
// either a meta fields or starts with the prefix
assert field.name().startsWith("_") || field.name().startsWith(prefix) : field.name() + " " + prefix;
fields.add(field);
}
/** Add fields so that they can later be fetched using {@link #getByKey(Object)}. */
public void addWithKey(Object key, IndexableField field) {
if (keyedFields == null) {
keyedFields = new ObjectObjectHashMap<>();
} else if (keyedFields.containsKey(key)) {
throw new IllegalStateException("Only one field can be stored per key");
}
keyedFields.put(key, field);
add(field);
}
/** Get back fields that have been previously added with {@link #addWithKey(Object, IndexableField)}. */
public IndexableField getByKey(Object key) {
return keyedFields == null ? null : keyedFields.get(key);
}
public IndexableField[] getFields(String name) {
List<IndexableField> f = new ArrayList<>();
for (IndexableField field : fields) {
if (field.name().equals(name)) {
f.add(field);
}
}
return f.toArray(new IndexableField[f.size()]);
}
/**
* Returns an array of values of the field specified as the method parameter.
* This method returns an empty array when there are no
* matching fields. It never returns null.
* For {@link org.apache.lucene.document.LegacyIntField}, {@link org.apache.lucene.document.LegacyLongField}, {@link
* org.apache.lucene.document.LegacyFloatField} and {@link org.apache.lucene.document.LegacyDoubleField} it returns the string value of the number.
* If you want the actual numeric field instances back, use {@link #getFields}.
* @param name the name of the field
* @return a <code>String[]</code> of field values
*/
public final String[] getValues(String name) {
List<String> result = new ArrayList<>();
for (IndexableField field : fields) {
if (field.name().equals(name) && field.stringValue() != null) {
result.add(field.stringValue());
}
}
return result.toArray(new String[result.size()]);
}
public IndexableField getField(String name) {
for (IndexableField field : fields) {
if (field.name().equals(name)) {
return field;
}
}
return null;
}
public String get(String name) {
for (IndexableField f : fields) {
if (f.name().equals(name) && f.stringValue() != null) {
return f.stringValue();
}
}
return null;
}
public BytesRef getBinaryValue(String name) {
for (IndexableField f : fields) {
if (f.name().equals(name) && f.binaryValue() != null) {
return f.binaryValue();
}
}
return null;
}
}
private static class FilterParseContext extends ParseContext {
private final ParseContext in;
private FilterParseContext(ParseContext in) {
this.in = in;
}
@Override
public DocumentMapperParser docMapperParser() {
return in.docMapperParser();
}
@Override
public boolean isWithinCopyTo() {
return in.isWithinCopyTo();
}
@Override
public boolean isWithinMultiFields() {
return in.isWithinMultiFields();
}
@Override
public String index() {
return in.index();
}
@Override
public Settings indexSettings() {
return in.indexSettings();
}
@Override
public String type() {
return in.type();
}
@Override
public SourceToParse sourceToParse() {
return in.sourceToParse();
}
@Override
public BytesReference source() {
return in.source();
}
@Override
public void source(BytesReference source) {
in.source(source);
}
@Override
public ContentPath path() {
return in.path();
}
@Override
public XContentParser parser() {
return in.parser();
}
@Override
public Document rootDoc() {
return in.rootDoc();
}
@Override
public List<Document> docs() {
return in.docs();
}
@Override
public Document doc() {
return in.doc();
}
@Override
public void addDoc(Document doc) {
in.addDoc(doc);
}
@Override
public RootObjectMapper root() {
return in.root();
}
@Override
public DocumentMapper docMapper() {
return in.docMapper();
}
@Override
public AnalysisService analysisService() {
return in.analysisService();
}
@Override
public MapperService mapperService() {
return in.mapperService();
}
@Override
public String id() {
return in.id();
}
@Override
public void id(String id) {
in.id(id);
}
@Override
public Field uid() {
return in.uid();
}
@Override
public void uid(Field uid) {
in.uid(uid);
}
@Override
public Field version() {
return in.version();
}
@Override
public void version(Field version) {
in.version(version);
}
@Override
public AllEntries allEntries() {
return in.allEntries();
}
@Override
public boolean externalValueSet() {
return in.externalValueSet();
}
@Override
public Object externalValue() {
return in.externalValue();
}
@Override
public StringBuilder stringBuilder() {
return in.stringBuilder();
}
@Override
public void addDynamicMapper(Mapper update) {
in.addDynamicMapper(update);
}
@Override
public List<Mapper> getDynamicMappers() {
return in.getDynamicMappers();
}
}
public static class InternalParseContext extends ParseContext {
private final DocumentMapper docMapper;
private final DocumentMapperParser docMapperParser;
private final ContentPath path;
private XContentParser parser;
private Document document;
private List<Document> documents = new ArrayList<>();
@Nullable
private final Settings indexSettings;
private SourceToParse sourceToParse;
private BytesReference source;
private String id;
private Field uid, version;
private StringBuilder stringBuilder = new StringBuilder();
private AllEntries allEntries = new AllEntries();
private List<Mapper> dynamicMappers = new ArrayList<>();
public InternalParseContext(@Nullable Settings indexSettings, DocumentMapperParser docMapperParser, DocumentMapper docMapper, ContentPath path) {
this.indexSettings = indexSettings;
this.docMapper = docMapper;
this.docMapperParser = docMapperParser;
this.path = path;
}
public void reset(XContentParser parser, Document document, SourceToParse source) {
this.parser = parser;
this.document = document;
if (document != null) {
this.documents = new ArrayList<>();
this.documents.add(document);
} else {
this.documents = null;
}
this.uid = null;
this.version = null;
this.id = null;
this.sourceToParse = source;
this.source = source == null ? null : sourceToParse.source();
this.path.reset();
this.allEntries = new AllEntries();
this.dynamicMappers = new ArrayList<>();
}
@Override
public DocumentMapperParser docMapperParser() {
return this.docMapperParser;
}
@Override
public String index() {
return sourceToParse.index();
}
@Override
@Nullable
public Settings indexSettings() {
return this.indexSettings;
}
@Override
public String type() {
return sourceToParse.type();
}
@Override
public SourceToParse sourceToParse() {
return this.sourceToParse;
}
@Override
public BytesReference source() {
return source;
}
// only should be used by SourceFieldMapper to update with a compressed source
@Override
public void source(BytesReference source) {
this.source = source;
}
@Override
public ContentPath path() {
return this.path;
}
@Override
public XContentParser parser() {
return this.parser;
}
@Override
public Document rootDoc() {
return documents.get(0);
}
@Override
public List<Document> docs() {
return this.documents;
}
@Override
public Document doc() {
return this.document;
}
@Override
public void addDoc(Document doc) {
this.documents.add(doc);
}
@Override
public RootObjectMapper root() {
return docMapper.root();
}
@Override
public DocumentMapper docMapper() {
return this.docMapper;
}
@Override
public AnalysisService analysisService() {
return docMapperParser.analysisService;
}
@Override
public MapperService mapperService() {
return docMapperParser.mapperService;
}
@Override
public String id() {
return id;
}
/**
* Really, just the id mapper should set this.
*/
@Override
public void id(String id) {
this.id = id;
}
@Override
public Field uid() {
return this.uid;
}
/**
* Really, just the uid mapper should set this.
*/
@Override
public void uid(Field uid) {
this.uid = uid;
}
@Override
public Field version() {
return this.version;
}
@Override
public void version(Field version) {
this.version = version;
}
@Override
public AllEntries allEntries() {
return this.allEntries;
}
/**
* A string builder that can be used to construct complex names for example.
* Its better to reuse the.
*/
@Override
public StringBuilder stringBuilder() {
stringBuilder.setLength(0);
return this.stringBuilder;
}
@Override
public void addDynamicMapper(Mapper mapper) {
dynamicMappers.add(mapper);
}
@Override
public List<Mapper> getDynamicMappers() {
return dynamicMappers;
}
}
public abstract DocumentMapperParser docMapperParser();
/**
* Return a new context that will be within a copy-to operation.
*/
public final ParseContext createCopyToContext() {
return new FilterParseContext(this) {
@Override
public boolean isWithinCopyTo() {
return true;
}
};
}
public boolean isWithinCopyTo() {
return false;
}
/**
* Return a new context that will be within multi-fields.
*/
public final ParseContext createMultiFieldContext() {
return new FilterParseContext(this) {
@Override
public boolean isWithinMultiFields() {
return true;
}
};
}
/**
* Return a new context that will be used within a nested document.
*/
public final ParseContext createNestedContext(String fullPath) {
final Document doc = new Document(fullPath, doc());
addDoc(doc);
return switchDoc(doc);
}
/**
* Return a new context that has the provided document as the current document.
*/
public final ParseContext switchDoc(final Document document) {
return new FilterParseContext(this) {
@Override
public Document doc() {
return document;
}
};
}
/**
* Return a new context that will have the provided path.
*/
public final ParseContext overridePath(final ContentPath path) {
return new FilterParseContext(this) {
@Override
public ContentPath path() {
return path;
}
};
}
public boolean isWithinMultiFields() {
return false;
}
public abstract String index();
@Nullable
public abstract Settings indexSettings();
public abstract String type();
public abstract SourceToParse sourceToParse();
@Nullable
public abstract BytesReference source();
// only should be used by SourceFieldMapper to update with a compressed source
public abstract void source(BytesReference source);
public abstract ContentPath path();
public abstract XContentParser parser();
public abstract Document rootDoc();
public abstract List<Document> docs();
public abstract Document doc();
public abstract void addDoc(Document doc);
public abstract RootObjectMapper root();
public abstract DocumentMapper docMapper();
public abstract AnalysisService analysisService();
public abstract MapperService mapperService();
public abstract String id();
/**
* Really, just the id mapper should set this.
*/
public abstract void id(String id);
public abstract Field uid();
/**
* Really, just the uid mapper should set this.
*/
public abstract void uid(Field uid);
public abstract Field version();
public abstract void version(Field version);
public final boolean includeInAll(Boolean includeInAll, FieldMapper mapper) {
return includeInAll(includeInAll, mapper.fieldType().indexOptions() != IndexOptions.NONE);
}
/**
* Is all included or not. Will always disable it if {@link org.elasticsearch.index.mapper.internal.AllFieldMapper#enabled()}
* is <tt>false</tt>. If its enabled, then will return <tt>true</tt> only if the specific flag is <tt>null</tt> or
* its actual value (so, if not set, defaults to "true") and the field is indexed.
*/
private boolean includeInAll(Boolean specificIncludeInAll, boolean indexed) {
if (isWithinCopyTo()) {
return false;
}
if (isWithinMultiFields()) {
return false;
}
if (!docMapper().allFieldMapper().enabled()) {
return false;
}
// not explicitly set
if (specificIncludeInAll == null) {
return indexed;
}
return specificIncludeInAll;
}
public abstract AllEntries allEntries();
/**
* Return a new context that will have the external value set.
*/
public final ParseContext createExternalValueContext(final Object externalValue) {
return new FilterParseContext(this) {
@Override
public boolean externalValueSet() {
return true;
}
@Override
public Object externalValue() {
return externalValue;
}
};
}
public boolean externalValueSet() {
return false;
}
public Object externalValue() {
throw new IllegalStateException("External value is not set");
}
/**
* Try to parse an externalValue if any
* @param clazz Expected class for external value
* @return null if no external value has been set or the value
*/
public final <T> T parseExternalValue(Class<T> clazz) {
if (!externalValueSet() || externalValue() == null) {
return null;
}
if (!clazz.isInstance(externalValue())) {
throw new IllegalArgumentException("illegal external value class ["
+ externalValue().getClass().getName() + "]. Should be " + clazz.getName());
}
return clazz.cast(externalValue());
}
/**
* A string builder that can be used to construct complex names for example.
* Its better to reuse the.
*/
public abstract StringBuilder stringBuilder();
/**
* Add a new mapper dynamically created while parsing.
*/
public abstract void addDynamicMapper(Mapper update);
/**
* Get dynamic mappers created while parsing.
*/
public abstract List<Mapper> getDynamicMappers();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.