answer
stringlengths 17
10.2M
|
|---|
package seedu.taskboss.logic.parser;
import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.HashSet;
import java.util.Set;
import seedu.taskboss.logic.commands.Command;
import seedu.taskboss.logic.commands.DeleteCommand;
import seedu.taskboss.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
*/
public Command parse(String args) {
Set<Integer> index = parseIndex(args);
if (index.isEmpty()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index);
}
private Set<Integer> parseIndex(String indexList) {
Set<Integer> taskIndex = new HashSet<Integer>();
String trimmedList = indexList.trim();
String[] indexes = trimmedList.split(" ");
for (String index : indexes) {
taskIndex.add(Integer.parseInt(index));
}
return taskIndex;
}
}
|
package software.sitb.dswrs.server.rpc;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import software.sitb.dswrs.core.rpc.RpcRequest;
import software.sitb.dswrs.core.rpc.RpcResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @author Sean sean.snow@live.com
*/
public class RpcServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcServerHandler.class);
private Map<String, Object> rpcServiceBean;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ctx.writeAndFlush(handler((RpcRequest) msg));
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error(",", cause);
if (ctx.channel().isActive()) {
ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
/**
* RPC
*
* @param request RPC
* @return RPC
* @see RpcResponse
*/
private RpcResponse handler(RpcRequest request) {
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
String className = request.getClassName();
Object serviceBean = rpcServiceBean.get(className);
if (null == serviceBean) {
throw new IllegalArgumentException("RPC -> " + className);
}
Class<?> serviceClass = serviceBean.getClass();
String methodName = request.getMethodName();
Class<?>[] parameterTypes = request.getParameterTypes();
Object[] parameters = request.getParameters();
Object[] params = new Object[parameters.length];
// null,null
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] instanceof String && parameters[i].equals("DSWRS_NULL_DATA")) {
params[i] = null;
} else {
params[i] = parameters[i];
}
}
FastClass serviceFastClass = FastClass.create(serviceClass);
FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
try {
response.setResult(serviceFastMethod.invoke(serviceBean, params));
} catch (InvocationTargetException t) {
LOGGER.error("RPC Handler Error -> {}", t.getTargetException().getMessage(), t.getTargetException());
response.setError(t.getTargetException());
}
return response;
}
public void setRpcServiceBean(Map<String, Object> rpcServiceBean) {
this.rpcServiceBean = rpcServiceBean;
}
}
|
package tld.testmod.common.animation;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.model.animation.Animation;
import net.minecraftforge.common.animation.Event;
import net.minecraftforge.common.animation.ITimeValue;
import net.minecraftforge.common.animation.TimeValues.VariableValue;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.model.animation.CapabilityAnimation;
import net.minecraftforge.common.model.animation.IAnimationStateMachine;
import tld.testmod.Main;
import tld.testmod.ModLogger;
import tld.testmod.init.ModBlocks;
public class TestAnimTileEntity extends TileEntity
{
private boolean openState = false;
private boolean previousRedstoneState;
@Nullable
private final IAnimationStateMachine asm;
private final VariableValue clickTime = new VariableValue(Float.NEGATIVE_INFINITY);
public TestAnimTileEntity()
{
asm = Main.proxy.load(new ResourceLocation(Main.MODID, "asms/block/test_anim.json"), ImmutableMap.<String, ITimeValue>of(
"click_time", clickTime
));
}
/* (non-Javadoc)
* @see net.minecraft.tileentity.TileEntity#setWorld(net.minecraft.world.World)
*/
@Override
public void setWorld(World worldIn)
{
if (worldIn.isRemote && asm != null)
asm.transition(openState ? "open" : "closed");
super.setWorld(worldIn);
}
/* (non-Javadoc)
* @see net.minecraft.tileentity.TileEntity#setWorldCreate(net.minecraft.world.World)
*/
@Override
protected void setWorldCreate(World worldIn)
{
if (worldIn.isRemote && asm != null)
asm.transition(openState ? "open" : "closed");
super.setWorld(worldIn);
}
public void handleEvents(float time, Iterable<Event> pastEvents)
{
for(Event event : pastEvents)
{
System.out.println("Event: " + event.event() + " " + event.offset() + " " + getPos() + " " + time);
}
}
@Override
public boolean hasFastRenderer()
{
return true;
}
public void click(boolean isOpen)
{
if (!this.getWorld().isRemote)
{
openState = !openState;
setOpenState(openState);
this.getWorld().addBlockEvent(pos, ModBlocks.TEST_ANIM, 0, openState ? 1 : 0 );
}
if(this.getWorld().isRemote) {
if (asm != null)
{
if(!isOpen) {
float time = Animation.getWorldTime(getWorld(), Animation.getPartialTickTime());
clickTime.setValue(time);
asm.transition("closing");
ModLogger.info("click closing: %f", time);
} else {
float time = Animation.getWorldTime(getWorld(), Animation.getPartialTickTime());
clickTime.setValue(time);
asm.transition("opening");
ModLogger.info("click opening: %f", time);
}
}
}
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing side)
{
if(capability == CapabilityAnimation.ANIMATION_CAPABILITY)
{
return true;
}
return super.hasCapability(capability, side);
}
@Override
@Nullable
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing side)
{
if(capability == CapabilityAnimation.ANIMATION_CAPABILITY)
{
return CapabilityAnimation.ANIMATION_CAPABILITY.cast(asm);
}
return super.getCapability(capability, side);
}
/**
* @return the previousRedstoneState
*/
public boolean isPreviousRedstoneState()
{
return previousRedstoneState;
}
/**
* @param previousRedstoneState the previousRedstoneState to set
*/
public void setPreviousRedstoneState(boolean previousRedstoneState)
{
this.previousRedstoneState = previousRedstoneState;
syncToClient();
}
/**
* @return the pitch
*/
public boolean getOpenState()
{
return openState;
}
/**
* @param pitch the pitch to set
*/
public void setOpenState(boolean openState)
{
this.openState = openState;
syncToClient();
}
// Persistence and syncing to client
@Override
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
openState = tag.getBoolean("open_state");
previousRedstoneState = tag.getBoolean("powered");
if (this.getWorld().isRemote && asm != null )
asm.transition(openState ? "open" : "closed");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag)
{
tag.setBoolean("open_state", openState);
tag.setBoolean("powered", this.previousRedstoneState);
return super.writeToNBT(tag);
}
public void syncToClient()
{
this.markDirty();
if (world != null)
{
if (!this.getWorld().isRemote && !this.isInvalid())
{
IBlockState state = this.getWorld().getBlockState(this.getPos());
/**
* Sets the block state at a given location. Flag 1 will cause a
* block update. Flag 2 will send the change to clients (you
* almost always want this). Flag 4 prevents the block from
* being re-rendered, if this is a client world. Flags can be
* added together.
*/
this.getWorld().notifyBlockUpdate(getPos(), state, state, 3);
}
}
}
@Override
public NBTTagCompound getUpdateTag()
{
NBTTagCompound tag = super.getUpdateTag();
return this.writeToNBT(tag);
}
@Override
public SPacketUpdateTileEntity getUpdatePacket()
{
NBTTagCompound cmp = new NBTTagCompound();
this.writeToNBT(cmp);
return new SPacketUpdateTileEntity(pos, 1, cmp);
}
@Override
public void onDataPacket(NetworkManager manager, SPacketUpdateTileEntity packet)
{
this.readFromNBT(packet.getNbtCompound());
}
}
|
package uk.co.jemos.podam.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.jemos.podam.api.PodamUtils;
import uk.co.jemos.podam.exceptions.PodamMockeryException;
import javax.validation.constraints.*;
import java.lang.annotation.Annotation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* This strategy fills attributes and parameters annotated with Java bean
* validation annotations
*
* @author daivanov
*/
public class BeanValidationStrategy implements AttributeStrategy<Object> {
private static final Logger LOG = LoggerFactory.getLogger(BeanValidationStrategy.class);
/** expected return type of an attribute */
private Class<?> attributeType;
/**
* Constructor for the strategy
*
* @param attributeType
* expected return type of an attribute
*/
public BeanValidationStrategy(Class<?> attributeType) {
this.attributeType = attributeType;
}
/**
* It returns a {@link Calendar} objects complying with Java bean validation
* annotations.
*
* {@inheritDoc}
*/
public Object getValue(Class<?> attrType, List<Annotation> annotations) throws PodamMockeryException {
if (null != findTypeFromList(annotations, AssertTrue.class)) {
return Boolean.TRUE;
}
if (null != findTypeFromList(annotations, AssertFalse.class)) {
return Boolean.FALSE;
}
if (null != findTypeFromList(annotations, Past.class)) {
int days = PodamUtils.getIntegerInRange(1, 365);
long timestamp = System.currentTimeMillis() - TimeUnit.DAYS.toSeconds(days);
return timestampToReturnType(timestamp);
}
if (null != findTypeFromList(annotations, Future.class)) {
int days = PodamUtils.getIntegerInRange(1, 365);
long timestamp = System.currentTimeMillis() + TimeUnit.DAYS.toSeconds(days);
return timestampToReturnType(timestamp);
}
Size size = findTypeFromList(annotations, Size.class);
if (null != size) {
int minValue = size.min();
int maxValue = size.max();
if (minValue < 1 && maxValue > 0) {
minValue = 1;
}
if (maxValue == Integer.MAX_VALUE) {
maxValue = PodamConstants.STR_DEFAULT_LENGTH;
}
int length = PodamUtils.getIntegerInRange(minValue, maxValue);
StringBuilder sb = new StringBuilder(length);
while (sb.length() < length) {
sb.append(PodamUtils.getNiceCharacter());
}
return sb.toString();
}
Pattern pattern = findTypeFromList(annotations, Pattern.class);
if (null != pattern) {
LOG.warn("At the moment PODAM doesn't support @Pattern({}),"
+ " returning null", pattern.regexp());
return null;
}
boolean isRound = false;
boolean isFloat = false;
BigDecimal min;
BigDecimal max;
if (Long.class.equals(attributeType)
|| long.class.equals(attributeType)) {
min = new BigDecimal(Long.MIN_VALUE);
max = new BigDecimal(Long.MAX_VALUE);
} else if (Integer.class.equals(attributeType)
|| int.class.equals(attributeType)) {
min = new BigDecimal(Integer.MIN_VALUE);
max = new BigDecimal(Integer.MAX_VALUE);
} else if (Short.class.equals(attributeType)
|| short.class.equals(attributeType)) {
min = new BigDecimal(Short.MIN_VALUE);
max = new BigDecimal(Short.MAX_VALUE);
} else if (Byte.class.equals(attributeType)
|| byte.class.equals(attributeType)) {
min = new BigDecimal(Byte.MIN_VALUE);
max = new BigDecimal(Byte.MAX_VALUE);
} else {
min = new BigDecimal(-Double.MAX_VALUE);
max = new BigDecimal(Double.MAX_VALUE);
}
DecimalMin decimalMin = findTypeFromList(annotations, DecimalMin.class);
if (null != decimalMin) {
isFloat = true;
min = new BigDecimal(decimalMin.value());
}
DecimalMax decimalMax = findTypeFromList(annotations, DecimalMax.class);
if (null != decimalMax) {
isFloat = true;
max = new BigDecimal(decimalMax.value());
}
Min minAnno = findTypeFromList(annotations, Min.class);
if (null != minAnno) {
isRound = true;
min = new BigDecimal(minAnno.value()).max(min);
}
Max maxAnno = findTypeFromList(annotations, Max.class);
if (null != maxAnno) {
isRound = true;
max = new BigDecimal(maxAnno.value()).min(max);
}
Positive positiveAnno = findTypeFromList(annotations, Positive.class);
if (null != positiveAnno) {
isFloat = true;
max = new BigDecimal(Integer.MAX_VALUE);
min = new BigDecimal(1);
}
PositiveOrZero positiveOrZeroAnno = findTypeFromList(annotations, PositiveOrZero.class);
if (null != positiveOrZeroAnno) {
isFloat = true;
max = new BigDecimal(Integer.MAX_VALUE);
min = new BigDecimal(0);
}
Negative negativeAnno = findTypeFromList(annotations, Negative.class);
if (null != negativeAnno) {
isFloat = true;
max = new BigDecimal(-1);
min = new BigDecimal(Integer.MIN_VALUE);
}
NegativeOrZero negativeOrZeroAnno = findTypeFromList(annotations, NegativeOrZero.class);
if (null != negativeOrZeroAnno) {
isFloat = true;
max = new BigDecimal(0);
min = new BigDecimal(Integer.MIN_VALUE);
}
Digits digits = findTypeFromList(annotations, Digits.class);
BigDecimal divisor = null;
if (null != digits) {
isRound = true;
divisor = BigDecimal.TEN.pow(digits.fraction());
BigDecimal limit = BigDecimal.TEN.pow(digits.integer());
max = limit.min(max).multiply(divisor);
min = limit.negate().max(min).multiply(divisor);
}
if (isRound || isFloat) {
BigDecimal value = getValueInRange(min, max);
if (isRound) {
/* Integer part */
BigInteger intValue = value.toBigInteger();
value = new BigDecimal(intValue);
}
if (null != divisor) {
value = value.divide(divisor);
}
return decimalToReturnType(value);
}
return null;
}
/**
* Utility to find an item of a desired type in the given list
*
* @param <T>
* Return type of item to find
* @param list
* List to search in
* @param type
* Type to find in the list
* @return
* First element from the list of desired type
*/
public static <T> T findTypeFromList(List<?> list, Class<T> type) {
for (Object item : list) {
if (type.isAssignableFrom(item.getClass())) {
@SuppressWarnings("unchecked")
T found = (T)item;
return found;
}
}
return null;
}
/**
* Produces random decimal value within specified range
*
* @param min
* minimum value of range
* @param max
* maximum value of range
* @return
* decimal value in the specified range
*/
private BigDecimal getValueInRange(BigDecimal min, BigDecimal max) {
BigDecimal scale = new BigDecimal(PodamUtils.getDoubleInRange(0.0, 1.0));
return min.add(max.subtract(min).multiply(scale));
}
/**
* Converts intermediate decimal value to the actual attribute type,
* for example, string representation of this decimal
*
* @param result
* {@link BigDecimal} intermediate result to convert to the
* real attribute type
* @return actual attribute type object
*/
private Object decimalToReturnType(BigDecimal result) {
if (String.class.equals(attributeType)) {
return result.toPlainString();
} else if (Double.class.equals(attributeType)
|| double.class.equals(attributeType)) {
return result.doubleValue();
} else if (Float.class.equals(attributeType)
|| float.class.equals(attributeType)) {
return result.floatValue();
} else if (Long.class.equals(attributeType)
|| long.class.equals(attributeType)) {
return result.longValue();
} else if (Integer.class.equals(attributeType)
|| int.class.equals(attributeType)) {
return result.intValue();
} else if (Short.class.equals(attributeType)
|| short.class.equals(attributeType)) {
return result.shortValue();
} else if (Byte.class.equals(attributeType)
|| byte.class.equals(attributeType)) {
return result.byteValue();
} else if (attributeType.isAssignableFrom(BigDecimal.class)) {
return result;
} else if (attributeType.isAssignableFrom(BigInteger.class)) {
return result.toBigInteger();
} else {
LOG.warn("Unsupported attribute type {}", attributeType);
return null;
}
}
/**
* Converts intermediate long time stamp value to the actual attribute type,
* {@link java.util.Date} or {@link java.util.Calendar}
*
* @param result
* {@link Long} intermediate result to convert to the
* real attribute type
* @return actual attribute type object
*/
private Object timestampToReturnType(Long result) {
if (attributeType.isAssignableFrom(Date.class)) {
return new Date(result);
} else if (attributeType.isAssignableFrom(Calendar.class)) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(result);
return calendar;
} else {
LOG.warn("Unsupported attribute type {}", attributeType);
return null;
}
}
}
|
package com.yahoo.search.query.profile;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.query.profile.compiled.Binding;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.DimensionalMap;
import com.yahoo.search.query.profile.compiled.ValueWithSource;
import com.yahoo.search.query.profile.types.QueryProfileType;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Logger;
/**
* Compile a set of query profiles into compiled profiles.
*
* @author bratseth
*/
public class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents())
output.register(compile(inputProfile, output));
return output;
}
public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<ValueWithSource> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<Object> unoverridables = new DimensionalMap.Builder<>();
// Resolve values for each existing variant and combine into a single data structure
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty)); // if this contains no variants
log.fine(() -> "Compiling " + in + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
for (Map.Entry<String, ValueWithSource> entry : in.visitValues(variant.path(), variant.binding().getContext()).valuesWithSource().entrySet()) {
CompoundName fullName = variant.path().append(entry.getKey());
values.put(fullName, variant.binding(), entry.getValue());
if (entry.getValue().isUnoverridable())
unoverridables.put(fullName, variant.binding(), Boolean.TRUE);
if (entry.getValue().isQueryProfile())
references.put(fullName, variant.binding(), Boolean.TRUE);
if (entry.getValue().queryProfileType() != null)
types.put(fullName, variant.binding(), entry.getValue().queryProfileType());
}
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants)); // parents and children may have different variant dimensions
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, and resolving [a=a1,b=b1] would
* otherwise lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
PathTree trie = new PathTree();
for (var variant : variants)
trie.add(variant);
trie.forEachPrefix((prefixes, variantz) -> {
for (var prefix : prefixes)
if (hasWildcardBeforeEnd(prefix.binding))
for (var variant : variantz)
if ( ! variant.binding.isNull() && variant != prefix) {
DimensionBinding combined = prefix.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() )
expanded.add(new DimensionBindingForPath(combined, prefix.path()));
}
});
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) { // -1 to not check the rightmost
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v2.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
// Allow switching order since we're entering another profile
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue; // values at this point in the graph are unreachable
variants.add(new DimensionBindingForPath(combinedVariant, path));
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17 * path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
/**
* Simple trie for CompoundName paths.
*
* @author jonmv
*/
static class PathTree {
private final Node root = new Node(0);
void add(DimensionBindingForPath entry) {
root.add(entry);
}
void forEachPrefix(DimensionBindingForPath entry, Consumer<DimensionBindingForPath> action) {
root.visit(entry, action);
}
void forEachPrefix(BiConsumer<Collection<DimensionBindingForPath>, Collection<DimensionBindingForPath>> action) {
root.visit(new ArrayDeque<>(), action);
}
private static class Node {
private final int depth;
private final SortedMap<String, Node> children = new TreeMap<>();
private final List<DimensionBindingForPath> elements = new ArrayList<>();
private Node(int depth) {
this.depth = depth;
}
void visit(Deque<DimensionBindingForPath> prefixes, BiConsumer<Collection<DimensionBindingForPath>, Collection<DimensionBindingForPath>> action) {
prefixes.addAll(elements);
action.accept(prefixes, elements);
for (Node child : children.values())
child.visit(prefixes, action);
for (int i = 0; i < elements.size(); i++)
prefixes.removeLast();
}
void visit(DimensionBindingForPath entry, Consumer<DimensionBindingForPath> action) {
elements.forEach(action);
if (depth < entry.path().size() && children.containsKey(entry.path().get(depth)))
children.get(entry.path().get(depth)).visit(entry, action);
}
void add(DimensionBindingForPath entry) {
if (depth == entry.path().size())
elements.add(entry);
else
children.computeIfAbsent(entry.path().get(depth),
__ -> new Node(depth + 1)).add(entry);
}
}
}
}
|
package zmaster587.advancedRocketry.util;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import zmaster587.advancedRocketry.AdvancedRocketry;
import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks;
import zmaster587.advancedRocketry.api.AreaBlob;
import zmaster587.advancedRocketry.api.Configuration;
import zmaster587.advancedRocketry.api.util.IBlobHandler;
import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler;
import zmaster587.libVulpes.util.BlockPosition;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class AtmosphereBlob extends AreaBlob implements Runnable {
static ThreadPoolExecutor pool = (Configuration.atmosphereHandleBitMask & 1) == 1 ? new ThreadPoolExecutor(3, 16, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2)) : null;
boolean executing;
BlockPosition blockPos;
List<AreaBlob> nearbyBlobs;
public AtmosphereBlob(IBlobHandler blobHandler) {
super(blobHandler);
executing = false;
}
@Override
public void removeBlock(int x, int y, int z) {
BlockPosition blockPos = new BlockPosition(x, y, z);
graph.remove(blockPos);
graph.contains(blockPos);
for(ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {
BlockPosition newBlock = blockPos.getPositionAtOffset(direction.offsetX, direction.offsetY, direction.offsetZ);
if(graph.contains(newBlock) && !graph.doesPathExist(newBlock, blobHandler.getRootPosition()))
runEffectOnWorldBlocks(blobHandler.getWorld(), graph.removeAllNodesConnectedTo(newBlock));
}
}
@Override
public boolean isPositionAllowed(World world, BlockPosition pos, List<AreaBlob> otherBlobs) {
for(AreaBlob blob : otherBlobs) {
if(blob.contains(pos) && blob != this)
return false;
}
return !SealableBlockHandler.INSTANCE.isBlockSealed(world, pos);
}
@Override
public void addBlock(BlockPosition blockPos, List<AreaBlob> otherBlobs) {
if(blobHandler.canFormBlob()) {
if(!this.contains(blockPos) &&
(this.graph.size() == 0 || contains(blockPos.getPositionAtOffset(0, 1, 0)) || contains(blockPos.getPositionAtOffset(0, -1, 0)) ||
contains(blockPos.getPositionAtOffset(1, 0, 0)) || contains(blockPos.getPositionAtOffset(-1, 0, 0)) ||
contains(blockPos.getPositionAtOffset(0, 0, 1)) || contains(blockPos.getPositionAtOffset(0, 0, -1)))) {
if(!executing) {
this.nearbyBlobs = otherBlobs;
this.blockPos = blockPos;
executing = true;
if((Configuration.atmosphereHandleBitMask & 1) == 1)
try {
pool.execute(this);
} catch (RejectedExecutionException e) {
AdvancedRocketry.logger.warn("Atmosphere calculation at " + this.getRootPosition() + " aborted due to oversize queue!");
}
else
this.run();
}
}
}
}
@Override
public void run() {
Stack<BlockPosition> stack = new Stack<BlockPosition>();
stack.push(blockPos);
final int maxSize = (Configuration.atmosphereHandleBitMask & 2) != 0 ? (int)(Math.pow(this.getBlobMaxRadius(), 3)*((4f/3f)*Math.PI)) : this.getBlobMaxRadius();
final HashSet<BlockPosition> addableBlocks = new HashSet<BlockPosition>();
//Breadth first search; non recursive
while(!stack.isEmpty()) {
BlockPosition stackElement = stack.pop();
addableBlocks.add(stackElement);
for(ForgeDirection dir2 : ForgeDirection.VALID_DIRECTIONS) {
BlockPosition searchNextPosition = stackElement.getPositionAtOffset(dir2.offsetX, dir2.offsetY, dir2.offsetZ);
//Don't path areas we have already scanned
if(!graph.contains(searchNextPosition) && !addableBlocks.contains(searchNextPosition)) {
boolean sealed;
try {
sealed = !isPositionAllowed(blobHandler.getWorld(), searchNextPosition, nearbyBlobs);//SealableBlockHandler.INSTANCE.isBlockSealed(blobHandler.getWorld(), searchNextPosition);
if(!sealed) {
if(((Configuration.atmosphereHandleBitMask & 2) == 0 && searchNextPosition.getDistance(this.getRootPosition()) <= maxSize) ||
((Configuration.atmosphereHandleBitMask & 2) != 0 && addableBlocks.size() <= maxSize)) {
stack.push(searchNextPosition);
addableBlocks.add(searchNextPosition);
}
else {
//Failed to seal, void
clearBlob();
executing = false;
return;
}
}
} catch (Exception e){
//Catches errors with additional information
AdvancedRocketry.logger.info("Error: AtmosphereBlob has failed to form correctly due to an error. \nCurrentBlock: " + stackElement + "\tNextPos: " + searchNextPosition + "\tDir: " + dir2 + "\tStackSize: " + stack.size());
e.printStackTrace();
//Failed to seal, void
clearBlob();
executing = false;
return;
}
}
}
}
//only one instance can editing this at a time because this will not run again b/c "worker" is not null
synchronized(graph) {
for(BlockPosition blockPos2 : addableBlocks) {
super.addBlock(blockPos2, nearbyBlobs);
}
}
executing = false;
}
/**
* @param world
* @param blocks Collection containing affected locations
*/
protected void runEffectOnWorldBlocks(World world, Collection<BlockPosition> blocks) {
if(!AtmosphereHandler.getOxygenHandler(world.provider.dimensionId).getDefaultAtmosphereType().allowsCombustion()) {
List<BlockPosition> list;
synchronized (graph) {
list = new LinkedList<BlockPosition>(blocks);
}
for(BlockPosition pos : list) {
Block block = world.getBlock(pos.x, pos.y, pos.z);
if(block== Blocks.torch) {
world.setBlock(pos.x, pos.y, pos.z, AdvancedRocketryBlocks.blockUnlitTorch);
}
else if(Configuration.torchBlocks.contains(block)) {
EntityItem item = new EntityItem(world, pos.x, pos.y, pos.z, new ItemStack(block));
world.setBlockToAir(pos.x, pos.y, pos.z);
world.spawnEntityInWorld(item);
}
}
}
}
@Override
public void clearBlob() {
World world = blobHandler.getWorld();
runEffectOnWorldBlocks(world, getLocations());
super.clearBlob();
}
public int getPressure() {
return 100;
}
}
|
package com.bottlerocketstudios.continuitysample.legislator.ui;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableList;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bottlerocketstudios.continuitysample.R;
import com.bottlerocketstudios.continuitysample.core.model.ResponseStatus;
import com.bottlerocketstudios.continuitysample.core.ui.BaseFragment;
import com.bottlerocketstudios.continuitysample.core.ui.LocationActivity;
import com.bottlerocketstudios.continuitysample.core.ui.ResponseStatusTranslator;
import com.bottlerocketstudios.continuitysample.core.ui.dialog.SampleDialogFragment;
import com.bottlerocketstudios.continuitysample.databinding.LegislatorSearchResultFragmentBinding;
import com.bottlerocketstudios.continuitysample.legislator.presenter.LegislatorSearchResultPresenter;
import com.bottlerocketstudios.continuitysample.legislator.viewmodel.LegislatorSearchResultViewModel;
import com.bottlerocketstudios.continuitysample.legislator.viewmodel.LegislatorViewModel;
public class LegislatorSearchResultFragment extends BaseFragment {
private static final int REQUEST_CODE_PERMISSION = 1;
private static final String ARG_SEARCH_QUERY = "searchQuery";
private static final String ARG_SEARCH_MODE = "searchMode";
//So many things can go wrong with a location.
private static final String DIALOG_TAG_ERROR = "errorDialog";
private static final int DIALOG_ID_PERMANENT_PERMISSION_FAILURE = 1;
private static final int DIALOG_ID_TEMPORARY_PERMISSION_FAILURE = 2;
private static final int DIALOG_ID_LOCATION_SETTING_FAILURE = 3;
private static final int DIALOG_ID_PLAY_SERVICES_FAILURE = 4;
private static final int DIALOG_ID_PERMISSION_RATIONALE = 5;
private static final int DIALOG_ID_NETWORK_ERROR = 6;
private LegislatorSearchResultFragmentBinding mFragmentBinding;
private LegislatorSearchResultPresenter mLegislatorSearchResultPresenter;
private LegislatorSearchRecyclerAdapter mLegislatorSearchRecyclerAdapter;
private LinearLayoutManager mResultLayoutManager;
private Listener mFragmentListener;
public static LegislatorSearchResultFragment newZipSearchInstance(String zipCode) {
LegislatorSearchResultFragment fragment = new LegislatorSearchResultFragment();
Bundle args = new Bundle();
args.putString(ARG_SEARCH_QUERY, zipCode);
args.putSerializable(ARG_SEARCH_MODE, LegislatorSearchResultPresenter.SearchMode.ZIP_CODE);
fragment.setArguments(args);
return fragment;
}
public static LegislatorSearchResultFragment newNameSearchInstance(String name) {
LegislatorSearchResultFragment fragment = new LegislatorSearchResultFragment();
Bundle args = new Bundle();
args.putString(ARG_SEARCH_QUERY, name);
args.putSerializable(ARG_SEARCH_MODE, LegislatorSearchResultPresenter.SearchMode.NAME);
fragment.setArguments(args);
return fragment;
}
public static LegislatorSearchResultFragment newLocalSearchInstance() {
LegislatorSearchResultFragment fragment = new LegislatorSearchResultFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_SEARCH_MODE, LegislatorSearchResultPresenter.SearchMode.LOCATION);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
//Create or retrieve the presenter
mLegislatorSearchResultPresenter = getPresenterRepository().with(this, LegislatorSearchResultPresenter.class).build();
//This has to be hosted by a special LocationActivity for Google Play Services plumbing so
//hand that to the presenter.
LocationActivity locationActivity = activityCastOrThrow(context, LocationActivity.class);
mLegislatorSearchResultPresenter.setLocationActivity(locationActivity);
mFragmentListener = activityCastOrThrow(context, Listener.class);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.legislator_search_result_fragment, container, false);
mFragmentBinding.setPresenter(mLegislatorSearchResultPresenter);
mResultLayoutManager = new LinearLayoutManager(getContext());
mFragmentBinding.lsrfRecyclerView.setLayoutManager(mResultLayoutManager);
mLegislatorSearchRecyclerAdapter = new LegislatorSearchRecyclerAdapter();
mLegislatorSearchRecyclerAdapter.setPresenter(mLegislatorSearchResultPresenter);
mFragmentBinding.lsrfRecyclerView.setAdapter(mLegislatorSearchRecyclerAdapter);
mLegislatorSearchResultPresenter.bindListener(mPresenterListener);
return mFragmentBinding.getRoot();
}
@Override
public void onResume() {
super.onResume();
mLegislatorSearchResultPresenter.onResume((LegislatorSearchResultPresenter.SearchMode) getArguments().getSerializable(ARG_SEARCH_MODE), getArguments().getString(ARG_SEARCH_QUERY, null));
}
private LegislatorSearchResultPresenter.Listener mPresenterListener = new LegislatorSearchResultPresenter.Listener() {
@Override
public void bindLegislatorSearchViewModel(LegislatorSearchResultViewModel legislatorSearchResultViewModel) {
mFragmentBinding.setLegislatorSearchViewModel(legislatorSearchResultViewModel);
}
@Override
public void bindLegislatorList(ObservableList<LegislatorViewModel> legislatorList) {
mLegislatorSearchRecyclerAdapter.swapList(legislatorList);
}
@Override
public boolean hasPermission(String permission) {
return PermissionChecker.checkSelfPermission(getContext(), permission) == PermissionChecker.PERMISSION_GRANTED;
}
@Override
public boolean shouldShowPermissionRationale(String permission) {
return LegislatorSearchResultFragment.this.shouldShowRequestPermissionRationale(permission);
}
@Override
public void showPermissionRationale(String permission) {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_PERMISSION_RATIONALE)
.setTitle(getString(R.string.lsrf_location_permission_title))
.setMessage(getString(R.string.lsrf_permission_rationale))
.setPositiveText(getString(R.string.ok))
.setNegativeText(getString(R.string.cancel))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
mLegislatorSearchResultPresenter.permissionRationaleAgreed();
break;
default:
mFragmentListener.closeSearchResults();
break;
}
}
})
.build()
.show(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void requestPermission(String permission) {
LegislatorSearchResultFragment.this.requestPermissions(new String[]{permission}, REQUEST_CODE_PERMISSION);
}
@Override
public void onPermanentLocationPermissionFailure() {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_PERMANENT_PERMISSION_FAILURE)
.setTitle(getString(R.string.lsrf_location_permission_title))
.setMessage(getString(R.string.lsrf_permanent_location_permission_failure))
.setPositiveText(getString(R.string.ok))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFragmentListener.closeSearchResults();
}
})
.build()
.postShow(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void onTemporaryLocationPermissionFailure() {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_TEMPORARY_PERMISSION_FAILURE)
.setTitle(getString(R.string.lsrf_location_permission_title))
.setMessage(getString(R.string.lsrf_temporary_location_permission_failure))
.setPositiveText(getString(R.string.ok))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFragmentListener.closeSearchResults();
}
})
.build()
.postShow(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void onLocationSettingFailure() {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_LOCATION_SETTING_FAILURE)
.setTitle(getString(R.string.lsrf_location_setting_failure_title))
.setMessage(getString(R.string.lsrf_location_setting_failure))
.setPositiveText(getString(R.string.ok))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFragmentListener.closeSearchResults();
}
})
.build()
.postShow(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void onPermanentGooglePlayServicesFailure() {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_PLAY_SERVICES_FAILURE)
.setTitle(getString(R.string.lsrf_play_services_failure_title))
.setMessage(getString(R.string.lsrf_play_services_failure))
.setPositiveText(getString(R.string.ok))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFragmentListener.closeSearchResults();
}
})
.build()
.show(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void showNetworkError(ResponseStatus responseStatus) {
new SampleDialogFragment.Builder()
.setDialogId(DIALOG_ID_NETWORK_ERROR)
.setTitle(getString(R.string.dialog_error_title))
.setMessage(ResponseStatusTranslator.getErrorString(getContext(), responseStatus))
.setPositiveText(getString(R.string.ok))
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mFragmentListener.closeSearchResults();
}
})
.build()
.show(getChildFragmentManager(), DIALOG_TAG_ERROR);
}
@Override
public void launchLegislatorDetail(View photo, LegislatorViewModel legislatorViewModel) {
Intent intent = LegislatorDetailActivity.newIntent(getActivity(), legislatorViewModel);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(getActivity(), photo, getString(R.string.transition_legislator_detail));
Bundle optionsBundle = options.toBundle();
startActivity(intent, optionsBundle);
} else {
startActivity(intent);
}
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION) {
mLegislatorSearchResultPresenter.handlePermissionResult(permissions, grantResults);
}
}
public interface Listener {
void closeSearchResults();
}
}
|
package org.chromium.content.browser;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.widget.FrameLayout;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.ui.base.WindowAndroid;
/***
* This view is used by a ContentView to render its content.
* Call {@link #setCurrentContentViewCore(ContentViewCore)} with the contentViewCore that should be
* managing the view.
* Note that only one ContentViewCore can be shown at a time.
*/
@JNINamespace("content")
public class ContentViewRenderView extends FrameLayout {
// The native side of this object.
private long mNativeContentViewRenderView;
private SurfaceHolder.Callback mSurfaceCallback;
private final SurfaceView mSurfaceView;
protected ContentViewCore mContentViewCore;
// Enum for the type of compositing surface:
// SURFACE_VIEW - Use SurfaceView as compositing surface which
// has a bit performance advantage
// TEXTURE_VIEW - Use TextureView as compositing surface which
// supports animation on the View
public enum CompositingSurfaceType { SURFACE_VIEW, TEXTURE_VIEW };
// The stuff for TextureView usage. It is not a good practice to mix 2 different
// implementations into one single class. However, for the sake of reducing the
// effort of rebasing maintanence in future, here we avoid heavily changes in
// this class.
private TextureView mTextureView;
private Surface mSurface;
private CompositingSurfaceType mCompositingSurfaceType;
private ContentReadbackHandler mContentReadbackHandler;
// The listener which will be triggered when below two conditions become valid.
// 1. The view has been initialized and ready to draw content to the screen.
// 2. The compositor finished compositing and the OpenGL buffers has been swapped.
// Which means the view has been updated with visually non-empty content.
// This listener will be triggered only once after registered.
private FirstRenderedFrameListener mFirstRenderedFrameListener;
private boolean mFirstFrameReceived;
public interface FirstRenderedFrameListener{
public void onFirstFrameReceived();
}
// Initialize the TextureView for rendering ContentView and configure the callback
// listeners.
private void initTextureView(Context context) {
mTextureView = new TextureView(context);
mTextureView.setBackgroundColor(Color.WHITE);
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0;
mSurface = new Surface(surfaceTexture);
nativeSurfaceCreated(mNativeContentViewRenderView);
// Force to trigger the compositor to start working.
onSurfaceTextureSizeChanged(surfaceTexture, width, height);
onReadyToRender();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0 && mSurface != null;
assert surfaceTexture == mTextureView.getSurfaceTexture();
assert mSurface != null;
// Here we hard-code the pixel format since the native part requires
// the format parameter to decide if the compositing surface should be
// replaced with a new one when the format is changed.
// If TextureView is used, the surface won't be possible to changed,
// so that the format is also not changed. There is no special reason
// to use RGBA_8888 value since the native part won't use its real
// value to do something for drawing.
// TODO(hmin): Figure out how to get pixel format from SurfaceTexture.
int format = PixelFormat.RGBA_8888;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, mSurface);
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
// Release the underlying surface to make it invalid.
mSurface.release();
mSurface = null;
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
// Do nothing since the SurfaceTexture won't be updated via updateTexImage().
}
});
}
public ContentViewRenderView(Context context) {
this(context, CompositingSurfaceType.SURFACE_VIEW);
}
/**
* Constructs a new ContentViewRenderView.
* This should be called and the {@link ContentViewRenderView} should be added to the view
* hierarchy before the first draw to avoid a black flash that is seen every time a
* {@link SurfaceView} is added.
* @param context The context used to create this.
* @param surfaceType TextureView is used as compositing target surface,
* otherwise SurfaceView is used.
*/
public ContentViewRenderView(Context context, CompositingSurfaceType surfaceType) {
super(context);
mCompositingSurfaceType = surfaceType;
if (surfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
initTextureView(context);
addView(mTextureView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// Avoid compiler warning.
mSurfaceView = null;
mSurfaceCallback = null;
return;
}
mSurfaceView = createSurfaceView(getContext());
mSurfaceView.setZOrderMediaOverlay(true);
setSurfaceViewBackgroundColor(Color.WHITE);
addView(mSurfaceView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mSurfaceView.setVisibility(GONE);
}
/**
* Initialization that requires native libraries should be done here.
* Native code should add/remove the layers to be rendered through the ContentViewLayerRenderer.
* @param rootWindow The {@link WindowAndroid} this render view should be linked to.
*/
public void onNativeLibraryLoaded(WindowAndroid rootWindow) {
assert rootWindow != null;
mNativeContentViewRenderView = nativeInit(rootWindow.getNativePointer());
assert mNativeContentViewRenderView != 0;
mContentReadbackHandler = new ContentReadbackHandler() {
@Override
protected boolean readyForReadback() {
return mNativeContentViewRenderView != 0 && mContentViewCore != null;
}
};
mContentReadbackHandler.initNativeContentReadbackHandler();
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW)
return;
assert !mSurfaceView.getHolder().getSurface().isValid() :
"Surface created before native library loaded.";
mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, holder.getSurface());
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceCreated(mNativeContentViewRenderView);
onReadyToRender();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
}
};
mSurfaceView.getHolder().addCallback(mSurfaceCallback);
mSurfaceView.setVisibility(VISIBLE);
}
/**
* @return The content readback handler.
*/
public ContentReadbackHandler getContentReadbackHandler() {
return mContentReadbackHandler;
}
/**
* Sets the background color of the surface view. This method is necessary because the
* background color of ContentViewRenderView itself is covered by the background of
* SurfaceView.
* @param color The color of the background.
*/
public void setSurfaceViewBackgroundColor(int color) {
if (mSurfaceView != null) {
mSurfaceView.setBackgroundColor(color);
}
}
/**
* Gets the SurfaceView for this ContentViewRenderView
*/
public SurfaceView getSurfaceView() {
return mSurfaceView;
}
/**
* Should be called when the ContentViewRenderView is not needed anymore so its associated
* native resource can be freed.
*/
public void destroy() {
mContentReadbackHandler.destroy();
mContentReadbackHandler = null;
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
mTextureView.setSurfaceTextureListener(null);
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
} else {
mSurfaceView.getHolder().removeCallback(mSurfaceCallback);
}
nativeDestroy(mNativeContentViewRenderView);
mNativeContentViewRenderView = 0;
}
public void setCurrentContentViewCore(ContentViewCore contentViewCore) {
assert mNativeContentViewRenderView != 0;
mContentViewCore = contentViewCore;
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(getWidth(), getHeight());
nativeSetCurrentContentViewCore(mNativeContentViewRenderView,
mContentViewCore.getNativeContentViewCore());
} else {
nativeSetCurrentContentViewCore(mNativeContentViewRenderView, 0);
}
}
/**
* Trigger a redraw of the compositor. This is only needed if the UI changes something that
* does not trigger a redraw itself by updating the layer tree.
*/
public void setNeedsComposite() {
if (mNativeContentViewRenderView == 0) return;
nativeSetNeedsComposite(mNativeContentViewRenderView);
}
/**
* This method should be subclassed to provide actions to be performed once the view is ready to
* render.
*/
protected void onReadyToRender() {
}
/**
* This method could be subclassed optionally to provide a custom SurfaceView object to
* this ContentViewRenderView.
* @param context The context used to create the SurfaceView object.
* @return The created SurfaceView object.
*/
protected SurfaceView createSurfaceView(Context context) {
return new SurfaceView(context);
}
public void registerFirstRenderedFrameListener(FirstRenderedFrameListener listener) {
mFirstRenderedFrameListener = listener;
if (mFirstFrameReceived && mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
/**
* @return whether the surface view is initialized and ready to render.
*/
public boolean isInitialized() {
return mSurfaceView.getHolder().getSurface() != null || mSurface != null;
}
/**
* Enter or leave overlay video mode.
* @param enabled Whether overlay mode is enabled.
*/
public void setOverlayVideoMode(boolean enabled) {
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
return;
}
int format = enabled ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
mSurfaceView.getHolder().setFormat(format);
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
}
@CalledByNative
protected void onCompositorLayout() {
}
@CalledByNative
private void onSwapBuffersCompleted() {
if (!mFirstFrameReceived && mContentViewCore != null && mContentViewCore.getWebContents().isReady()) {
mFirstFrameReceived = true;
if (mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
// Ignore if TextureView is used.
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) return;
if (mSurfaceView.getBackground() != null) {
post(new Runnable() {
@Override public void run() {
mSurfaceView.setBackgroundResource(0);
}
});
}
}
/**
* @return Native pointer for the UI resource provider taken from the compositor.
*/
public long getUIResourceProvider() {
return nativeGetUIResourceProvider(mNativeContentViewRenderView);
}
private native long nativeInit(long rootWindowNativePointer);
private native long nativeGetUIResourceProvider(long nativeContentViewRenderView);
private native void nativeDestroy(long nativeContentViewRenderView);
private native void nativeSetCurrentContentViewCore(long nativeContentViewRenderView,
long nativeContentViewCore);
private native void nativeSurfaceCreated(long nativeContentViewRenderView);
private native void nativeSurfaceDestroyed(long nativeContentViewRenderView);
private native void nativeSurfaceChanged(long nativeContentViewRenderView,
int format, int width, int height, Surface surface);
private native void nativeSetOverlayVideoMode(long nativeContentViewRenderView,
boolean enabled);
private native void nativeSetNeedsComposite(long nativeContentViewRenderView);
}
|
package scalac.transformer;
import java.io.*;
import java.util.HashMap;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import Tree.*;
/** A lambda lifting transformer
*
* @author Martin Odersky
* @version 1.0
*
* What it does:
* Lift every class and function that's contained in another function
* out to be a member to the next enclosing class.
* Pass free variables and type variables as parameters to class constructors.
* Variables and values that are free in some function or class
* are given new unique names.
* Free mutable variables are converted to reference cells.
* All types are updated so that proxies are passed for additional free
* type variables.
*/
public class LambdaLift extends OwnerTransformer
implements Modifiers, Kinds {
final Global global;
final Definitions definitions;
final FreeVars free;
final LambdaLiftPhase descr;
private Unit unit;
public LambdaLift(Global global, LambdaLiftPhase descr) {
super(global);
this.global = global;
this.definitions = global.definitions;
this.free = new FreeVars(global);
this.descr = descr;
}
public void apply(Unit unit) {
this.unit = unit;
global.log(unit.source.toString());
free.initialize(unit);
currentOwner = global.definitions.ROOT_CLASS;
unit.body = transformTemplateStats(unit.body, currentOwner);
}
/** If `sym' is a class, return its primary constructor;
* otherwise current symbol itself
*/
static Symbol asFunction(Symbol sym) {
return sym.kind == CLASS ? sym.primaryConstructor() : sym;
}
/** Is symbol local relative to owner?
* Primary constructor parameters are local iff owner (contained in)
* the primary constructor.
*/
static boolean isLocal(Symbol sym, Symbol owner) {
if ((sym.flags & PARAM) != 0 &&
sym.owner().isPrimaryConstructor() &&
sym.owner().constructorClass().kind == CLASS &&
!((owner.flags & PARAM) != 0 && owner.owner() == sym)) {
Symbol encl = sym.owner().owner();
Symbol clazz = sym.owner().constructorClass();
//System.out.println("isLocal " + sym + " " + encl + " " + clazz + " " + owner);//DEBUG
while (owner != encl &&
owner.kind != NONE &&
owner != clazz) {
owner = owner.owner();
//System.out.println(":" + owner);//DEBUG
}
return owner != clazz;
}
return sym.isLocal();
}
/** Propagate free fariables from all called functions. /** `asFunction' applied to the next enclosing function or class owner.
*/
static Symbol enclFun(Symbol owner) {
Symbol sym = owner;
while (!asFunction(sym).isMethod()) sym = sym.owner();
return asFunction(sym);
}
/** Return SymSet from a hashmap.
*/
private static SymSet get(HashMap f, Symbol sym) {
SymSet ss = (SymSet) f.get(sym);
return ss == null ? SymSet.EMPTY : ss;
}
/** Compute free variables map `fvs'.
* Also assign unique names to all
* value/variable/let symbols that are free in some function or class, and to
* all class/function symbols that are owned by some function.
*/
static class FreeVars extends OwnerTransformer {
private Unit unit;
public FreeVars(Global global) {
super(global);
}
/** A hashtable storing free variables of functions and class constructors.
*/
private HashMap/*<Symbol,SymSet>*/ fvs;
/** A hashtable storing free type variables of functions and class constructors.
*/
private HashMap/*<Symbol,SymSet>*/ ftvs;
/** A hashtable storing calls between functions and class constructors
*/
private HashMap/*<Symbol,SymSet>*/ called;
/** The set of symbols that need to be renamed.
*/
private SymSet renamable;
/** The set of symbols that bound by polytypes
* and therefore are not free type variables.
*/
private SymSet excluded;
/** A flag to indicate whether new free variables have been found
*/
private boolean changedFreeVars;
/** A flag to indicate whether we are in propagation phase
* (used in assertion).
*/
private boolean propagatePhase;
/** Insert `sym' into the set of free variables of `owner'
*/
private void putFree(Symbol owner, Symbol sym) {
assert owner.isLocal();
HashMap f = sym.isType() ? ftvs : fvs;
SymSet ss = get(f, owner);
if (!ss.contains(sym)) {
f.put(owner, ss.incl(sym));
changedFreeVars = true;
if (global.debug) global.log(sym + " is free in " + owner);
}
}
/** Insert `to' into the set of functions called by `from'
*/
private void putCall(Symbol from, Symbol to) {
SymSet ss = get(called, from);
if (!ss.contains(to)) {
called.put(from, ss.incl(to));
}
}
/** Mark symbol `sym' as being free in `owner', unless `sym'
* is defined in `owner' or there is a class between `owner's owner
* and the owner of `sym'.
* Return `true' if there is no class between `owner' and
* the owner of sym.
*/
private boolean markFree(Symbol sym, Symbol owner) {
if (global.debug) global.log("mark " + sym + " of " + sym.owner() + " free in " + owner);//debug
if (owner.kind == NONE) {
assert propagatePhase : sym + " in " + sym.owner();
return false;
} else if (sym.owner() == owner) {
return true;
} else if (markFree(sym, owner.owner())) {
Symbol fowner = asFunction(owner);
if (fowner.isMethod()) {
putFree(fowner, sym);
renamable = renamable.incl(sym);
if (sym.isVariable()) sym.flags |= CAPTURED;
}
return owner.kind != CLASS;
} else {
return false;
}
}
/** Assign unique name to symbol.
* If symbol is a class assign same name to its primary constructor.
*/
private void makeUnique(Symbol sym) {
sym.name = global.freshNameCreator.newName(sym.name);
}
private Type.Map traverseTypeMap = new Type.Map() {
public Type apply(Type tp) {
if (global.debug) global.log("traverse " + tp);//debug
switch (tp) {
case TypeRef(ThisType(_), Symbol sym, Type[] targs):
if (isLocal(sym, currentOwner) &&
sym.kind == TYPE &&
!excluded.contains(sym))
markFree(sym, currentOwner);
break;
case PolyType(Symbol[] tparams, Type restp):
for (int i = 0; i < tparams.length; i++)
excluded = excluded.incl(tparams[i]);
Type tp1 = super.map(tp);
for (int i = 0; i < tparams.length; i++)
excluded = excluded.excl(tparams[i]);
return tp1;
}
return map(tp);
}
};
public Tree transform(Tree tree) {
if (global.debug) global.log("free " + tree);//debug
assert tree.type != null : tree;
traverseTypeMap.apply(tree.type.widen());
Symbol sym = tree.symbol();
switch(tree) {
case ClassDef(_, _, _, _, _, _):
case DefDef(_, _, _, _, _, _):
if (sym.isLocal()) {
renamable = renamable.incl(sym);
}
return super.transform(tree);
case AbsTypeDef(int mods, Name name, Tree rhs, Tree lobound):
// ignore type definition as owner.
// reason: it might be in a refinement
// todo: handle type parameters?
return copy.AbsTypeDef(
tree, sym,
transform(rhs, currentOwner),
transform(lobound, currentOwner));
case AliasTypeDef(int mods, Name name, AbsTypeDef[] tparams, Tree rhs):
// ignore type definition as owner.
// reason: it might be in a refinement
// todo: handle type parameters?
return copy.AliasTypeDef(
tree, sym,
transform(tparams, currentOwner),
transform(rhs, currentOwner));
case Ident(_):
if (isLocal(sym, currentOwner)) {
if (sym.isMethod()) {
Symbol f = enclFun(currentOwner);
if (f.name.length() > 0) // it is not a template function {
putCall(f, sym);
} else if (sym.kind == VAL || sym.kind == TYPE) {
markFree(sym, currentOwner);
}
}
return tree;
default:
return super.transform(tree);
}
}
/** Propagate free fariables from all called functions.
*/
void propagateFvs(HashMap fvs) {
Object[] fs = called.keySet().toArray();
for (int i = 0; i < fs.length; i++) {
Symbol f = (Symbol) fs[i];
Symbol[] calledFromF = get(called, f).toArray();
for (int j = 0; j < calledFromF.length; j++) {
//System.out.println(f + " calls " + calledFromF[j]);//DEBUG
Symbol[] newFvs = get(fvs, calledFromF[j]).toArray();
for (int k = 0; k < newFvs.length; k++) {
markFree(newFvs[k], f);
}
}
}
}
/** This method re-enters all free variables into their free variable sets
* This is necessary because the names of these variables (and therefore their
* `isLess' order have changed.
*/
void restoreFvs(HashMap fvs) {
Object[] fs = fvs.keySet().toArray();
for (int i = 0; i < fs.length; i++) {
Symbol f = (Symbol) fs[i];
Symbol[] elems = get(fvs, f).toArray();
SymSet elems1 = SymSet.EMPTY;
for (int j = 0; j < elems.length; j++)
elems1 = elems1.incl(elems[j]);
fvs.put(f, elems1);
}
}
/** Compute a mapping from symbols to their free variables
* in hashtable `fvs'. Also rename all variables that need it.
*/
public void initialize(Unit unit) {
this.unit = unit;
fvs = new HashMap();
ftvs = new HashMap();
called = new HashMap();
renamable = SymSet.EMPTY;
excluded = SymSet.EMPTY;
apply(unit);
propagatePhase = true;
do {
changedFreeVars = false;
propagateFvs(fvs);
propagateFvs(ftvs);
} while (changedFreeVars);
Symbol[] ss = renamable.toArray();
for (int i = 0; i < ss.length; i++) {
makeUnique(ss[i]);
}
restoreFvs(fvs);
restoreFvs(ftvs);
}
}
private TreeList liftedDefs;
/** Transform template and add lifted definitions to it.
*/
public Tree[] transformTemplateStats(Tree[] stats, Symbol tsym) {
TreeList prevLiftedDefs = liftedDefs;
liftedDefs = new TreeList();
TreeList stats1 = new TreeList(super.transformTemplateStats(stats, tsym));
stats1.append(liftedDefs);
liftedDefs = prevLiftedDefs;
return stats1.toArray();
}
public Tree transform(Tree tree) {
//global.debugPrinter.print("lifting ").print(tree).println().end();//DEBUG
//System.out.print(tree.type + " --> ");//DEBUG
tree.type = descr.transform(tree.type, currentOwner);
//System.out.println(tree.type);//DEBUG
switch (tree) {
case Block(Tree[] stats):
for (int i = 0; i < stats.length; i++)
liftSymbol(stats[i]);
return copy.Block(tree, transform(stats));
case ClassDef(int mods, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Template impl):
Symbol sym = tree.symbol();
if ((mods & LIFTED) != 0) {
((ClassDef) tree).mods &= ~LIFTED;
Tree tree1 = copy.ClassDef(
tree, sym,
addTypeParams(transform(tparams, sym), newtparams(sym.primaryConstructor())),
new ValDef[][]{
addParams(transform(vparams, sym)[0], newparams(sym.primaryConstructor()))},
transform(tpe, sym),
transform(impl, sym));
liftedDefs.append(tree1);
return Tree.Empty;
} else {
assert !sym.isLocal() : sym;
return copy.ClassDef(
tree, sym,
transform(tparams, sym),
transform(vparams, sym),
transform(tpe, sym),
transform(impl, sym));
}
case DefDef(int mods, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Tree rhs):
Symbol sym = tree.symbol();
if ((mods & LIFTED) != 0) {
((DefDef) tree).mods &= ~LIFTED;
Tree tree1 = copy.DefDef(
tree, sym,
addTypeParams(transform(tparams, sym), newtparams(sym)),
new ValDef[][]{
addParams(transform(vparams, sym)[0], newparams(sym))},
transform(tpe, sym),
transform(rhs, sym));
liftedDefs.append(tree1);
return Tree.Empty;
} else {
assert !sym.isLocal() : sym;
return copy.DefDef(
tree, sym,
transform(tparams, sym), transform(vparams, sym), transform(tpe, sym),
transform(rhs, sym));
}
case AbsTypeDef(int mods, Name name, Tree rhs, Tree lobound):
// ignore type definition as owner.
// reason: it might be in a refinement
// todo: handle type parameters?
return copy.AbsTypeDef(
tree, tree.symbol(),
transform(rhs, currentOwner),
transform(lobound, currentOwner));
case AliasTypeDef(int mods, Name name, AbsTypeDef[] tparams, Tree rhs):
// ignore type definition as owner.
// reason: it might be in a refinement
// todo: handle type parameters?
return copy.AliasTypeDef(
tree, tree.symbol(),
transform(tparams, currentOwner),
transform(rhs, currentOwner));
case ValDef(_, _, Tree tpe, Tree rhs):
Symbol sym = tree.symbol();
Tree tpe1 = transform(tpe);
Tree rhs1 = transform(rhs, sym);
if ((sym.flags & CAPTURED) != 0) {
assert sym.isLocal();
Type boxedType = sym.nextType();
tpe1 = gen.mkType(tpe.pos, boxedType);
rhs1 = gen.New(
gen.mkPrimaryConstr(rhs.pos, boxedType, new Tree[]{rhs1}));
}
return copy.ValDef(tree, sym, tpe1, rhs1);
case Sequence(Tree[] args):
Tree tree1 = mkList(tree.pos, tree.type, transform(args));
//new scalac.ast.printer.TextTreePrinter().print("TUPLE: ").print(tree).print("\n ==> \n").print(tree1).println().end();//DEBUG
return tree1;
case Return(Tree expr):
if (tree.symbol() != currentOwner.enclMethod()) {
unit.error(tree.pos, "non-local return not yet implemented");
}
return super.transform(tree);
case Apply(Tree fn, Tree[] args):
Symbol fsym = TreeInfo.methSymbol(fn);
Tree fn1 = transform(fn);
switch (fn1) {
case TypeApply(Tree fn2, Tree[] targs):
fn1 = copy.TypeApply(
fn1, fn2, addFreeArgs(tree.pos, get(free.ftvs, fsym), targs, true));
break;
default:
Tree[] targs = addFreeArgs(
tree.pos, get(free.ftvs, fsym), Tree.EMPTY_ARRAY, true);
if (targs.length > 0)
fn1 = gen.TypeApply(fn1, targs);
}
Tree[] args1 = transform(args);
return copy.Apply(
tree, fn1, addFreeArgs(tree.pos, get(free.fvs, fsym), args1, false));
case Ident(Name name):
Symbol sym = tree.symbol();
if (isLocal(sym, currentOwner) &&
(sym.kind == TYPE || (sym.kind == VAL && !sym.isMethod()))) {
sym = descr.proxy(sym, currentOwner);
}
Tree tree1 = (sym.owner().kind == CLASS)
? gen.mkRef(tree.pos, sym)
: copy.Ident(tree, sym).setType(sym.nextType());
if (name != sym.name) {
if (tree1 instanceof Ident) ((Ident)tree1).name = sym.name;
else ((Select)tree1).selector = sym.name;
}
if ((sym.flags & CAPTURED) != 0) return gen.Select(tree1, definitions.REF_ELEM());
else return tree1;
default:
return super.transform(tree);
}
}
Symbol[] ftvsParams(Symbol owner) {
Symbol[] freevars = get(free.ftvs, owner).toArray();
Symbol[] params = new Symbol[freevars.length];
for (int i = 0; i < params.length; i++) {
params[i] = freevars[i].cloneSymbol(owner);
params[i].pos = owner.pos;
params[i].flags = PARAM | SYNTHETIC;
}
for (int i = 0; i < params.length; i++)
params[i].setInfo(freevars[i].info().subst(freevars, params));
return params;
}
Symbol[] fvsParams(Symbol owner) {
Symbol[] freevars = get(free.fvs, owner).toArray();
Symbol[] params = new Symbol[freevars.length];
for (int i = 0; i < params.length; i++) {
params[i] = freevars[i].cloneSymbol(owner);
params[i].pos = owner.pos;
params[i].flags &= CAPTURED;
params[i].flags |= PARAM | SYNTHETIC;
params[i].setInfo(freevars[i].type());
}
return params;
}
Symbol[] newtparams(Symbol owner) {
Symbol[] tparams = owner.nextType().typeParams();
int nfree = get(free.ftvs, owner).size();
assert nfree == tparams.length - owner.type().typeParams().length
: owner + " " + nfree + " " + tparams.length + " " + owner.type().firstParams().length;
Symbol[] newtparams = new Symbol[nfree];
System.arraycopy(tparams, tparams.length - nfree, newtparams, 0, nfree);
return newtparams;
}
Symbol[] newparams(Symbol owner) {
Symbol[] params = owner.nextType().firstParams();
int nfree = get(free.fvs, owner).size();
assert nfree == params.length - owner.type().firstParams().length;
Symbol[] newparams = new Symbol[nfree];
System.arraycopy(params, params.length - nfree, newparams, 0, nfree);
return newparams;
}
/** change symbol of tree so that
* owner = currentClass
* newparams are added
* enter symbol in scope of currentClass
*/
void liftSymbol(Tree tree) {
switch (tree) {
case ClassDef(_, _, _, _, _, _):
((ClassDef) tree).mods |= LIFTED;
Symbol sym = tree.symbol();
assert sym.isLocal() : sym;
Symbol constr = sym.primaryConstructor();
liftSymbol(
sym, get(free.ftvs, constr).toArray(),
ftvsParams(constr), fvsParams(constr));
break;
case DefDef(_, _, _, _, _, _):
((DefDef) tree).mods |= LIFTED;
Symbol sym = tree.symbol();
assert sym.isLocal() : sym;
liftSymbol(
sym, get(free.ftvs, sym).toArray(),
ftvsParams(sym), fvsParams(sym));
}
}
void liftSymbol(Symbol sym, Symbol[] oldtparams,
Symbol[] newtparams, Symbol[] newparams) {
Symbol enclClass = sym.owner().enclClass();
if (!sym.isPrimaryConstructor()) sym.setOwner(enclClass);
if (!sym.isConstructor()) enclClass.members().enter(sym);
if (sym.isMethod()) {
if (newtparams.length != 0 || newparams.length != 0) {
sym.updateInfo(
addParams(
addTypeParams(
sym.nextInfo(), oldtparams, newtparams),
newparams));
if (global.debug)
global.log(sym + " has now type " + sym.nextType());
}
} else if (sym.kind == CLASS) {
Symbol constr = sym.primaryConstructor();
liftSymbol(constr, oldtparams, newtparams, newparams);
// fix result type of constructor
constr.updateInfo(descr.transform(constr.nextInfo(), constr));
} else {
throw new ApplicationError();
}
}
Type addTypeParams(Type tp, Symbol[] oldtparams, Symbol[] newtparams) {
if (newtparams.length == 0) return tp;
switch (tp) {
case MethodType(_, _):
return Type.PolyType(
newtparams,
Type.getSubst(oldtparams, newtparams, true).apply(tp));
case PolyType(Symbol[] tparams, Type restpe):
Symbol[] tparams1 = new Symbol[tparams.length + newtparams.length];
System.arraycopy(tparams, 0, tparams1, 0, tparams.length);
System.arraycopy(newtparams, 0, tparams1, tparams.length, newtparams.length);
return Type.PolyType(
tparams1,
Type.getSubst(oldtparams, newtparams, true).apply(restpe));
default:
throw new ApplicationError("illegal type: " + tp);
}
}
Type addParams(Type tp, Symbol[] newparams) {
if (newparams.length == 0) return tp;
switch (tp) {
case MethodType(Symbol[] params, Type restpe):
Symbol[] params1 = new Symbol[params.length + newparams.length];
System.arraycopy(params, 0, params1, 0, params.length);
System.arraycopy(newparams, 0, params1, params.length, newparams.length);
return Type.MethodType(params1, restpe);
case PolyType(Symbol[] tparams, Type restpe):
return Type.PolyType(tparams, addParams(restpe, newparams));
default:
throw new ApplicationError("illegal type: " + tp);
}
}
AbsTypeDef[] addTypeParams(AbsTypeDef[] tparams, Symbol[] newtparams) {
if (newtparams.length == 0) return tparams;
AbsTypeDef[] tparams1 = new AbsTypeDef[tparams.length + newtparams.length];
System.arraycopy(tparams, 0, tparams1, 0, tparams.length);
for (int i = 0; i < newtparams.length; i++) {
tparams1[tparams.length + i] = gen.mkTypeParam(newtparams[i]);
}
return tparams1;
}
ValDef[] addParams(ValDef[] params, Symbol[] newparams) {
if (newparams.length == 0) return params;
ValDef[] params1 = new ValDef[params.length + newparams.length];
System.arraycopy(params, 0, params1, 0, params.length);
for (int i = 0; i < newparams.length; i++) {
params1[params.length + i] = gen.mkParam(newparams[i]);
}
return params1;
}
/** For all variables or type variables in `fvs',
* append proxies to argument array `args'.
*/
Tree[] addFreeArgs(int pos, SymSet fvs, Tree[] args, boolean types) {
if (fvs != SymSet.EMPTY) {
Symbol[] fparams = fvs.toArray();
Tree[] args1 = new Tree[args.length + fparams.length];
System.arraycopy(args, 0, args1, 0, args.length);
for (int i = 0; i < fparams.length; i++) {
Symbol farg = descr.proxy(fparams[i], currentOwner);
args1[args.length + i] =
types ? gen.mkTypeRef(pos, farg) : gen.Ident(pos, farg);
}
return args1;
} else {
return args;
}
}
//todo: remove type parameters
Tree mkList(int pos, Type tpe, Tree[] args) {
return mkList(pos, tpe.typeArgs()[0], args, 0);
}
Tree mkList(int pos, Type elemtpe, Tree[] args, int start) {
if (start == args.length) return gen.Nil(pos);
else return gen.Cons(pos, elemtpe, args[start],
mkList(pos, elemtpe, args, start + 1));
}
/*
Tree mkNil(int pos) {
return gen.mkRef(pos, global.definitions.getModule(Names.scala_Nil));
}
Tree mkCons(int pos, Type elemtpe, Tree hd, Tree tl) {
return gen.New(
gen.Apply(
gen.TypeApply(
gen.mkRef(
pos,
global.definitions.getClass(Names.scala_COLONCOLON).primaryConstructor()),
new Tree[]{gen.mkType(pos, elemtpe)}),
new Tree[]{hd, tl}));
}
*/
}
|
package org.ovirt.engine.core.vdsbroker.gluster;
import java.util.Map;
import org.ovirt.engine.core.common.asynctasks.gluster.GlusterAsyncTaskStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeTaskStatusDetail;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeTaskStatusEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeTaskStatusForHost;
import org.ovirt.engine.core.common.job.JobExecutionStatus;
import org.ovirt.engine.core.compat.Guid;
public class GlusterVolumeTaskReturnForXmlRpc extends GlusterTaskInfoReturnForXmlRpc {
private static final String HOST_LIST = "hosts";
private static final String SUMMARY = "summary";
private static final String HOST_NAME = "name";
private static final String HOST_UUID = "id";
private static final String FILES_MOVED = "filesMoved";
private static final String TOTAL_SIZE_MOVED = "totalSizeMoved";
private static final String FILES_SCANNED = "filesScanned";
private static final String FILES_FAILED = "filesFailed";
private static final String FILES_SKIPPED = "filesSkipped";
private static final String STATUS = "status";
private static final String RUNTIME = "runtime";
private final GlusterVolumeTaskStatusEntity statusDetails = new GlusterVolumeTaskStatusEntity();
@SuppressWarnings("unchecked")
public GlusterVolumeTaskReturnForXmlRpc(Map<String, Object> innerMap) {
super(innerMap);
if (innerMap.containsKey(HOST_LIST)) {
for (Object nodeStatus : (Object[]) innerMap.get(HOST_LIST)) {
statusDetails.getHostwiseStatusDetails().add(getStatusForNode((Map<String, Object>) nodeStatus));
}
}
if (innerMap.containsKey(SUMMARY)) {
populateGlusterVolumeTaskStatusDetail(statusDetails.getStatusSummary(),
(Map<String, Object>) innerMap.get(SUMMARY));
}
}
private GlusterVolumeTaskStatusForHost getStatusForNode(Map<String, Object> nodeStatus) {
GlusterVolumeTaskStatusForHost rebalanceStatusForHost = new GlusterVolumeTaskStatusForHost();
rebalanceStatusForHost.setHostName(nodeStatus.containsKey(HOST_NAME) ? (String) nodeStatus.get(HOST_NAME)
: null);
rebalanceStatusForHost.setHostUuid(nodeStatus.containsKey(HOST_UUID) ? new Guid((String) nodeStatus.get(HOST_UUID))
: null);
populateGlusterVolumeTaskStatusDetail(rebalanceStatusForHost, nodeStatus);
return rebalanceStatusForHost;
}
private void populateGlusterVolumeTaskStatusDetail(GlusterVolumeTaskStatusDetail detail, Map<String, Object> map) {
detail.setFilesScanned(map.containsKey(FILES_SCANNED) ? Long.parseLong(map.get(FILES_SCANNED).toString()) : 0);
detail.setFilesMoved(map.containsKey(FILES_MOVED) ? Long.parseLong(map.get(FILES_MOVED).toString()) : 0);
detail.setFilesFailed(map.containsKey(FILES_FAILED) ? Long.parseLong(map.get(FILES_FAILED).toString()) : 0);
detail.setFilesSkipped(map.containsKey(FILES_SKIPPED) ? Long.parseLong(map.get(FILES_SKIPPED).toString()) : 0);
detail.setTotalSizeMoved(map.containsKey(TOTAL_SIZE_MOVED) ? Long.parseLong(map.get(TOTAL_SIZE_MOVED).toString())
: 0);
detail.setStatus(map.containsKey(STATUS) ? GlusterAsyncTaskStatus.from(map.get(STATUS).toString())
.getJobExecutionStatus() : JobExecutionStatus.UNKNOWN);
detail.setRunTime(map.containsKey(RUNTIME) ? Double.parseDouble(map.get(RUNTIME).toString()) : 0);
}
public GlusterVolumeTaskStatusEntity getStatusDetails() {
return statusDetails;
}
}
|
package gov.nih.nci.cabig.caaers.service.migrator;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.domain.AdditionalInformation;
import gov.nih.nci.cabig.caaers.domain.AdditionalInformationDocument;
import gov.nih.nci.cabig.caaers.domain.Address;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod;
import gov.nih.nci.cabig.caaers.domain.AdverseEventResponseDescription;
import gov.nih.nci.cabig.caaers.domain.Agent;
import gov.nih.nci.cabig.caaers.domain.AgentAdjustment;
import gov.nih.nci.cabig.caaers.domain.AnatomicSite;
import gov.nih.nci.cabig.caaers.domain.Availability;
import gov.nih.nci.cabig.caaers.domain.BehavioralIntervention;
import gov.nih.nci.cabig.caaers.domain.BiologicalIntervention;
import gov.nih.nci.cabig.caaers.domain.ConcomitantMedication;
import gov.nih.nci.cabig.caaers.domain.ConfigProperty;
import gov.nih.nci.cabig.caaers.domain.CourseAgent;
import gov.nih.nci.cabig.caaers.domain.CtepStudyDisease;
import gov.nih.nci.cabig.caaers.domain.DateValue;
import gov.nih.nci.cabig.caaers.domain.DelayUnits;
import gov.nih.nci.cabig.caaers.domain.Device;
import gov.nih.nci.cabig.caaers.domain.DeviceOperator;
import gov.nih.nci.cabig.caaers.domain.DietarySupplementIntervention;
import gov.nih.nci.cabig.caaers.domain.DiseaseHistory;
import gov.nih.nci.cabig.caaers.domain.DiseaseTerm;
import gov.nih.nci.cabig.caaers.domain.Dose;
import gov.nih.nci.cabig.caaers.domain.EventStatus;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.GeneticIntervention;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.InterventionSite;
import gov.nih.nci.cabig.caaers.domain.Investigator;
import gov.nih.nci.cabig.caaers.domain.Lab;
import gov.nih.nci.cabig.caaers.domain.LabCategory;
import gov.nih.nci.cabig.caaers.domain.LabTerm;
import gov.nih.nci.cabig.caaers.domain.LabValue;
import gov.nih.nci.cabig.caaers.domain.LocalInvestigator;
import gov.nih.nci.cabig.caaers.domain.LocalOrganization;
import gov.nih.nci.cabig.caaers.domain.LocalResearchStaff;
import gov.nih.nci.cabig.caaers.domain.MedicalDevice;
import gov.nih.nci.cabig.caaers.domain.MetastaticDiseaseSite;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier;
import gov.nih.nci.cabig.caaers.domain.OtherAEIntervention;
import gov.nih.nci.cabig.caaers.domain.OtherCause;
import gov.nih.nci.cabig.caaers.domain.OtherIntervention;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.ParticipantHistory;
import gov.nih.nci.cabig.caaers.domain.ParticipantHistory.Measure;
import gov.nih.nci.cabig.caaers.domain.Physician;
import gov.nih.nci.cabig.caaers.domain.PostAdverseEventStatus;
import gov.nih.nci.cabig.caaers.domain.PreExistingCondition;
import gov.nih.nci.cabig.caaers.domain.PriorTherapy;
import gov.nih.nci.cabig.caaers.domain.PriorTherapyAgent;
import gov.nih.nci.cabig.caaers.domain.RadiationAdministration;
import gov.nih.nci.cabig.caaers.domain.RadiationIntervention;
import gov.nih.nci.cabig.caaers.domain.ReportStatus;
import gov.nih.nci.cabig.caaers.domain.Reporter;
import gov.nih.nci.cabig.caaers.domain.ReprocessedDevice;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.ReviewStatus;
import gov.nih.nci.cabig.caaers.domain.SAEReportPreExistingCondition;
import gov.nih.nci.cabig.caaers.domain.SAEReportPriorTherapy;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyAgent;
import gov.nih.nci.cabig.caaers.domain.StudyDevice;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.Submitter;
import gov.nih.nci.cabig.caaers.domain.SurgeryIntervention;
import gov.nih.nci.cabig.caaers.domain.TimeValue;
import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment;
import gov.nih.nci.cabig.caaers.domain.TreatmentInformation;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition;
import gov.nih.nci.cabig.caaers.domain.report.ReportDeliveryDefinition;
import gov.nih.nci.cabig.caaers.domain.report.ReportFormat;
import gov.nih.nci.cabig.caaers.domain.report.ReportVersion;
import gov.nih.nci.cabig.caaers.domain.report.TimeScaleUnit;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdditionalInformationDocumentType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdditionalInformationType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdverseEventReportingPeriodType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.AdverseEventResponseDescriptionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.BehavioralInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.BiologicalInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ConcomitantMedicationRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ConcomitantMedicationType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ContactMechanismType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.CourseAgentRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.CourseAgentType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.DateValueType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.DietarySupplementInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.DiseaseHistoryRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.DiseaseHistoryType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.DoseType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.GeneticInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.LabType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.MedicalDeviceRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.MedicalDeviceType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.MetastaticDiseaseSiteType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OrganizationAssignedIdentifierType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OtherAEInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OtherCauseType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.OtherInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ParticipantHistoryType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ParticipantType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ParticipantType.Identifiers;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.PhysicianType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.PriorTherapyAgentType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.RadiationInterventionRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.RadiationInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReportDeliveryDefinitionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReportType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReportVersionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.ReporterType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.SAEReportPreExistingConditionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.SAEReportPriorTherapyType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudyParticipantAssignmentRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudyParticipantAssignmentType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudyRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudySiteRefType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.StudySiteType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.SubmitterType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.SurgeryInterventionType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.TreatmentAssignmentType;
import gov.nih.nci.cabig.caaers.integration.schema.aereport.TreatmentInformationType;
import gov.nih.nci.cabig.caaers.integration.schema.common.OrganizationType;
import gov.nih.nci.cabig.caaers.utils.XMLUtil;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.MessageSource;
/**
* @author vinodh.rc
*/
public class ExpeditedAdverseEventReportConverterUtility {
/** The Constant EMAIL. key for the e-mail address */
protected static final String EMAIL = "e-mail";
/** The Constant FAX. key for the fax number */
protected static final String FAX = "fax";
/** The Constant PHONE. key for the phone number */
protected static final String PHONE = "phone";
private MessageSource messageSource;
/** The now factory. */
private NowFactory nowFactory;
public NowFactory getNowFactory() {
return nowFactory;
}
public void setNowFactory(NowFactory nowFactory) {
this.nowFactory = nowFactory;
}
private StudyDao studyDao;
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public MessageSource getMessageSource() {
return messageSource;
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
protected List<Lab> mergeLabs(List<Lab> allLabs){
List<Lab> mergedLabs = new ArrayList<Lab>();
Map<String,Lab> map = new HashMap<String,Lab>();
for(Lab lab :allLabs){
if(map.get(lab.getLabTerm().getTerm()) == null){
map.put(lab.getLabTerm().getTerm(),lab);
} else {
if(lab.getBaseline().getValue() != null && map.get(lab.getLabTerm().getTerm()).getBaseline().getValue() == null){
addBaseline(lab, map.get(lab.getLabTerm().getTerm()));
}
if(lab.getNadir().getValue() != null && map.get(lab.getLabTerm().getTerm()).getNadir().getValue() == null){
addNadir(lab, map.get(lab.getLabTerm().getTerm()));
}
if(lab.getRecovery().getValue() != null && map.get(lab.getLabTerm().getTerm()).getRecovery().getValue() == null){
addRecovery(lab, map.get(lab.getLabTerm().getTerm()));
}
}
}
mergedLabs.addAll(map.values());
return mergedLabs;
}
protected void addBaseline(Lab labSrc,Lab labTarget){
labTarget.getBaseline().setValue(labSrc.getBaseline().getValue());
if(labSrc.getBaseline().getDate() != null){
labTarget.getBaseline().setDate(labSrc.getBaseline().getDate());
}
}
protected void addNadir(Lab labSrc,Lab labTarget){
labTarget.getNadir().setValue(labSrc.getNadir().getValue());
if(labSrc.getNadir().getDate() != null){
labTarget.getNadir().setDate(labSrc.getNadir().getDate());
}
}
protected void addRecovery(Lab labSrc,Lab labTarget){
labTarget.getRecovery().setValue(labSrc.getRecovery().getValue());
if(labSrc.getRecovery().getDate() != null){
labTarget.getRecovery().setDate(labSrc.getRecovery().getDate());
}
}
protected OtherAEIntervention convertOtherAEIntervention(OtherAEInterventionType xmlOtherAEInterventionType, ExpeditedAdverseEventReport report){
OtherAEIntervention otherAEIntervention = new OtherAEIntervention();
otherAEIntervention.setDescription(xmlOtherAEInterventionType.getDescription());
if(xmlOtherAEInterventionType.getStudyIntervention() != null){
otherAEIntervention.setStudyIntervention(convertOtherIntervention(xmlOtherAEInterventionType.getStudyIntervention()));
}
otherAEIntervention.setReport(report);
return otherAEIntervention;
}
protected BehavioralIntervention convertBehavioralIntervention(BehavioralInterventionType xmlBehavioralInterventionType, ExpeditedAdverseEventReport report){
BehavioralIntervention behavioralIntervention= new BehavioralIntervention();
behavioralIntervention.setDescription(xmlBehavioralInterventionType.getDescription());
if(xmlBehavioralInterventionType.getStudyIntervention() != null){
behavioralIntervention.setStudyIntervention(convertOtherIntervention(xmlBehavioralInterventionType.getStudyIntervention()));
}
behavioralIntervention.setReport(report);
return behavioralIntervention;
}
protected GeneticIntervention convertGeneticIntervention(GeneticInterventionType xmlGeneticInterventionType, ExpeditedAdverseEventReport report){
GeneticIntervention geneticIntervention= new GeneticIntervention();
geneticIntervention.setDescription(xmlGeneticInterventionType.getDescription());
if(xmlGeneticInterventionType.getStudyIntervention() != null){
geneticIntervention.setStudyIntervention(convertOtherIntervention(xmlGeneticInterventionType.getStudyIntervention()));
}
geneticIntervention.setReport(report);
return geneticIntervention;
}
protected Report convertReport(ReportType xmlReportType, SubmitterType xmlSubmitterType){
Report report = new Report();
// report.setRequired(xmlReportType.isRequired());
if(xmlReportType.isWithdraw() != null && xmlReportType.isWithdraw()){
report.setWithdrawnOn(nowFactory.getNow());
}
if(xmlReportType.getCaseNumber() != null){
report.setCaseNumber(xmlReportType.getCaseNumber());
}
if ( xmlReportType.isManuallySelected() != null ) {
report.setManuallySelected(xmlReportType.isManuallySelected());
}
if(xmlReportType.getReviewStatus() != null){
report.setReviewStatus(ReviewStatus.valueOf(xmlReportType.getReviewStatus().name()));
}
for(ReportVersionType xmlReportVersionType: xmlReportType.getAeReportVersion()){
ReportVersion reportVersion = new ReportVersion();
if(xmlReportVersionType.getAmendedOn() != null){
reportVersion.setAmendedOn(xmlReportVersionType.getAmendedOn().toGregorianCalendar().getTime());
}
if(xmlReportVersionType.getDueOn() != null){
reportVersion.setDueOn(xmlReportVersionType.getDueOn().toGregorianCalendar().getTime());
}
if(xmlReportVersionType.getWithdrawnOn() != null){
reportVersion.setWithdrawnOn(xmlReportVersionType.getWithdrawnOn().toGregorianCalendar().getTime());
}
if(xmlReportVersionType.getSubmittedOn() != null){
reportVersion.setSubmittedOn(xmlReportVersionType.getSubmittedOn().toGregorianCalendar().getTime());
}
if(xmlReportVersionType.getCreatedOn() != null){
reportVersion.setCreatedOn(xmlReportVersionType.getCreatedOn().toGregorianCalendar().getTime());
}
reportVersion.setPhysicianSignoff(xmlReportVersionType.isPhysicianSignoff());
if(xmlReportVersionType.getReportVersionId() == null){
reportVersion.setReportVersionId("0");
} else {
reportVersion.setReportVersionId((xmlReportVersionType.getReportVersionId()));
}
reportVersion.setSubmissionMessage(xmlReportVersionType.getSubmissionMessage());
reportVersion.setSubmissionUrl(xmlReportVersionType.getSubmissionUrl());
reportVersion.setCcEmails(xmlReportVersionType.getCcEmails());
if(xmlReportVersionType.getReportStatus() != null){
reportVersion.setReportStatus(ReportStatus.valueOf(xmlReportVersionType.getReportStatus().name()));
}
if(xmlSubmitterType != null){
Submitter submitter = convertSubmitter(xmlSubmitterType);
reportVersion.setSubmitter(submitter);
}
report.addReportVersion(reportVersion);
}
ReportDefinition reportDefinition = new ReportDefinition();
reportDefinition.setName(xmlReportType.getAeReportDefinition().getName());
reportDefinition.setLabel(xmlReportType.getAeReportDefinition().getLabel());
reportDefinition.setDuration(xmlReportType.getAeReportDefinition().getDuration());
if(xmlReportType.getAeReportDefinition().getGroup() != null){
ConfigProperty group = new ConfigProperty();
group.setCode(xmlReportType.getAeReportDefinition().getGroup().getCode());
group.setName(xmlReportType.getAeReportDefinition().getGroup().getName());
reportDefinition.setGroup(group);
}
if(xmlReportType.getAeReportDefinition().getTimeScaleUnitType() != null && xmlReportType.getAeReportDefinition().getTimeScaleUnitType().name() != null){
reportDefinition.setTimeScaleUnitType(TimeScaleUnit.valueOf(xmlReportType.getAeReportDefinition().getTimeScaleUnitType().name()));
}
report.setReportDefinition(reportDefinition);
for(ReportDeliveryDefinitionType xmlReportDeliveryDefinitionType : xmlReportType.getAeReportDefinition().getReportDeliveryDefinition()){
ReportDeliveryDefinition reportDeliveryDefinition = new ReportDeliveryDefinition();
reportDeliveryDefinition.setEndPoint(xmlReportDeliveryDefinitionType.getEndPoint());
reportDeliveryDefinition.setEndPointType(xmlReportDeliveryDefinitionType.getEndPointType());
reportDeliveryDefinition.setEntityDescription(xmlReportDeliveryDefinitionType.getEntityDescription());
reportDeliveryDefinition.setEntityName(xmlReportDeliveryDefinitionType.getEntityName());
reportDeliveryDefinition.setEntityType(xmlReportDeliveryDefinitionType.getEntityType());
reportDeliveryDefinition.setPassword(xmlReportDeliveryDefinitionType.getPassword());
reportDeliveryDefinition.setUserName(xmlReportDeliveryDefinitionType.getUserName());
reportDeliveryDefinition.setFormat(ReportFormat.valueOf(xmlReportDeliveryDefinitionType.getFormat().name()));
reportDefinition.addReportDeliveryDefinition(reportDeliveryDefinition);
}
return report;
}
protected AdditionalInformation convertAdditionalInformation(AdditionalInformationType additionalInfoType){
AdditionalInformation additionalInfo = new AdditionalInformation();
additionalInfo.setAutopsyReport(additionalInfoType.isAutopsyReport());
additionalInfo.setConsults(additionalInfoType.isConsults());
additionalInfo.setDischargeSummary(additionalInfoType.isDischargeSummary());
additionalInfo.setFlowCharts(additionalInfoType.isFlowCharts());
additionalInfo.setIrbReport(additionalInfoType.isIrbReport());
additionalInfo.setLabReports(additionalInfoType.isLabReports());
additionalInfo.setObaForm(additionalInfoType.isObaForm());
additionalInfo.setOther(additionalInfoType.isOther());
additionalInfo.setPathologyReport(additionalInfoType.isPathologyReport());
additionalInfo.setProgressNotes(additionalInfoType.isProgressNotes());
additionalInfo.setRadiologyReports(additionalInfoType.isRadiologyReports());
additionalInfo.setReferralLetters(additionalInfoType.isReferralLetters());
additionalInfo.setOtherInformation(additionalInfoType.getOtherInformation());
for(AdditionalInformationDocumentType xmlAdditionalInformationDocumentType: additionalInfoType.getAdditionalInformationDocuments()){
AdditionalInformationDocument document = new AdditionalInformationDocument();
document.setFileId(xmlAdditionalInformationDocumentType.getFileId());
document.setFileName(xmlAdditionalInformationDocumentType.getFileName());
document.setFilePath(xmlAdditionalInformationDocumentType.getFilePath());
document.setFileSize(xmlAdditionalInformationDocumentType.getFileSize());
document.setOriginalFileName(xmlAdditionalInformationDocumentType.getOriginalFileName());
document.setRelativePath(xmlAdditionalInformationDocumentType.getRelativePath());
if(xmlAdditionalInformationDocumentType.getAdditionalInformationDocumentType() != null){
document.setAdditionalInformationDocumentType(gov.nih.nci.cabig.caaers.domain.AdditionalInformationDocumentType.valueOf
(xmlAdditionalInformationDocumentType.getAdditionalInformationDocumentType().name()));
}
}
return additionalInfo;
}
protected OtherCause convertOtherCause(OtherCauseType xmlOtherCauseType){
OtherCause otherCause = new OtherCause();
otherCause.setText(xmlOtherCauseType.getText());
return otherCause;
}
protected TreatmentInformation convertTreatmentInformation(TreatmentInformationType treatmentInfoType){
TreatmentInformation treatmentInformation = new TreatmentInformation();
treatmentInformation.setInvestigationalAgentAdministered(treatmentInfoType.isInvestigationalAgentAdministered());
treatmentInformation.setFirstCourseDate(XMLUtil.toDate(treatmentInfoType.getFirstCourseDate()));
treatmentInformation.setTotalCourses(treatmentInfoType.getTotalCourses());
treatmentInformation.setTreatmentAssignment(convertTreatmentAssignment(treatmentInfoType.getTreatmentAssignment()));
//Intervention - Agents
for (CourseAgentType courseAgentType : treatmentInfoType.getCourseAgent()){
treatmentInformation.addCourseAgent(convertCourseAgent(courseAgentType));
}
return treatmentInformation;
}
protected TreatmentAssignment convertTreatmentAssignment(TreatmentAssignmentType tacType){
TreatmentAssignment tac = new TreatmentAssignment();
if(tacType != null){
tac.setCode(tacType.getCode());
tac.setDescription(tacType.getDescription());
tac.setDoseLevelOrder(tacType.getDoseLevelOrder());
tac.setComments(tacType.getComments());
}
return tac;
}
protected CourseAgent convertCourseAgentRef(CourseAgentRefType courseAgentRefType){
CourseAgent courseAgent = new CourseAgent();
StudyAgent studyAgent = new StudyAgent();
Agent agent = new Agent();
agent.setNscNumber(courseAgentRefType.getStudyAgentRef().getAgent().getNscNumber());
studyAgent.setAgent(agent);
courseAgent.setStudyAgent(studyAgent);
return courseAgent;
}
protected CourseAgent convertCourseAgent(CourseAgentType courseAgentType){
CourseAgent courseAgent = new CourseAgent();
courseAgent.setAdministrationDelay(courseAgentType.getAdministrationDelayAmount());
if(courseAgent.getAdministrationDelayUnits() != null){
courseAgent.setAdministrationDelayUnits(DelayUnits.valueOf(courseAgentType.getAdministrationDelayUnits().name()));
}
if(courseAgentType.getDose() != null){
courseAgent.setDose(convertDose(courseAgentType.getDose()));
}
if(courseAgentType.getModifiedDose() != null){
courseAgent.setModifiedDose(convertDose(courseAgentType.getModifiedDose()));
}
if(courseAgentType.getAgentAdjustment() != null){
courseAgent.setAgentAdjustment(AgentAdjustment.valueOf(courseAgentType.getAgentAdjustment().value()));
}
courseAgent.setDurationAndSchedule(courseAgentType.getDurationAndSchedule());
courseAgent.setTotalDoseAdministeredThisCourse(courseAgentType.getTotalDoseAdministeredThisCourse());
if(courseAgentType.getLastAdministeredDate() != null){
courseAgent.setLastAdministeredDate(courseAgentType.getLastAdministeredDate().toGregorianCalendar().getTime());
}
if(courseAgentType.getStudyAgent() != null){
StudyAgent studyAgent = new StudyAgent();
if(courseAgentType.getStudyAgent().getAgent() != null){
Agent agent = new Agent();
agent.setName(courseAgentType.getStudyAgent().getAgent().getName());
agent.setDescription(courseAgentType.getStudyAgent().getAgent().getDescription());
agent.setNscNumber(courseAgentType.getStudyAgent().getAgent().getNscNumber());
studyAgent.setAgent(agent);
} else {
studyAgent.setOtherAgent(courseAgentType.getStudyAgent().getOtherAgent());
}
courseAgent.setStudyAgent(studyAgent);
}
if(courseAgentType.getLotNumber() != null){
courseAgent.setLotNumber(courseAgentType.getLotNumber());
}
return courseAgent;
}
protected Dose convertDose(DoseType xmlDoseType){
Dose dose = new Dose();
dose.setAmount(xmlDoseType.getAmount());
dose.setUnits(xmlDoseType.getUnits());
dose.setRoute(xmlDoseType.getRoute());
return dose;
}
protected SAEReportPriorTherapy convertPriorTherapy(SAEReportPriorTherapyType priorTherapyType){
SAEReportPriorTherapy saeReportPriorTherapy = new SAEReportPriorTherapy();
if(priorTherapyType.getStartDate() != null){
saeReportPriorTherapy.setStartDate((convertDateValue(priorTherapyType.getStartDate())));
}
if(priorTherapyType.getEndDate() != null) {
saeReportPriorTherapy.setEndDate((convertDateValue(priorTherapyType.getEndDate())));
}
saeReportPriorTherapy.setOther(priorTherapyType.getOther());
if(priorTherapyType.getPriorTherapy() != null){
PriorTherapy priorTherapy = new PriorTherapy();
priorTherapy.setText(priorTherapyType.getPriorTherapy().getText());
priorTherapy.setMeddraCode((priorTherapyType.getPriorTherapy().getMeddraCode()));
saeReportPriorTherapy.setPriorTherapy(priorTherapy);
}
if(priorTherapyType.getPriorTherapyAgent() != null && ! priorTherapyType.getPriorTherapyAgent().isEmpty()){
for(PriorTherapyAgentType xmlPriorTherapyAgent : priorTherapyType.getPriorTherapyAgent()){
PriorTherapyAgent priorTherapyAgent = new PriorTherapyAgent();
Agent agent = new Agent();
agent.setNscNumber(xmlPriorTherapyAgent.getAgent().getNscNumber());
priorTherapyAgent.setAgent(agent);
saeReportPriorTherapy.getPriorTherapyAgents().add(priorTherapyAgent);
}
}
return saeReportPriorTherapy;
}
protected SAEReportPreExistingCondition convertPreExistingCondition(SAEReportPreExistingConditionType preCondType){
SAEReportPreExistingCondition saeReportPreExistingCondition = new SAEReportPreExistingCondition();
saeReportPreExistingCondition.setOther(preCondType.getOther());
saeReportPreExistingCondition.setLinkedToOtherCause(preCondType.isLinkedToOtherCause() == null ? Boolean.FALSE : preCondType.isLinkedToOtherCause());
if(preCondType.getPreExistingCondition() != null){
PreExistingCondition preExistingCondition = new PreExistingCondition();
preExistingCondition.setText(preCondType.getPreExistingCondition().getText());
preExistingCondition.setMeddraHlgt(preCondType.getPreExistingCondition().getMeddraHlgt());
preExistingCondition.setMeddraLlt(preCondType.getPreExistingCondition().getMeddraLlt());
preExistingCondition.setMeddraLltCode(preCondType.getPreExistingCondition().getMeddraLltCode());
saeReportPreExistingCondition.setPreExistingCondition(preExistingCondition);
}
return saeReportPreExistingCondition;
}
protected Lab convertLab(LabType labType){
Lab lab = new Lab();
lab.setUnits(labType.getUnits());
lab.setNormalRange(labType.getNormalRange());
if(labType.getBaseline() != null){
LabValue baseline = new LabValue();
baseline.setValue(labType.getBaseline().getValue());
if(labType.getBaseline().getDate() != null){
baseline.setDate(labType.getBaseline().getDate().toGregorianCalendar().getTime());
}
lab.setBaseline(baseline);
}
if(labType.getNadir() != null){
LabValue nadir = new LabValue();
nadir.setValue(labType.getNadir().getValue());
if(labType.getNadir().getDate() != null){
nadir.setDate(labType.getNadir().getDate().toGregorianCalendar().getTime());
}
lab.setNadir(nadir);
}
if(labType.getRecovery() != null){
LabValue recovery = new LabValue();
recovery.setValue(labType.getRecovery().getValue());
if(labType.getRecovery().getDate() != null){
recovery.setDate(labType.getRecovery().getDate().toGregorianCalendar().getTime());
}
lab.setRecovery(recovery);
}
if(labType.getLabTerm() != null){
LabTerm labTerm = new LabTerm();
labTerm.setTerm(labType.getLabTerm().getTerm());
if(labType.getLabTerm().getCategory() != null){
LabCategory labCategory = new LabCategory();
labCategory.setName(labType.getLabTerm().getCategory().getName());
labTerm.setCategory(labCategory);
}
lab.setLabTerm(labTerm);
}
return lab;
}
protected ConcomitantMedication convertConcomitantMedication(ConcomitantMedicationType xmlConcomitantMedicationType){
ConcomitantMedication concomitantMedication = new ConcomitantMedication();
concomitantMedication.setAgentName(xmlConcomitantMedicationType.getName().toString());
if(xmlConcomitantMedicationType.getStartDate() != null){
concomitantMedication.setStartDate(convertDateValue(xmlConcomitantMedicationType.getStartDate()));
}
if(xmlConcomitantMedicationType.getEndDate()!= null){
concomitantMedication.setEndDate(convertDateValue(xmlConcomitantMedicationType.getEndDate()));
}
concomitantMedication.setStillTakingMedications(xmlConcomitantMedicationType.isStillTakingMedications() != null ? xmlConcomitantMedicationType.isStillTakingMedications() : Boolean.FALSE );
return concomitantMedication;
}
protected ConcomitantMedication convertConcomitantMedicationRef(ConcomitantMedicationRefType xmlConcomitantMedicationRefType){
ConcomitantMedication concomitantMedication = new ConcomitantMedication();
concomitantMedication.setAgentName(xmlConcomitantMedicationRefType.getName().toString());
if(xmlConcomitantMedicationRefType.getStartDate() != null){
concomitantMedication.setStartDate(convertDateValue(xmlConcomitantMedicationRefType.getStartDate()));
}
if(xmlConcomitantMedicationRefType.getEndDate()!= null){
concomitantMedication.setEndDate(convertDateValue(xmlConcomitantMedicationRefType.getEndDate()));
}
return concomitantMedication;
}
protected MedicalDevice convertMedicalDevice(MedicalDeviceType xmlMedicalDeviceType){
MedicalDevice medicalDevice = new MedicalDevice();
medicalDevice.setBrandName(xmlMedicalDeviceType.getBrandName());
medicalDevice.setCatalogNumber(xmlMedicalDeviceType.getCatalogNumber());
medicalDevice.setCommonName(xmlMedicalDeviceType.getCommonName());
if(xmlMedicalDeviceType.getDeviceOperator() != null){
medicalDevice.setDeviceOperator(DeviceOperator.valueOf(xmlMedicalDeviceType.getDeviceOperator().name()));
}
medicalDevice.setDeviceType(xmlMedicalDeviceType.getDeviceType());
medicalDevice.setManufacturerName(xmlMedicalDeviceType.getManufacturerName());
medicalDevice.setManufacturerCity(xmlMedicalDeviceType.getManufacturerCity());
medicalDevice.setManufacturerState(xmlMedicalDeviceType.getManufacturerState());
medicalDevice.setModelNumber(xmlMedicalDeviceType.getModelNumber());
medicalDevice.setSerialNumber(xmlMedicalDeviceType.getSerialNumber());
medicalDevice.setOtherNumber(xmlMedicalDeviceType.getOtherNumber());
if(xmlMedicalDeviceType.getExplantedDate() != null){
medicalDevice.setExplantedDate(xmlMedicalDeviceType.getExplantedDate().toGregorianCalendar().getTime());
}
if(xmlMedicalDeviceType.getImplantedDate() != null){
medicalDevice.setImplantedDate(xmlMedicalDeviceType.getImplantedDate().toGregorianCalendar().getTime());
}
if(xmlMedicalDeviceType.getDeviceReprocessed() != null){
medicalDevice.setDeviceReprocessed(ReprocessedDevice.valueOf(xmlMedicalDeviceType.getDeviceReprocessed().name()));
if(xmlMedicalDeviceType.getDeviceReprocessed().name().equals("YES")){
medicalDevice.setReprocessorName(xmlMedicalDeviceType.getReprocessedName());
medicalDevice.setReprocessorAddress(xmlMedicalDeviceType.getReprocessedAddress());
}
}
if(xmlMedicalDeviceType.getEvaluationAvailability() != null){
medicalDevice.setEvaluationAvailability(Availability.valueOf(xmlMedicalDeviceType.getEvaluationAvailability().name()));
}
if(xmlMedicalDeviceType.getStudyDevice() != null){
StudyDevice studyDevice = new StudyDevice();
if(xmlMedicalDeviceType.getStudyDevice().getDevice() != null){
Device device = new Device();
device.setType(xmlMedicalDeviceType.getStudyDevice().getDevice().getType());
device.setBrandName(xmlMedicalDeviceType.getStudyDevice().getDevice().getBrandName());
device.setCommonName(xmlMedicalDeviceType.getStudyDevice().getDevice().getCommonName());
studyDevice.setDevice(device);
studyDevice.setCatalogNumber(xmlMedicalDeviceType.getStudyDevice().getCatalogNumber());
studyDevice.setModelNumber(xmlMedicalDeviceType.getStudyDevice().getModelNumber());
studyDevice.setManufacturerName(xmlMedicalDeviceType.getStudyDevice().getManufacturerName());
studyDevice.setManufacturerCity(xmlMedicalDeviceType.getStudyDevice().getManufacturerCity());
studyDevice.setManufacturerState(xmlMedicalDeviceType.getStudyDevice().getManufacturerState());
} else {
studyDevice.setOtherBrandName(xmlMedicalDeviceType.getStudyDevice().getOtherBrandName());
studyDevice.setOtherCommonName(xmlMedicalDeviceType.getStudyDevice().getOtherCommonName());
studyDevice.setOtherDeviceType(xmlMedicalDeviceType.getStudyDevice().getOtherDeviceType());
}
medicalDevice.setStudyDevice(studyDevice);
}
if(xmlMedicalDeviceType.getLotNumber() != null){
medicalDevice.setLotNumber(xmlMedicalDeviceType.getLotNumber());
}
if(xmlMedicalDeviceType.getReturnedDate() != null){
medicalDevice.setReturnedDate(xmlMedicalDeviceType.getReturnedDate().toGregorianCalendar().getTime());
}
if(xmlMedicalDeviceType.getExpirationDate() != null){
medicalDevice.setExpirationDate(xmlMedicalDeviceType.getExpirationDate().toGregorianCalendar().getTime());
}
return medicalDevice;
}
protected MedicalDevice convertMedicalDeviceRef(MedicalDeviceRefType xmlMedicalDeviceRefType){
MedicalDevice medicalDevice = new MedicalDevice();
StudyDevice studyDevice = new StudyDevice();
Device device = new Device();
if(xmlMedicalDeviceRefType.getStudyDeviceRef().getDevice().getType() != null){
device.setType(xmlMedicalDeviceRefType.getStudyDeviceRef().getDevice().getType());
}
device.setBrandName(xmlMedicalDeviceRefType.getStudyDeviceRef().getDevice().getBrandName());
device.setCommonName(xmlMedicalDeviceRefType.getStudyDeviceRef().getDevice().getCommonName());
studyDevice.setDevice(device);
medicalDevice.setStudyDevice(studyDevice);
return medicalDevice;
}
protected ParticipantHistory convertParticipantHistory(ParticipantHistoryType xmlParticipantHistoryType){
ParticipantHistory history = new ParticipantHistory();
history.setBaselinePerformanceStatus(xmlParticipantHistoryType.getBaselinePerformanceStatus());
if(xmlParticipantHistoryType.getHeight() != null){
Measure height = new Measure();
if(xmlParticipantHistoryType.getHeight().getCode() != null){
height.setCode(xmlParticipantHistoryType.getHeight().getCode());
}
height.setQuantity(xmlParticipantHistoryType.getHeight().getQuantity());
height.setUnit(xmlParticipantHistoryType.getHeight().getUnit());
history.setHeight(height);
}
if(xmlParticipantHistoryType.getWeight() != null){
Measure weight = new Measure();
if(xmlParticipantHistoryType.getWeight().getCode() != null){
weight.setCode(xmlParticipantHistoryType.getWeight().getCode());
}
weight.setQuantity(xmlParticipantHistoryType.getWeight().getQuantity());
weight.setUnit(xmlParticipantHistoryType.getWeight().getUnit());
history.setWeight(weight);
}
return history;
}
// convert interventions
protected RadiationIntervention convertRadiationIntervention(RadiationInterventionType xmlRadiationInterventionType){
RadiationIntervention intervention = new RadiationIntervention();
intervention.setAdjustment(xmlRadiationInterventionType.getAdjustment());
intervention.setDaysElapsed(String.valueOf(xmlRadiationInterventionType.getDaysElapsed()));
intervention.setDosage(String.valueOf(xmlRadiationInterventionType.getDosage()));
intervention.setDosageUnit(String.valueOf(xmlRadiationInterventionType.getDosageUnit()));
if(xmlRadiationInterventionType.getLastTreatmentDate() != null){
intervention.setLastTreatmentDate(xmlRadiationInterventionType.getLastTreatmentDate().toGregorianCalendar().getTime());
}
intervention.setFractionNumber(String.valueOf(xmlRadiationInterventionType.getFractionNumber()));
intervention.setAdjustment(xmlRadiationInterventionType.getAdjustment());
if(xmlRadiationInterventionType.getOtherIntervention() != null){
OtherIntervention otherIntervention =convertOtherIntervention(xmlRadiationInterventionType.getOtherIntervention());
intervention.setStudyRadiation(otherIntervention);
}
if(xmlRadiationInterventionType.getAdministration() != null) {
intervention.setAdministration(RadiationAdministration.findByDisplayName(xmlRadiationInterventionType.getAdministration().value()));
}
return intervention;
}
protected RadiationIntervention convertRadiationInterventionRef(RadiationInterventionRefType xmlRadiationInterventionRefType){
RadiationIntervention intervention = new RadiationIntervention();
intervention.setLastTreatmentDate(xmlRadiationInterventionRefType.getLastTreatmentDate().toGregorianCalendar().getTime());
intervention.setAdministration(RadiationAdministration.findByDisplayName(xmlRadiationInterventionRefType.getAdministration().value()));
return intervention;
}
protected OtherIntervention convertOtherIntervention(OtherInterventionType xmlOtherInterventionType){
OtherIntervention otherIntervention = new OtherIntervention();
otherIntervention.setName(xmlOtherInterventionType.getName());
otherIntervention.setDescription(xmlOtherInterventionType.getDescription());
return otherIntervention;
}
protected SurgeryIntervention convertSurgeryIntervention(SurgeryInterventionType xmlSurgeryInterventionType){
SurgeryIntervention intervention = new SurgeryIntervention();
if(xmlSurgeryInterventionType.getInterventionDate() != null){
intervention.setInterventionDate(xmlSurgeryInterventionType.getInterventionDate().toGregorianCalendar().getTime());
}
if(xmlSurgeryInterventionType.getInterventionSite() != null){
InterventionSite interventionSite = new InterventionSite();
interventionSite.setName(xmlSurgeryInterventionType.getInterventionSite().getName());
intervention.setInterventionSite(interventionSite);
}
return intervention;
}
protected BiologicalIntervention convertBiologicalIntervention(BiologicalInterventionType xmlBiologicalInterventionType){
BiologicalIntervention intervention = new BiologicalIntervention();
intervention.setDescription(xmlBiologicalInterventionType.getDescription());
if(xmlBiologicalInterventionType.getOtherIntervention() != null){
OtherIntervention otherIntervention = convertOtherIntervention(xmlBiologicalInterventionType.getOtherIntervention());
intervention.setStudyIntervention(otherIntervention);
}
return intervention;
}
protected DietarySupplementIntervention convertDietarySupplementIntervention(DietarySupplementInterventionType xmlDietarySupplementInterventionType){
DietarySupplementIntervention intervention = new DietarySupplementIntervention();
intervention.setDescription(xmlDietarySupplementInterventionType.getDescription());
if(xmlDietarySupplementInterventionType.getOtherIntervention() != null){
OtherIntervention otherIntervention = convertOtherIntervention(xmlDietarySupplementInterventionType.getOtherIntervention());
intervention.setStudyIntervention(otherIntervention);
}
return intervention;
}
protected DiseaseHistory convertDiseaseHistory(DiseaseHistoryType xmlDiseaseHistoryType){
DiseaseHistory diseaseHistory = new DiseaseHistory();
DiseaseTerm dt = new DiseaseTerm();
dt.setTerm(xmlDiseaseHistoryType.getPrimaryDisease());
// Setting the Abstract study Disease as Ctep Study as the Study details are not provided in the input.
diseaseHistory.setAbstractStudyDisease(new CtepStudyDisease());
diseaseHistory.getAbstractStudyDisease().setTerm(dt) ;
diseaseHistory.setOtherPrimaryDisease(xmlDiseaseHistoryType.getOtherPrimaryDisease());
if (xmlDiseaseHistoryType.getMetastaticDiseaseSite() != null){
for(MetastaticDiseaseSiteType metastaticDiseaseSite : xmlDiseaseHistoryType.getMetastaticDiseaseSite()){
diseaseHistory.addMetastaticDiseaseSite(convertMestastaticDiseaseSite(metastaticDiseaseSite));
}
}
AnatomicSite anatomicSite = new AnatomicSite();
anatomicSite.setName(xmlDiseaseHistoryType.getCodedPrimaryDiseaseSite());
diseaseHistory.setCodedPrimaryDiseaseSite(anatomicSite);
diseaseHistory.setOtherPrimaryDiseaseSite(xmlDiseaseHistoryType.getOtherPrimaryDiseaseSite());
if(xmlDiseaseHistoryType.getDiagnosisDate() != null){
diseaseHistory.setDiagnosisDate(convertDateValue(xmlDiseaseHistoryType.getDiagnosisDate()));
}
return diseaseHistory;
}
protected DiseaseHistory convertDiseaseHistoryRef(DiseaseHistoryRefType xmlDiseaseHistoryRefType){
DiseaseHistory diseaseHistory = new DiseaseHistory();
if(xmlDiseaseHistoryRefType.getPrimaryDisease() != null){
DiseaseTerm dt = new DiseaseTerm();
dt.setTerm(xmlDiseaseHistoryRefType.getPrimaryDisease());
diseaseHistory.setAbstractStudyDisease(new CtepStudyDisease());
diseaseHistory.getAbstractStudyDisease().setTerm(dt) ;
} else if (xmlDiseaseHistoryRefType.getOtherPrimaryDisease() != null){
diseaseHistory.setOtherPrimaryDisease(xmlDiseaseHistoryRefType.getOtherPrimaryDisease());
}
return diseaseHistory;
}
protected DateValue convertDateValue(DateValueType xmlDateValueType){
DateValue dateValue = new DateValue();
dateValue.setDay(xmlDateValueType.getDay());
dateValue.setMonth(xmlDateValueType.getMonth());
dateValue.setYear(xmlDateValueType.getYear());
if(xmlDateValueType.getZone() != null){
dateValue.setZone(xmlDateValueType.getZone());
}
return dateValue;
}
protected MetastaticDiseaseSite convertMestastaticDiseaseSite(MetastaticDiseaseSiteType xmlMetastaticDiseaseSiteType){
MetastaticDiseaseSite site = new MetastaticDiseaseSite();
if (xmlMetastaticDiseaseSiteType.getCodedSite() != null){
AnatomicSite anatomicSite = new AnatomicSite();
anatomicSite.setName(xmlMetastaticDiseaseSiteType.getCodedSite().getName());
if(xmlMetastaticDiseaseSiteType.getCodedSite().getCategory() != null){
anatomicSite.setCategory(xmlMetastaticDiseaseSiteType.getCodedSite().getCategory());
}
site.setCodedSite(anatomicSite);
}
if(xmlMetastaticDiseaseSiteType.getOtherSite() != null){
site.setOtherSite(xmlMetastaticDiseaseSiteType.getOtherSite());
}
return site;
}
protected AdverseEventResponseDescription convertAdverseEventResponseDescription(AdverseEventResponseDescriptionType xmlAdverseEventResponseDescriptionType){
AdverseEventResponseDescription adverseEventResponseDescription = new AdverseEventResponseDescription();
if(xmlAdverseEventResponseDescriptionType.isRetreated() != null){
adverseEventResponseDescription.setRetreated(xmlAdverseEventResponseDescriptionType.isRetreated());
}
if(xmlAdverseEventResponseDescriptionType.isAutopsyPerformed() != null){
adverseEventResponseDescription.setAutopsyPerformed(xmlAdverseEventResponseDescriptionType.isAutopsyPerformed());
}
adverseEventResponseDescription.setEventDescription(xmlAdverseEventResponseDescriptionType.getEventDescription());
if(xmlAdverseEventResponseDescriptionType.getRecoveryDate() != null){
adverseEventResponseDescription.setRecoveryDate(xmlAdverseEventResponseDescriptionType.getRecoveryDate().toGregorianCalendar().getTime());
}
if(xmlAdverseEventResponseDescriptionType.getDateRemovedFromProtocol() != null){
adverseEventResponseDescription.setDateRemovedFromProtocol(xmlAdverseEventResponseDescriptionType.getDateRemovedFromProtocol().toGregorianCalendar().getTime());
}
adverseEventResponseDescription.setRetreated(xmlAdverseEventResponseDescriptionType.isRetreated());
if(xmlAdverseEventResponseDescriptionType.getPresentStatus() != null){
adverseEventResponseDescription.setPresentStatus(PostAdverseEventStatus.valueOf(xmlAdverseEventResponseDescriptionType.getPresentStatus().name()));
}
if(xmlAdverseEventResponseDescriptionType.getEventAbate() != null){
adverseEventResponseDescription.setEventAbate(EventStatus.valueOf(xmlAdverseEventResponseDescriptionType.getEventAbate()));
}
if(xmlAdverseEventResponseDescriptionType.getEventReappear() != null){
adverseEventResponseDescription.setEventReappear(EventStatus.valueOf(xmlAdverseEventResponseDescriptionType.getEventReappear()));
}
if(xmlAdverseEventResponseDescriptionType.getPrimaryTreatmentApproximateTime() != null){
TimeValue primaryTreatmentApproximateTime = new TimeValue();
primaryTreatmentApproximateTime.setHour(xmlAdverseEventResponseDescriptionType.getPrimaryTreatmentApproximateTime().getHour());
primaryTreatmentApproximateTime.setMinute(xmlAdverseEventResponseDescriptionType.getPrimaryTreatmentApproximateTime().getMinute());
primaryTreatmentApproximateTime.setType(xmlAdverseEventResponseDescriptionType.getPrimaryTreatmentApproximateTime().getType());
}
return adverseEventResponseDescription;
}
protected Reporter convertReporter(ReporterType xmlReporterType){
Reporter reporter = new Reporter();
reporter.setFirstName(xmlReporterType.getFirstName());
reporter.setLastName(xmlReporterType.getLastName());
reporter.setMiddleName(xmlReporterType.getMiddleName());
if(xmlReporterType.getNciIdentifier() != null){
ResearchStaff staff = new LocalResearchStaff();
staff.setNciIdentifier(xmlReporterType.getNciIdentifier());
}
Address address = new Address();
address.setStreet(xmlReporterType.getStreet());
address.setCity(xmlReporterType.getCity());
address.setCountry(xmlReporterType.getCountry());
address.setState(xmlReporterType.getState());
address.setZip(xmlReporterType.getZip());
reporter.setAddress(address);
if(xmlReporterType.getContactMechanism() != null){
reporter.setEmailAddress(getEmail(xmlReporterType.getContactMechanism()));
reporter.setPhoneNumber(getPhone(xmlReporterType.getContactMechanism()));
reporter.setFax(getFax(xmlReporterType.getContactMechanism()));
reporter.setFaxNumber(getFax(xmlReporterType.getContactMechanism()));
}
return reporter;
}
protected Submitter convertSubmitter(SubmitterType xmlSubmitterType){
Submitter submitter = new Submitter();
submitter.setFirstName(xmlSubmitterType.getFirstName());
submitter.setLastName(xmlSubmitterType.getLastName());
submitter.setMiddleName(xmlSubmitterType.getMiddleName());
if(xmlSubmitterType.getNciIdentifier() != null){
ResearchStaff staff = new LocalResearchStaff();
staff.setNciIdentifier(xmlSubmitterType.getNciIdentifier());
}
Address address = new Address();
address.setStreet(xmlSubmitterType.getStreet());
address.setCity(xmlSubmitterType.getCity());
address.setCountry(xmlSubmitterType.getCountry());
address.setState(xmlSubmitterType.getState());
address.setZip(xmlSubmitterType.getZip());
submitter.setAddress(address);
if(xmlSubmitterType.getContactMechanism() != null){
submitter.setEmailAddress(getEmail(xmlSubmitterType.getContactMechanism()));
submitter.setPhoneNumber(getPhone(xmlSubmitterType.getContactMechanism()));
submitter.setFax(getFax(xmlSubmitterType.getContactMechanism()));
submitter.setFaxNumber(getFax(xmlSubmitterType.getContactMechanism()));
}
return submitter;
}
protected Physician convertPhysician(PhysicianType xmlPhysicianType){
Physician physician = new Physician();
physician.setFirstName(xmlPhysicianType.getFirstName());
physician.setLastName(xmlPhysicianType.getLastName());
physician.setMiddleName(xmlPhysicianType.getMiddleName());
if(xmlPhysicianType.getNciIdentifier() != null){
Investigator investigator = new LocalInvestigator();
investigator.setNciIdentifier(xmlPhysicianType.getNciIdentifier());
}
Address address = new Address();
address.setStreet(xmlPhysicianType.getStreet());
address.setCity(xmlPhysicianType.getCity());
address.setCountry(xmlPhysicianType.getCountry());
address.setState(xmlPhysicianType.getState());
address.setZip(xmlPhysicianType.getZip());
physician.setAddress(address);
if(xmlPhysicianType.getContactMechanism() != null){
physician.setEmailAddress(getEmail(xmlPhysicianType.getContactMechanism()));
physician.setPhoneNumber(getPhone(xmlPhysicianType.getContactMechanism()));
physician.setFax(getFax(xmlPhysicianType.getContactMechanism()));
}
return physician;
}
protected AdverseEventReportingPeriod convertAdverseEventReportingPeriod(AdverseEventReportingPeriodType reportingPeriodType){
AdverseEventReportingPeriod reportingPeriod = new AdverseEventReportingPeriod();
if(reportingPeriodType.getStudyParticipantAssignmentRef() != null){
reportingPeriod.setAssignment(convertStudyParticipantAssignmentRef(reportingPeriodType.getStudyParticipantAssignmentRef()));
}
if(reportingPeriodType.getTreatmentAssignment() != null){
TreatmentAssignment treatmentAssignment = new TreatmentAssignment();
treatmentAssignment.setCode(reportingPeriodType.getTreatmentAssignment().getCode());
if(reportingPeriodType.getTreatmentAssignment().getComments() != null){
treatmentAssignment.setComments(reportingPeriodType.getTreatmentAssignment().getComments());
}
treatmentAssignment.setDescription(reportingPeriodType.getTreatmentAssignment().getDescription());
treatmentAssignment.setDoseLevelOrder(reportingPeriodType.getTreatmentAssignment().getDoseLevelOrder());
reportingPeriod.setTreatmentAssignment(treatmentAssignment);
}
if(reportingPeriodType.getTreatmentAssignmentDescription() != null){
reportingPeriod.setTreatmentAssignmentDescription(reportingPeriodType.getTreatmentAssignmentDescription());
}
if(reportingPeriodType.getStartDate() != null){
reportingPeriod.setStartDate(reportingPeriodType.getStartDate().toGregorianCalendar().getTime());
}
if(reportingPeriodType.getCycleNumber() != null){
reportingPeriod.setCycleNumber(reportingPeriodType.getCycleNumber());
}
return reportingPeriod;
}
protected StudyParticipantAssignment convertStudyParticipantAssignment(StudyParticipantAssignmentType assignmentType) {
StudyParticipantAssignment assignment= new StudyParticipantAssignment();
assignment.setStudySubjectIdentifier(assignmentType.getStudySubjectIdentifier());
assignment.setDateOfEnrollment(XMLUtil.toDate(assignmentType.getDateOfEnrollment()));
assignment.setStartDateOfFirstCourse(XMLUtil.toDate(assignmentType.getStartDateOfFirstCourse()));
if(assignmentType.getParticipant() != null) {
assignment.setParticipant(convertParticipant(assignmentType.getParticipant()));
assignment.getParticipant().getAssignments().add(assignment);
}
if(assignmentType.getStudySite() != null)
assignment.setStudySite(convertStudySite(assignmentType.getStudySite()));
return assignment;
}
protected StudyParticipantAssignment convertStudyParticipantAssignmentRef(StudyParticipantAssignmentRefType assignmentType) {
StudyParticipantAssignment assignment= new StudyParticipantAssignment();
assignment.setStudySubjectIdentifier(assignmentType.getStudySubjectIdentifier());
if(assignmentType.getStudySiteRef() != null)
assignment.setStudySite(convertStudySiteRef(assignmentType.getStudySiteRef()));
return assignment;
}
protected Participant convertParticipant(ParticipantType xmlParticipantType){
Participant participant = new Participant();
try{
participant.setFirstName(xmlParticipantType.getFirstName());
participant.setLastName(xmlParticipantType.getLastName());
participant.setMiddleName(xmlParticipantType.getMiddleName());
participant.setMaidenName(xmlParticipantType.getMaidenName());
if(xmlParticipantType.getBirthDate() != null){
DateValue dateOfBirth = new DateValue(xmlParticipantType.getBirthDate().getDay(),xmlParticipantType.getBirthDate().getMonth(),xmlParticipantType.getBirthDate().getYear());
participant.setDateOfBirth(dateOfBirth);
}else{
if(xmlParticipantType.getBirthYear() != null){
DateValue dateOfBirth = new DateValue(null,xmlParticipantType.getBirthMonth().intValue(),xmlParticipantType.getBirthYear().intValue());
participant.setDateOfBirth(dateOfBirth);
}
}
if(xmlParticipantType.getGender() != null){
participant.setGender(xmlParticipantType.getGender().value());
}
if(xmlParticipantType.getRace() != null){
participant.setRace(xmlParticipantType.getRace().value());
}
if(xmlParticipantType.getEthnicity() != null){
participant.setEthnicity(xmlParticipantType.getEthnicity().value());
}
//Populate Identifiers
convertIdentifierTypesToDomainIdentifiers(xmlParticipantType.getIdentifiers(),participant.getIdentifiers());
}catch(Exception e){
throw new CaaersSystemException("Exception while converting XML participant to domain participant",e);
}
return participant;
}
protected void convertIdentifierTypesToDomainIdentifiers(Identifiers identifierTypes, List<Identifier> identifiers) throws Exception{
if(identifierTypes != null){
List<OrganizationAssignedIdentifierType> orgAssignedIdList = identifierTypes.getOrganizationAssignedIdentifier();
if(orgAssignedIdList != null && !orgAssignedIdList.isEmpty()){
for(OrganizationAssignedIdentifierType organizationAssignedIdentifierType : orgAssignedIdList){
identifiers.add(convertOrganizationIdentifierTypeToDomainIdentifier(organizationAssignedIdentifierType));
}
}
}
}
protected OrganizationAssignedIdentifier convertOrganizationIdentifierTypeToDomainIdentifier(OrganizationAssignedIdentifierType identifierType) throws Exception{
Organization organization = new LocalOrganization();
OrganizationAssignedIdentifier orgIdentifier = new OrganizationAssignedIdentifier();
orgIdentifier.setType(identifierType.getType().value());
orgIdentifier.setValue(identifierType.getValue());
orgIdentifier.setPrimaryIndicator(identifierType.isPrimaryIndicator());
organization.setName(identifierType.getOrganizationRef().getName());
organization.setNciInstituteCode(identifierType.getOrganizationRef().getNciInstituteCode());
orgIdentifier.setOrganization(organization);
return orgIdentifier;
}
protected StudySite convertStudySite(StudySiteType studySiteType) {
StudySite studySite = new StudySite();
studySite.setOrganization(convertOrganization(studySiteType.getOrganization()));
studySite.setStudy(convertStudy(studySiteType.getStudyRef()));
return studySite;
}
protected StudySite convertStudySiteRef(StudySiteRefType studySiteType) {
StudySite studySite = new StudySite();
studySite.setStudy(convertStudy(studySiteType.getStudyRef()));
Organization organization = new LocalOrganization();
organization.setNciInstituteCode(studySiteType.getNciInstituteCode());
studySite.setOrganization(organization);
return studySite;
}
protected Organization convertOrganization(OrganizationType xmlOrganizationType){
LocalOrganization organization = new LocalOrganization();
organization.setName(xmlOrganizationType.getName());
organization.setNciInstituteCode(xmlOrganizationType.getNciInstituteCode());
return organization;
}
protected Study convertStudy(StudyRefType xmlStudyType) {
Identifier identifier = new Identifier();
if ( xmlStudyType.getIdentifiers().getIdentifier().getType() != null) {
identifier.setType(xmlStudyType.getIdentifiers().getIdentifier().getType().value());
}
identifier.setValue(xmlStudyType.getIdentifiers().getIdentifier().getValue());
Study study = fetchStudy(identifier);
return study;
}
protected String getEmail(List<ContactMechanismType> contactMechanisms){
for(ContactMechanismType cm : contactMechanisms){
if(cm.getType().equals(EMAIL)){
return cm.getValue();
}
}
return null;
}
protected String getPhone(List<ContactMechanismType> contactMechanisms){
for(ContactMechanismType cm : contactMechanisms){
if(cm.getType().equals(PHONE)){
return cm.getValue();
}
}
return null;
}
protected String getFax(List<ContactMechanismType> contactMechanisms){
for(ContactMechanismType cm : contactMechanisms){
if(cm.getType().equals(FAX)){
return cm.getValue();
}
}
return null;
}
protected Study fetchStudy(Identifier identifier) {
if (StringUtils.isEmpty(identifier.getValue())) {
throw new CaaersSystemException("WS_SAE_004", messageSource.getMessage("WS_SAE_004", new String[] {}, "",
Locale.getDefault()));
}
Study study = null;
try {
study = studyDao.getByIdentifier(identifier);
} catch (Exception e) {
throw new CaaersSystemException("WS_GEN_001", messageSource.getMessage("WS_GEN_001", new String[] {}, "",
Locale.getDefault()));
}
if (study == null) {
throw new CaaersSystemException("WS_SAE_005", messageSource.getMessage("WS_SAE_005",
new String[] { identifier.getValue() }, "", Locale.getDefault()));
}
return study;
}
}
|
package gov.nih.nci.cagrid.introduce.portal.modification;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.common.portal.BusyDialogRunnable;
import gov.nih.nci.cagrid.common.portal.PortalLookAndFeel;
import gov.nih.nci.cagrid.common.portal.PortalUtils;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.ResourceManager;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.extension.DiscoveryExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionsType;
import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodsType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespacesType;
import gov.nih.nci.cagrid.introduce.beans.namespace.SchemaElementType;
import gov.nih.nci.cagrid.introduce.beans.resource.ResourcePropertiesListType;
import gov.nih.nci.cagrid.introduce.beans.security.ServiceSecurity;
import gov.nih.nci.cagrid.introduce.beans.service.ServiceType;
import gov.nih.nci.cagrid.introduce.codegen.SyncTools;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.extension.ExtensionsLoader;
import gov.nih.nci.cagrid.introduce.info.ServiceInformation;
import gov.nih.nci.cagrid.introduce.portal.common.IntroduceLookAndFeel;
import gov.nih.nci.cagrid.introduce.portal.extension.ServiceModificationUIPanel;
import gov.nih.nci.cagrid.introduce.portal.modification.discovery.NamespaceTypeDiscoveryComponent;
import gov.nih.nci.cagrid.introduce.portal.modification.properties.ServicePropertiesTable;
import gov.nih.nci.cagrid.introduce.portal.modification.security.ServiceSecurityPanel;
import gov.nih.nci.cagrid.introduce.portal.modification.services.ServicesJTree;
import gov.nih.nci.cagrid.introduce.portal.modification.services.methods.MethodViewer;
import gov.nih.nci.cagrid.introduce.portal.modification.services.methods.MethodsTable;
import gov.nih.nci.cagrid.introduce.portal.modification.services.resourceproperties.ModifyResourcePropertiesPanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespaceTypeConfigurePanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespaceTypeTreeNode;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespacesJTree;
import gov.nih.nci.cagrid.introduce.portal.modification.types.SchemaElementTypeConfigurePanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.SchemaElementTypeTreeNode;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.namespace.QName;
import org.projectmobius.portal.GridPortalComponent;
import org.projectmobius.portal.PortalResourceManager;
/**
* @author <A HREF="MAILTO:hastings@bmi.osu.edu">Shannon Hastings </A>
* @author <A HREF="MAILTO:oster@bmi.osu.edu">Scott Oster </A>
*/
public class ModificationViewer extends GridPortalComponent {
private JPanel mainPanel = null;
private JPanel operationsPanel = null;
private JPanel buttonPanel = null;
private JButton cancel = null;
private JPanel selectPanel = null;
private MethodsTable methodsTable = null;
private JScrollPane methodsScrollPane = null;
private File methodsDirectory = null;
private ServiceDescription introService;
private Properties serviceProperties = null;
private JButton addMethodButton = null;
private JButton saveButton = null;
private JButton removeButton = null;
private JButton modifyButton = null;
private JPanel operationsButtonPanel = null;
private JButton undoButton = null;
private boolean dirty = false;
private JTabbedPane contentTabbedPane = null;
private ServiceSecurityPanel securityPanel = null;
private JLabel serviceNameLabel = null;
private JTextField serviceName = null;
private JLabel namespaceLable = null;
private JTextField namespace = null;
private JLabel lastSavedLabel = null;
private JTextField lastSaved = null;
private JLabel saveLocationLabel = null;
private JTextField saveLocation = null;
private JPanel discoveryPanel = null;
private JPanel discoveryButtonPanel = null;
private JButton namespaceAddButton = null;
private JButton namespaceRemoveButton = null;
private JScrollPane namespaceTableScrollPane = null;
private NamespacesJTree namespaceJTree = null;
private JPanel namespaceTypePropertiesPanel = null;
private NamespaceTypeConfigurePanel namespaceTypeConfigurationPanel = null;
private SchemaElementTypeConfigurePanel schemaElementTypeConfigurationPanel = null;
private ServiceInformation info = null;
private JTabbedPane discoveryTabbedPane = null;
private JPanel namespaceConfPanel = null;
private JPanel servicePropertiesPanel = null;
private JPanel servicePropertiesTableContainerPanel = null;
private JScrollPane servicePropertiesTableScrollPane = null;
private ServicePropertiesTable servicePropertiesTable = null;
private JPanel servicePropertiesControlPanel = null;
private JButton addServiceProperyButton = null;
private JButton removeServicePropertyButton = null;
private JTextField servicePropertyKeyTextField = null;
private JTextField servicePropertyValueTextField = null;
private JLabel servicePropertiesKeyLabel = null;
private JLabel servicePropertiesValueLabel = null;
private JPanel servicePropertiesButtonPanel = null;
private JPanel resourceesTabbedPanel = null;
private JPanel resourcesPanel = null;
private JScrollPane resourcesScrollPane = null;
private ServicesJTree resourcesJTree = null;
private ModifyResourcePropertiesPanel rpHolderPanel = null;
private JSplitPane typesSplitPane = null;
private JButton namespaceReloadButton = null;
/**
* This is the default constructor
*/
public ModificationViewer() {
super();
// throw a thread out so that i can make sure that if the chooser is
// canceled i can dispose of this frame
Thread th = createChooserThread();
th.start();
}
public ModificationViewer(File methodsDirectory) {
super();
this.methodsDirectory = methodsDirectory;
try {
initialize();
} catch (Exception e) {
// should never get here but in case.....
e.printStackTrace();
}
}
private Thread createChooserThread() {
Thread th = new Thread() {
public void run() {
try {
chooseService();
} catch (Exception e) {
e.printStackTrace();
}
if (methodsDirectory == null) {
ModificationViewer.this.dispose();
return;
}
File file = new File(methodsDirectory.getAbsolutePath() + File.separator + "introduce.xml");
if (file.exists() && file.canRead()) {
try {
initialize();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this, e.getMessage());
ModificationViewer.this.dispose();
}
} else {
JOptionPane.showMessageDialog(ModificationViewer.this, "Directory "
+ methodsDirectory.getAbsolutePath() + " does not seem to be an introduce service");
ModificationViewer.this.dispose();
}
}
};
return th;
}
private void loadServiceProps() {
try {
serviceProperties = new Properties();
serviceProperties.load(new FileInputStream(this.methodsDirectory.getAbsolutePath() + File.separator
+ IntroduceConstants.INTRODUCE_PROPERTIES_FILE));
serviceProperties.setProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR, methodsDirectory
.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void chooseService() throws Exception {
String dir = ResourceManager.promptDir(this, null);
if (dir != null) {
this.methodsDirectory = new File(dir);
}
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() throws Exception {
if (this.methodsDirectory != null) {
this.introService = (ServiceDescription) Utils.deserializeDocument(this.methodsDirectory.getAbsolutePath()
+ File.separator + "introduce.xml", ServiceDescription.class);
if (introService.getIntroduceVersion() == null
|| !introService.getIntroduceVersion().equals(IntroduceConstants.INTRODUCE_VERSION)) {
throw new Exception(
"Introduce version in project does not match version provided by Introduce Toolkit ( "
+ IntroduceConstants.INTRODUCE_VERSION + " ): " + introService.getIntroduceVersion());
}
loadServiceProps();
this.info = new ServiceInformation(introService, serviceProperties, methodsDirectory);
this.setContentPane(getMainPanel());
this.setTitle("Modify Service Interface");
this.setFrameIcon(IntroduceLookAndFeel.getModifyIcon());
this.pack();
}
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getMainPanel() {
if (mainPanel == null) {
GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
gridBagConstraints13.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints13.weighty = 1.0;
gridBagConstraints13.gridx = 0;
gridBagConstraints13.gridy = 1;
gridBagConstraints13.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints13.weightx = 1.0;
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints11.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints11.gridheight = 0;
gridBagConstraints11.gridwidth = 0;
gridBagConstraints11.gridx = 0;
gridBagConstraints11.gridy = 3;
gridBagConstraints11.weighty = 1.0D;
gridBagConstraints11.fill = java.awt.GridBagConstraints.HORIZONTAL;
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
gridBagConstraints2.gridx = 0;
gridBagConstraints2.gridy = 2;
gridBagConstraints2.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints2.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints2.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints3.gridx = 0;
gridBagConstraints3.gridy = 0;
gridBagConstraints3.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints3.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints3.fill = java.awt.GridBagConstraints.HORIZONTAL;
mainPanel.add(getButtonPanel(), gridBagConstraints2);
mainPanel.add(getSelectPanel(), gridBagConstraints3);
mainPanel.add(getContentTabbedPane(), gridBagConstraints13);
}
return mainPanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing. gridBagConstraints41.gridx = 1; JPanel
*/
private JPanel getMethodsPanel() {
if (operationsPanel == null) {
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints.gridy = 0;
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
operationsPanel = new JPanel();
operationsPanel.setLayout(new GridBagLayout());
gridBagConstraints4.weightx = 1.0;
gridBagConstraints4.weighty = 1.0;
gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints4.gridwidth = 2;
gridBagConstraints4.gridx = 0;
gridBagConstraints4.gridy = 0;
operationsPanel.add(getMethodsScrollPane(), gridBagConstraints4);
operationsPanel.add(getMethodsButtonPanel(), gridBagConstraints);
}
return operationsPanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getButtonPanel() {
if (buttonPanel == null) {
GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
gridBagConstraints10.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints10.gridy = 0;
gridBagConstraints10.fill = java.awt.GridBagConstraints.NONE;
gridBagConstraints10.gridx = 2;
GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
gridBagConstraints9.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints9.gridy = 0;
gridBagConstraints9.gridx = 1;
GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
gridBagConstraints8.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints8.gridy = 0;
gridBagConstraints8.gridx = 0;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.add(getUndoButton(), gridBagConstraints8);
buttonPanel.add(getSaveButton(), gridBagConstraints9);
buttonPanel.add(getCancel(), gridBagConstraints10);
}
return buttonPanel;
}
/**
* This method initializes jButton1
*
* @return javax.swing.JButton
*/
private JButton getCancel() {
if (cancel == null) {
cancel = new JButton(PortalLookAndFeel.getCloseIcon());
cancel.setText("Cancel");
cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dispose();
}
});
}
return cancel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getSelectPanel() {
if (selectPanel == null) {
GridBagConstraints gridBagConstraints24 = new GridBagConstraints();
gridBagConstraints24.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints24.gridy = 1;
gridBagConstraints24.weightx = 1.0;
gridBagConstraints24.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints24.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints24.gridx = 3;
GridBagConstraints gridBagConstraints23 = new GridBagConstraints();
gridBagConstraints23.gridx = 2;
gridBagConstraints23.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints23.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints23.gridy = 1;
saveLocationLabel = new JLabel();
saveLocationLabel.setText("Location");
saveLocationLabel.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
gridBagConstraints22.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints22.gridy = 1;
gridBagConstraints22.weightx = 1.0;
gridBagConstraints22.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints22.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints22.gridx = 1;
GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
gridBagConstraints21.gridx = 0;
gridBagConstraints21.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints21.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints21.gridy = 1;
lastSavedLabel = new JLabel();
lastSavedLabel.setText("Last Saved");
lastSavedLabel.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints20 = new GridBagConstraints();
gridBagConstraints20.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints20.gridy = 0;
gridBagConstraints20.weightx = 1.0;
gridBagConstraints20.gridx = 3;
gridBagConstraints20.insets = new java.awt.Insets(2, 2, 2, 2);
GridBagConstraints gridBagConstraints19 = new GridBagConstraints();
gridBagConstraints19.gridx = 2;
gridBagConstraints19.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints19.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints19.gridy = 0;
namespaceLable = new JLabel();
namespaceLable.setText("Namespace");
namespaceLable.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints18 = new GridBagConstraints();
gridBagConstraints18.gridx = 0;
gridBagConstraints18.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints18.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints18.gridy = 0;
GridBagConstraints gridBagConstraints17 = new GridBagConstraints();
gridBagConstraints17.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints17.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints17.gridx = 1;
gridBagConstraints17.gridy = 0;
gridBagConstraints17.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints17.weightx = 1.0;
serviceNameLabel = new JLabel();
serviceNameLabel.setText("Service Name");
serviceNameLabel.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 12));
selectPanel = new JPanel();
selectPanel.setLayout(new GridBagLayout());
selectPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Properties",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION, null, PortalLookAndFeel.getPanelLabelColor()));
selectPanel.add(serviceNameLabel, gridBagConstraints18);
selectPanel.add(getServiceName(), gridBagConstraints17);
selectPanel.add(namespaceLable, gridBagConstraints19);
selectPanel.add(getNamespace(), gridBagConstraints20);
selectPanel.add(lastSavedLabel, gridBagConstraints21);
selectPanel.add(getLastSaved(), gridBagConstraints22);
selectPanel.add(saveLocationLabel, gridBagConstraints23);
selectPanel.add(getSaveLocation(), gridBagConstraints24);
}
return selectPanel;
}
/**
* This method initializes jTable
*
* @return javax.swing.JTable
*/
private MethodsTable getMethodsTable() {
if (methodsTable == null) {
methodsTable = new MethodsTable(introService.getServices().getService(0), this.methodsDirectory,
this.serviceProperties);
methodsTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
dirty = true;
performMethodModify();
}
}
});
}
return methodsTable;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getMethodsScrollPane() {
if (methodsScrollPane == null) {
methodsScrollPane = new JScrollPane();
methodsScrollPane.setViewportView(getMethodsTable());
}
return methodsScrollPane;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getAddMethodButton() {
if (addMethodButton == null) {
addMethodButton = new JButton(PortalLookAndFeel.getAddIcon());
addMethodButton.setText("Add");
addMethodButton.setToolTipText("add new operation");
addMethodButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
MethodType method = new MethodType();
method.setName("newMethod");
MethodTypeOutput output = new MethodTypeOutput();
output.setQName(new QName("", "void"));
method.setOutput(output);
getMethodsTable().addRow(method);
performMethodModify();
}
});
}
return addMethodButton;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getSaveButton() {
if (saveButton == null) {
saveButton = new JButton(PortalLookAndFeel.getSaveIcon());
saveButton.setText("Save");
saveButton.setToolTipText("modify and rebuild service");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
saveModifications();
}
});
}
return saveButton;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getRemoveButton() {
if (removeButton == null) {
removeButton = new JButton(PortalLookAndFeel.getRemoveIcon());
removeButton.setText("Remove");
removeButton.setToolTipText("remove selected operation");
removeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
int row = getMethodsTable().getSelectedRow();
if ((row < 0) || (row >= getMethodsTable().getRowCount())) {
PortalUtils.showErrorMessage("Please select a method to remove.");
return;
}
try {
getMethodsTable().removeSelectedRow();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
return removeButton;
}
private void resetMethodSecurityIfServiceSecurityChanged() throws Exception {
boolean update = false;
ServiceSecurity service = introService.getServices().getService(0).getServiceSecurity();
ServiceSecurity curr = securityPanel.getServiceSecurity();
// This should be cleaned up some
if ((service == null) && (curr == null)) {
update = false;
} else if ((service != null) && (curr == null)) {
update = true;
} else if ((service == null) && (curr != null)) {
update = true;
} else if (!service.equals(curr)) {
update = true;
}
if (update) {
MethodsType mt = this.introService.getServices().getService(0).getMethods();
List changes = new ArrayList();
if (mt != null) {
introService.getServices().getService(0).setServiceSecurity(curr);
MethodType[] methods = mt.getMethod();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if ((methods[i].getMethodSecurity() != null)
&& (!CommonTools.equals(curr, methods[i].getMethodSecurity()))) {
methods[i].setMethodSecurity(null);
changes.add(methods[i].getName());
}
}
}
if (changes.size() > 0) {
StringBuffer sb = new StringBuffer();
sb
.append("Service security configuration changed, the security configurations for the following methods were reset:\n");
for (int i = 0; i < changes.size(); i++) {
String method = (String) changes.get(i);
sb.append(" " + (i + 1) + ") " + method);
}
PortalUtils.showMessage(sb.toString());
}
}
}
}
private void performMethodModify() {
try {
this.resetMethodSecurityIfServiceSecurityChanged();
} catch (Exception e) {
e.printStackTrace();
PortalUtils.showErrorMessage(e);
return;
}
MethodType method = getMethodsTable().getSelectedMethodType();
if (method == null) {
PortalUtils.showErrorMessage("Please select a method to modify.");
return;
}
// TODO: check this.... setting this for now......
MethodViewer mv = new MethodViewer(method, info);
PortalResourceManager.getInstance().getGridPortal().addGridPortalComponent(mv);
// TODO: total hack for now to avoid tryin sort action listerners and
// having to pass the table into the method modification viewer.
mv.getDoneButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread th = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
Thread.yield();
} catch (InterruptedException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
getMethodsTable().sort();
}
});
th.start();
}
});
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getModifyButton() {
if (modifyButton == null) {
modifyButton = new JButton(IntroduceLookAndFeel.getModifyIcon());
modifyButton.setText("Modify");
modifyButton.setToolTipText("modify seleted operation");
modifyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
performMethodModify();
}
});
}
return modifyButton;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getMethodsButtonPanel() {
if (operationsButtonPanel == null) {
GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
gridBagConstraints7.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints7.gridy = 1;
gridBagConstraints7.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints7.gridx = 0;
GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
gridBagConstraints6.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints6.gridy = 2;
gridBagConstraints6.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints6.gridx = 0;
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints5.gridy = 0;
gridBagConstraints5.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints5.gridx = 0;
operationsButtonPanel = new JPanel();
operationsButtonPanel.setLayout(new GridBagLayout());
operationsButtonPanel.add(getAddMethodButton(), gridBagConstraints5);
operationsButtonPanel.add(getModifyButton(), gridBagConstraints6);
operationsButtonPanel.add(getRemoveButton(), gridBagConstraints7);
}
return operationsButtonPanel;
}
/**
* This method initializes undoButton
*
* @return javax.swing.JButton
*/
private JButton getUndoButton() {
if (undoButton == null) {
undoButton = new JButton(IntroduceLookAndFeel.getUndoIcon());
undoButton.setText("Undo");
undoButton.setToolTipText("roll back to last save state");
undoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int decision = JOptionPane.showConfirmDialog(ModificationViewer.this,
"Are you sure you wish to roll back.");
if (decision == JOptionPane.OK_OPTION) {
BusyDialogRunnable r = new BusyDialogRunnable(PortalResourceManager.getInstance()
.getGridPortal(), "Undo") {
public void process() {
System.out.println("Loading in last known save for this project");
try {
if (!dirty) {
setProgressText("restoring from local cache");
ResourceManager.restoreLatest(serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP),
serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME),
serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR));
}
dispose();
PortalResourceManager.getInstance().getGridPortal().addGridPortalComponent(
new ModificationViewer(methodsDirectory));
} catch (Exception e1) {
// e1.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this,
"Unable to roll back, there may be no older versions available");
return;
}
}
};
Thread th = new Thread(r);
th.start();
}
}
});
}
return undoButton;
}
/**
* This method initializes contentTabbedPane
*
* @return javax.swing.JTabbedPane
*/
private JTabbedPane getContentTabbedPane() {
if (contentTabbedPane == null) {
contentTabbedPane = new JTabbedPane();
contentTabbedPane.addTab("Types", null, getTypesSplitPane(), null);
contentTabbedPane.addTab("Operations", null, getMethodsPanel(), null);
contentTabbedPane.addTab("Metadata", null, getRpHolderPanel(), null);
contentTabbedPane.addTab("Service Properties", null, getServicePropertiesPanel(), null);
contentTabbedPane.addTab("Service Contexts", null, getResourceesTabbedPanel(), null);
contentTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
getNamespaceJTree().setNamespaces(info.getNamespaces());
getResourcesJTree().setServices(info.getServices());
getMethodsTable().clearTable();
getMethodsTable().setMethods(info.getServices().getService(0));
getRpHolderPanel().reInitialize(info.getServices().getService(0).getResourcePropertiesList(),
info.getNamespaces());
getServicePropertiesTable().refreshView();
}
});
// diable the metadata tab if they've specified not to sync metadata
ResourcePropertiesListType metadataList = this.introService.getServices().getService(0)
.getResourcePropertiesList();
if (metadataList != null && metadataList.getSynchronizeResourceFramework() != null
&& !metadataList.getSynchronizeResourceFramework().booleanValue()) {
// Disable the tab
contentTabbedPane.setEnabledAt(contentTabbedPane.getTabCount() - 1, false);
}
contentTabbedPane.addTab("Security", null, getSecurityPanel(), null);
// add a tab for each extension...
ExtensionsType exts = introService.getExtensions();
if (exts != null && exts.getExtension() != null) {
ExtensionType[] extsTypes = exts.getExtension();
for (int i = 0; i < extsTypes.length; i++) {
ServiceExtensionDescriptionType extDtype = ExtensionsLoader.getInstance().getServiceExtension(
extsTypes[i].getName());
try {
if (extDtype.getServiceModificationUIPanel() != null
&& !extDtype.getServiceModificationUIPanel().equals("")) {
ServiceModificationUIPanel extPanel = gov.nih.nci.cagrid.introduce.portal.extension.ExtensionTools
.getServiceModificationUIPanel(extDtype.getName(), info);
contentTabbedPane.addTab(extDtype.getDisplayName(), null, extPanel, null);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this, "Cannot load extension: "
+ extDtype.getDisplayName());
}
}
}
}
return contentTabbedPane;
}
/**
* This method initializes securityPanel
*
* @return javax.swing.JPanel
*/
private ServiceSecurityPanel getSecurityPanel() {
if (securityPanel == null) {
try {
securityPanel = new ServiceSecurityPanel(introService.getServices().getService(0).getServiceSecurity());
} catch (Exception e) {
e.printStackTrace();
PortalUtils.showErrorMessage(e);
}
}
return securityPanel;
}
/**
* This method initializes serviceName
*
* @return javax.swing.JTextField
*/
private JTextField getServiceName() {
if (serviceName == null) {
serviceName = new JTextField();
serviceName.setEditable(false);
serviceName.setFont(new java.awt.Font("Dialog", java.awt.Font.ITALIC, 12));
serviceName.setText(serviceProperties.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME));
}
return serviceName;
}
/**
* This method initializes packageName
*
* @return javax.swing.JTextField
*/
private JTextField getNamespace() {
if (namespace == null) {
namespace = new JTextField();
namespace.setText(serviceProperties.getProperty(IntroduceConstants.INTRODUCE_SKELETON_NAMESPACE_DOMAIN));
namespace.setFont(new java.awt.Font("Dialog", java.awt.Font.ITALIC, 12));
namespace.setEditable(false);
}
return namespace;
}
/**
* This method initializes lastSaved
*
* @return javax.swing.JTextField
*/
private JTextField getLastSaved() {
if (lastSaved == null) {
lastSaved = new JTextField();
lastSaved.setEditable(false);
lastSaved.setFont(new java.awt.Font("Dialog", java.awt.Font.ITALIC, 12));
setLastSaved(serviceProperties.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP));
}
return lastSaved;
}
private void setLastSaved(String savedDate) {
Date date;
if (savedDate.equals("0")) {
date = new Date();
} else {
date = new Date(Long.parseLong(savedDate));
}
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
lastSaved.setText(formatter.format(date));
}
/**
* This method initializes location
*
* @return javax.swing.JTextField
*/
private JTextField getSaveLocation() {
if (saveLocation == null) {
saveLocation = new JTextField();
saveLocation.setText(methodsDirectory.getAbsolutePath());
saveLocation.setFont(new java.awt.Font("Dialog", java.awt.Font.ITALIC, 12));
saveLocation.setEditable(false);
}
return saveLocation;
}
/**
* This method initializes discoveryPanel
*
* @return javax.swing.JPanel
*/
private JPanel getDiscoveryPanel() {
if (discoveryPanel == null) {
GridBagConstraints gridBagConstraints27 = new GridBagConstraints();
gridBagConstraints27.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints27.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints27.gridx = 0;
gridBagConstraints27.gridy = 1;
GridBagConstraints gridBagConstraints16 = new GridBagConstraints();
gridBagConstraints16.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints16.weighty = 1.0;
gridBagConstraints16.weightx = 1.0;
gridBagConstraints16.gridx = 0;
gridBagConstraints16.gridy = 0;
gridBagConstraints16.insets = new java.awt.Insets(2, 2, 2, 2);
discoveryPanel = new JPanel();
discoveryPanel.setLayout(new GridBagLayout());
discoveryPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select Type",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
PortalLookAndFeel.getPanelLabelColor()));
discoveryPanel.add(getDiscoveryTabbedPane(), gridBagConstraints16);
discoveryPanel.add(getDiscoveryButtonPanel(), gridBagConstraints27);
}
return discoveryPanel;
}
/**
* This method initializes discoveryButtonPanel
*
* @return javax.swing.JPanel
*/
private JPanel getDiscoveryButtonPanel() {
if (discoveryButtonPanel == null) {
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 2;
gridBagConstraints1.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints1.gridy = 0;
GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
gridBagConstraints31.gridx = 1;
gridBagConstraints31.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints31.gridy = 0;
GridBagConstraints gridBagConstraints30 = new GridBagConstraints();
gridBagConstraints30.gridx = 0;
gridBagConstraints30.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints30.gridy = 0;
discoveryButtonPanel = new JPanel();
discoveryButtonPanel.setLayout(new GridBagLayout());
discoveryButtonPanel.add(getNamespaceAddButton(), gridBagConstraints30);
discoveryButtonPanel.add(getNamespaceRemoveButton(), gridBagConstraints31);
discoveryButtonPanel.add(getNamespaceReloadButton(), gridBagConstraints1);
}
return discoveryButtonPanel;
}
/**
* This method initializes namespaceAddButton
*
* @return javax.swing.JButton
*/
private JButton getNamespaceAddButton() {
if (namespaceAddButton == null) {
namespaceAddButton = new JButton();
namespaceAddButton.setText("Add");
namespaceAddButton.setIcon(PortalLookAndFeel.getAddIcon());
namespaceAddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
NamespaceType type = ((NamespaceTypeDiscoveryComponent) getDiscoveryTabbedPane()
.getSelectedComponent()).createNamespaceType(new File(methodsDirectory
+ File.separator
+ "schema"
+ File.separator
+ info.getIntroduceServiceProperties().getProperty(
IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME)));
if (type != null) {
getNamespaceJTree().addNode(type);
} else {
JOptionPane.showMessageDialog(ModificationViewer.this, "Error retrieving schema.");
}
}
});
}
return namespaceAddButton;
}
/**
* This method initializes namespaceRemoveButton
*
* @return javax.swing.JButton
*/
private JButton getNamespaceRemoveButton() {
if (namespaceRemoveButton == null) {
namespaceRemoveButton = new JButton();
namespaceRemoveButton.setText("Remove");
namespaceRemoveButton.setIcon(PortalLookAndFeel.getRemoveIcon());
namespaceRemoveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
if (getNamespaceJTree().getCurrentNode() instanceof NamespaceTypeTreeNode) {
NamespaceType type = (NamespaceType) getNamespaceJTree().getCurrentNode().getUserObject();
if (!type.getNamespace().equals(IntroduceConstants.W3CNAMESPACE)) {
if (CommonTools.isNamespaceTypeInUse(type, introService)) {
String[] message = {"The namespace " + type.getNamespace(),
"contains types in use by this service."};
JOptionPane.showMessageDialog(ModificationViewer.this, message);
} else {
getNamespaceJTree().removeSelectedNode();
}
} else {
PortalUtils.showMessage("Cannot remove " + IntroduceConstants.W3CNAMESPACE);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(ModificationViewer.this, "Please select namespace to Remove");
}
}
});
}
return namespaceRemoveButton;
}
/**
* This method initializes namespaceTableScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getNamespaceTableScrollPane() {
if (namespaceTableScrollPane == null) {
namespaceTableScrollPane = new JScrollPane();
namespaceTableScrollPane.setViewportView(getNamespaceJTree());
}
return namespaceTableScrollPane;
}
/**
* This method initializes namespaceJTree
*
* @return javax.swing.JTree
*/
private NamespacesJTree getNamespaceJTree() {
if (namespaceJTree == null) {
namespaceJTree = new NamespacesJTree(introService.getNamespaces(), true);
namespaceJTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
DefaultMutableTreeNode node = getNamespaceJTree().getCurrentNode();
if (node instanceof NamespaceTypeTreeNode) {
getNamespaceTypeConfigurationPanel().setNamespaceType(
(NamespaceType) ((NamespaceTypeTreeNode) node).getUserObject());
getSchemaElementTypeConfigurationPanel().clear();
} else if (node instanceof SchemaElementTypeTreeNode) {
NamespaceTypeTreeNode parentNode = (NamespaceTypeTreeNode) node.getParent();
NamespaceType nsType = (NamespaceType) parentNode.getUserObject();
if (nsType.getNamespace().equals(IntroduceConstants.W3CNAMESPACE)) {
getSchemaElementTypeConfigurationPanel().setSchemaElementType(
(SchemaElementType) ((SchemaElementTypeTreeNode) node).getUserObject(), false);
} else {
getSchemaElementTypeConfigurationPanel().setSchemaElementType(
(SchemaElementType) ((SchemaElementTypeTreeNode) node).getUserObject(), true);
}
getNamespaceTypeConfigurationPanel().setNamespaceType(nsType);
} else {
getNamespaceTypeConfigurationPanel().clear();
getSchemaElementTypeConfigurationPanel().clear();
}
}
});
}
return namespaceJTree;
}
/**
* This method initializes namespaceTypePropertiesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespaceTypePropertiesPanel() {
if (namespaceTypePropertiesPanel == null) {
GridBagConstraints gridBagConstraints33 = new GridBagConstraints();
gridBagConstraints33.gridx = 0;
gridBagConstraints33.weightx = 1.0D;
gridBagConstraints33.gridy = 0;
gridBagConstraints33.fill = GridBagConstraints.BOTH;
GridBagConstraints gridBagConstraints34 = new GridBagConstraints();
gridBagConstraints34.gridx = 0;
gridBagConstraints34.weightx = 1.0D;
gridBagConstraints34.gridy = 1;
gridBagConstraints34.fill = GridBagConstraints.BOTH;
namespaceTypePropertiesPanel = new JPanel();
namespaceTypePropertiesPanel.setLayout(new GridBagLayout());
namespaceTypePropertiesPanel.add(getNamespaceTypeConfigurationPanel(), gridBagConstraints33);
namespaceTypePropertiesPanel.add(getSchemaElementTypeConfigurationPanel(), gridBagConstraints34);
}
return namespaceTypePropertiesPanel;
}
/**
* This method initializes namespaceTypeCconfigurationPanel
*
* @return javax.swing.JPanel
*/
private NamespaceTypeConfigurePanel getNamespaceTypeConfigurationPanel() {
if (namespaceTypeConfigurationPanel == null) {
namespaceTypeConfigurationPanel = new NamespaceTypeConfigurePanel();
namespaceTypeConfigurationPanel.setName("namespaceTypeCconfigurationPanel");
}
return namespaceTypeConfigurationPanel;
}
/**
* This method initializes schemaElementTypeConfigurationPanel
*
* @return javax.swing.JPanel
*/
private SchemaElementTypeConfigurePanel getSchemaElementTypeConfigurationPanel() {
if (schemaElementTypeConfigurationPanel == null) {
schemaElementTypeConfigurationPanel = new SchemaElementTypeConfigurePanel();
}
return schemaElementTypeConfigurationPanel;
}
/**
* This method initializes discoveryTabbedPane
*
* @return javax.swing.JTabbedPane
*/
private JTabbedPane getDiscoveryTabbedPane() {
if (discoveryTabbedPane == null) {
discoveryTabbedPane = new JTabbedPane();
List discoveryTypes = ExtensionsLoader.getInstance().getDiscoveryExtensions();
if (discoveryTypes != null) {
for (int i = 0; i < discoveryTypes.size(); i++) {
DiscoveryExtensionDescriptionType dd = (DiscoveryExtensionDescriptionType) discoveryTypes.get(i);
try {
NamespaceTypeDiscoveryComponent comp = gov.nih.nci.cagrid.introduce.portal.extension.ExtensionTools
.getNamespaceTypeDiscoveryComponent(dd.getName());
if (comp != null) {
discoveryTabbedPane.addTab(dd.getDisplayName(), comp);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this, "Error loading discovery type: "
+ dd.getDisplayName());
}
}
}
}
return discoveryTabbedPane;
}
private void saveModifications() {
int confirmed = JOptionPane.showConfirmDialog(ModificationViewer.this, "Are you sure you want to save?",
"Confirm Save", JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.OK_OPTION) {
// verify no needed namespace types have been removed or modified
if (!CommonTools.usedTypesAvailable(introService)) {
Set unavailable = CommonTools.getUnavailableUsedTypes(introService);
String[] message = {"The following schema element types used in the service",
"are not available in the specified namespace types!", "Please add schemas as appropriate.",
"\n"};
String[] err = new String[unavailable.size() + message.length];
System.arraycopy(message, 0, err, 0, message.length);
int index = message.length;
Iterator unavailableIter = unavailable.iterator();
while (unavailableIter.hasNext()) {
err[index] = unavailableIter.next().toString();
index++;
}
JOptionPane.showMessageDialog(ModificationViewer.this, err, "Unavailable types found",
JOptionPane.WARNING_MESSAGE);
return;
}
try {
resetMethodSecurityIfServiceSecurityChanged();
} catch (Exception ex) {
ex.printStackTrace();
PortalUtils.showErrorMessage(ex);
}
BusyDialogRunnable r = new BusyDialogRunnable(PortalResourceManager.getInstance().getGridPortal(), "Save") {
public void process() {
try {
// walk the namespaces and make sure they are valid
setProgressText("validating namespaces");
NamespacesType namespaces = introService.getNamespaces();
if (namespaces != null && namespaces.getNamespace() != null) {
for (int i = 0; i < namespaces.getNamespace().length; i++) {
NamespaceType currentNs = namespaces.getNamespace(i);
if (currentNs.getPackageName() != null) {
if (!CommonTools.isValidPackageName(currentNs.getPackageName())) {
setErrorMessage("Error: Invalid package name for namespace "
+ currentNs.getNamespace() + " : " + currentNs.getPackageName());
return;
}
}
}
}
introService.getServices().getService(0).setServiceSecurity(securityPanel.getServiceSecurity());
// check the methods to make sure they are valid.......
if (introService.getServices() != null && introService.getServices().getService() != null) {
for (int serviceI = 0; serviceI < introService.getServices().getService().length; serviceI++) {
ServiceType service = introService.getServices().getService(serviceI);
if (service.getMethods() != null && service.getMethods().getMethod() != null) {
List methodNames = new ArrayList();
if (service.getMethods() != null && service.getMethods().getMethod() != null) {
for (int methodI = 0; methodI < service.getMethods().getMethod().length; methodI++) {
MethodType method = service.getMethods().getMethod(methodI);
if (!(methodNames.contains(method.getName()))) {
methodNames.add(method.getName());
} else {
setErrorMessage("The service " + service.getName()
+ " has duplicate methods " + method.getName());
return;
}
}
}
}
}
}
// save the metadata and methods and then call the
// resync and build
setProgressText("writting service document");
Utils.serializeDocument(methodsDirectory.getAbsolutePath() + File.separator + "introduce.xml",
introService, IntroduceConstants.INTRODUCE_SKELETON_QNAME);
// call the sync tools
setProgressText("sychronizing skeleton");
SyncTools sync = new SyncTools(methodsDirectory);
sync.sync();
// build the synchronized service
setProgressText("rebuilding skeleton");
String cmd = CommonTools.getAntCommand("clean all", methodsDirectory.getAbsolutePath());
Process p = CommonTools.createAndOutputProcess(cmd);
p.waitFor();
if (p.exitValue() != 0) {
setErrorMessage("Error: Unable to rebuild the skeleton");
return;
}
dirty = false;
setProgressText("loading service properties");
loadServiceProps();
setLastSaved(serviceProperties.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP));
this.setProgressText("");
// reinitialize the GUI with changes from saved model
initialize();
} catch (Exception e1) {
e1.printStackTrace();
setErrorMessage("Error: " + e1.getMessage());
return;
}
}
};
Thread th = new Thread(r);
th.start();
}
}
/**
* This method initializes namespaceConfPanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespaceConfPanel() {
if (namespaceConfPanel == null) {
namespaceConfPanel = new JPanel();
namespaceConfPanel.setLayout(new BoxLayout(namespaceConfPanel, BoxLayout.Y_AXIS));
namespaceConfPanel.add(getDiscoveryPanel());
namespaceConfPanel.add(getNamespaceTypePropertiesPanel());
}
return namespaceConfPanel;
}
/**
* This method initializes servicePropertiesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesPanel() {
if (servicePropertiesPanel == null) {
GridBagConstraints gridBagConstraints26 = new GridBagConstraints();
gridBagConstraints26.gridx = 0;
gridBagConstraints26.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints26.weightx = 1.0D;
gridBagConstraints26.weighty = 1.0D;
gridBagConstraints26.gridy = 0;
GridBagConstraints gridBagConstraints25 = new GridBagConstraints();
gridBagConstraints25.gridx = 0;
gridBagConstraints25.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints25.gridy = 1;
servicePropertiesPanel = new JPanel();
servicePropertiesPanel.setLayout(new GridBagLayout());
servicePropertiesPanel.add(getServicePropertiesTableContainerPanel(), gridBagConstraints26);
servicePropertiesPanel.add(getServicePropertiesControlPanel(), gridBagConstraints25);
}
return servicePropertiesPanel;
}
/**
* This method initializes servicePropertiesTableContainerPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesTableContainerPanel() {
if (servicePropertiesTableContainerPanel == null) {
GridBagConstraints gridBagConstraints28 = new GridBagConstraints();
gridBagConstraints28.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints28.gridx = 0;
gridBagConstraints28.gridy = 0;
gridBagConstraints28.weightx = 1.0;
gridBagConstraints28.weighty = 1.0;
gridBagConstraints28.insets = new java.awt.Insets(5, 5, 5, 5);
servicePropertiesTableContainerPanel = new JPanel();
servicePropertiesTableContainerPanel.setLayout(new GridBagLayout());
servicePropertiesTableContainerPanel.add(getServicePropertiesTableScrollPane(), gridBagConstraints28);
}
return servicePropertiesTableContainerPanel;
}
/**
* This method initializes servicePropertiesTableScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getServicePropertiesTableScrollPane() {
if (servicePropertiesTableScrollPane == null) {
servicePropertiesTableScrollPane = new JScrollPane();
servicePropertiesTableScrollPane.setViewportView(getServicePropertiesTable());
}
return servicePropertiesTableScrollPane;
}
/**
* This method initializes servicePropertiesTable
*
* @return javax.swing.JTable
*/
private ServicePropertiesTable getServicePropertiesTable() {
if (servicePropertiesTable == null) {
servicePropertiesTable = new ServicePropertiesTable(info);
}
return servicePropertiesTable;
}
/**
* This method initializes servicePropertiesControlPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesControlPanel() {
if (servicePropertiesControlPanel == null) {
GridBagConstraints gridBagConstraints42 = new GridBagConstraints();
gridBagConstraints42.gridx = 1;
gridBagConstraints42.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints42.gridwidth = 1;
gridBagConstraints42.gridheight = 4;
gridBagConstraints42.gridy = 0;
GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
gridBagConstraints41.gridx = 0;
gridBagConstraints41.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints41.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints41.gridy = 2;
servicePropertiesValueLabel = new JLabel();
servicePropertiesValueLabel.setText("Default Value:");
GridBagConstraints gridBagConstraints40 = new GridBagConstraints();
gridBagConstraints40.gridx = 0;
gridBagConstraints40.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints40.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints40.gridy = 0;
servicePropertiesKeyLabel = new JLabel();
servicePropertiesKeyLabel.setText("Key:");
GridBagConstraints gridBagConstraints39 = new GridBagConstraints();
gridBagConstraints39.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints39.gridy = 3;
gridBagConstraints39.weightx = 1.0;
gridBagConstraints39.insets = new java.awt.Insets(2, 2, 10, 10);
gridBagConstraints39.gridx = 0;
GridBagConstraints gridBagConstraints38 = new GridBagConstraints();
gridBagConstraints38.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints38.gridy = 1;
gridBagConstraints38.weightx = 1.0;
gridBagConstraints38.insets = new java.awt.Insets(2, 2, 10, 10);
gridBagConstraints38.gridx = 0;
servicePropertiesControlPanel = new JPanel();
servicePropertiesControlPanel.setLayout(new GridBagLayout());
servicePropertiesControlPanel.add(getServicePropertyKeyTextField(), gridBagConstraints38);
servicePropertiesControlPanel.add(getServicePropertyValueTextField(), gridBagConstraints39);
servicePropertiesControlPanel.add(servicePropertiesKeyLabel, gridBagConstraints40);
servicePropertiesControlPanel.add(servicePropertiesValueLabel, gridBagConstraints41);
servicePropertiesControlPanel.add(getServicePropertiesButtonPanel(), gridBagConstraints42);
}
return servicePropertiesControlPanel;
}
/**
* This method initializes addServiceProperyButton
*
* @return javax.swing.JButton
*/
private JButton getAddServiceProperyButton() {
if (addServiceProperyButton == null) {
addServiceProperyButton = new JButton();
addServiceProperyButton.setText("Add");
addServiceProperyButton.setIcon(PortalLookAndFeel.getAddIcon());
addServiceProperyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (getServicePropertyKeyTextField().getText().length() > 0
&& CommonTools.isValidJavaField(getServicePropertyKeyTextField().getText())) {
String key = getServicePropertyKeyTextField().getText();
String value = getServicePropertyValueTextField().getText();
getServicePropertiesTable().addRow(key, value);
} else {
JOptionPane
.showMessageDialog(ModificationViewer.this,
"Service Property key must be a valid java identifier, beginning with a lowercase character.");
}
}
});
}
return addServiceProperyButton;
}
/**
* This method initializes removeServicePropertyButton
*
* @return javax.swing.JButton
*/
private JButton getRemoveServicePropertyButton() {
if (removeServicePropertyButton == null) {
removeServicePropertyButton = new JButton();
removeServicePropertyButton.setText("Remove");
removeServicePropertyButton.setIcon(PortalLookAndFeel.getRemoveIcon());
removeServicePropertyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
getServicePropertiesTable().removeSelectedRow();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
return removeServicePropertyButton;
}
/**
* This method initializes servicePropertyKeyTextField
*
* @return javax.swing.JTextField
*/
private JTextField getServicePropertyKeyTextField() {
if (servicePropertyKeyTextField == null) {
servicePropertyKeyTextField = new JTextField();
}
return servicePropertyKeyTextField;
}
/**
* This method initializes servicePropertyValueTextField
*
* @return javax.swing.JTextField
*/
private JTextField getServicePropertyValueTextField() {
if (servicePropertyValueTextField == null) {
servicePropertyValueTextField = new JTextField();
}
return servicePropertyValueTextField;
}
/**
* This method initializes servicePropertiesButtonPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesButtonPanel() {
if (servicePropertiesButtonPanel == null) {
GridBagConstraints gridBagConstraints37 = new GridBagConstraints();
gridBagConstraints37.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints37.gridy = 0;
gridBagConstraints37.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints37.gridx = 0;
GridBagConstraints gridBagConstraints32 = new GridBagConstraints();
gridBagConstraints32.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints32.gridy = 1;
gridBagConstraints32.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints32.gridx = 0;
servicePropertiesButtonPanel = new JPanel();
servicePropertiesButtonPanel.setLayout(new GridBagLayout());
servicePropertiesButtonPanel.add(getRemoveServicePropertyButton(), gridBagConstraints32);
servicePropertiesButtonPanel.add(getAddServiceProperyButton(), gridBagConstraints37);
}
return servicePropertiesButtonPanel;
}
/**
* This method initializes servicesTabbedPanel
*
* @return javax.swing.JPanel
*/
private JPanel getResourceesTabbedPanel() {
if (resourceesTabbedPanel == null) {
GridBagConstraints gridBagConstraints45 = new GridBagConstraints();
gridBagConstraints45.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints45.gridy = 0;
gridBagConstraints45.weightx = 1.0D;
gridBagConstraints45.weighty = 1.0D;
gridBagConstraints45.gridx = 1;
resourceesTabbedPanel = new JPanel();
resourceesTabbedPanel.setLayout(new GridBagLayout());
resourceesTabbedPanel.add(getResourcesPanel(), gridBagConstraints45);
}
return resourceesTabbedPanel;
}
/**
* This method initializes resourcesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getResourcesPanel() {
if (resourcesPanel == null) {
GridBagConstraints gridBagConstraints46 = new GridBagConstraints();
gridBagConstraints46.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints46.gridx = 0;
gridBagConstraints46.gridy = 0;
gridBagConstraints46.weightx = 1.0;
gridBagConstraints46.weighty = 1.0;
gridBagConstraints46.insets = new java.awt.Insets(2, 2, 2, 2);
resourcesPanel = new JPanel();
resourcesPanel.setLayout(new GridBagLayout());
resourcesPanel.add(getResourcesScrollPane(), gridBagConstraints46);
}
return resourcesPanel;
}
/**
* This method initializes resourcesScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getResourcesScrollPane() {
if (resourcesScrollPane == null) {
resourcesScrollPane = new JScrollPane();
resourcesScrollPane.setPreferredSize(new java.awt.Dimension(252, 84));
resourcesScrollPane.setViewportView(getResourcesJTree());
}
return resourcesScrollPane;
}
/**
* This method initializes resourcesJTree
*
* @return javax.swing.JTree
*/
private ServicesJTree getResourcesJTree() {
if (resourcesJTree == null) {
resourcesJTree = new ServicesJTree(info.getServices(), info);
resourcesJTree.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
super.focusGained(e);
getResourcesJTree().setServices(info.getServices());
}
});
}
return resourcesJTree;
}
/**
* This method initializes rpHolderPanel
*
* @return javax.swing.JPanel
*/
private ModifyResourcePropertiesPanel getRpHolderPanel() {
if (rpHolderPanel == null) {
if (info.getServices().getService(0).getResourcePropertiesList() == null) {
ResourcePropertiesListType properties = new ResourcePropertiesListType();
info.getServices().getService(0).setResourcePropertiesList(properties);
}
rpHolderPanel = new ModifyResourcePropertiesPanel(info.getServices().getService(0), info.getNamespaces(),
new File(info.getBaseDirectory().getAbsolutePath() + File.separator + "etc"), new File(info
.getBaseDirectory().getAbsolutePath()
+ File.separator + "schema" + File.separator + info.getServices().getService(0).getName()), false);
}
return rpHolderPanel;
}
/**
* This method initializes jSplitPane
*
* @return javax.swing.JSplitPane
*/
private JSplitPane getTypesSplitPane() {
if (typesSplitPane == null) {
typesSplitPane = new JSplitPane();
typesSplitPane.setOneTouchExpandable(true);
typesSplitPane.setLeftComponent(getNamespaceTableScrollPane());
typesSplitPane.setRightComponent(getNamespaceConfPanel());
typesSplitPane.setDividerLocation(0.5d);
}
return typesSplitPane;
}
/**
* This method initializes namespaceReloadButton
*
* @return javax.swing.JButton
*/
private JButton getNamespaceReloadButton() {
if (namespaceReloadButton == null) {
namespaceReloadButton = new JButton();
namespaceReloadButton.setText("Reload");
namespaceReloadButton.setIcon(IntroduceLookAndFeel.getResyncIcon());
namespaceReloadButton.setPreferredSize(new java.awt.Dimension(100, 32));
namespaceReloadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
// build up the new namespace and it's schema
// elements and replace the old one
NamespaceType newType = ((NamespaceTypeDiscoveryComponent) getDiscoveryTabbedPane()
.getSelectedComponent()).createNamespaceType(new File(methodsDirectory
+ File.separator
+ "schema"
+ File.separator
+ info.getIntroduceServiceProperties().getProperty(
IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME)));
if (newType != null) {
// set the old namespaceType to this new one
if (info.getNamespaces() != null && info.getNamespaces().getNamespace() != null) {
for (int namespaceI = 0; namespaceI < info.getNamespaces().getNamespace().length; namespaceI++) {
NamespaceType tempType = info.getNamespaces().getNamespace()[namespaceI];
if (tempType.getNamespace().equals(newType.getNamespace())) {
info.getNamespaces().getNamespace()[namespaceI] = newType;
break;
}
}
}
getNamespaceJTree().setNamespaces(info.getNamespaces());
} else {
JOptionPane.showMessageDialog(ModificationViewer.this, "Error retrieving schema.");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(ModificationViewer.this, "Please select namespace to Remove");
}
}
});
}
return namespaceReloadButton;
}
}
|
package gov.nih.nci.cagrid.introduce.portal.modification;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.common.portal.BusyDialogRunnable;
import gov.nih.nci.cagrid.common.portal.PortalLookAndFeel;
import gov.nih.nci.cagrid.common.portal.PortalUtils;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.ResourceManager;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.extension.DiscoveryExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionsType;
import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodType;
import gov.nih.nci.cagrid.introduce.beans.method.MethodTypeOutput;
import gov.nih.nci.cagrid.introduce.beans.method.MethodsType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespacesType;
import gov.nih.nci.cagrid.introduce.beans.namespace.SchemaElementType;
import gov.nih.nci.cagrid.introduce.beans.property.ServiceProperties;
import gov.nih.nci.cagrid.introduce.beans.property.ServicePropertiesProperty;
import gov.nih.nci.cagrid.introduce.beans.resource.ResourcePropertiesListType;
import gov.nih.nci.cagrid.introduce.beans.security.ServiceSecurity;
import gov.nih.nci.cagrid.introduce.beans.service.ServiceType;
import gov.nih.nci.cagrid.introduce.codegen.SyncTools;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
import gov.nih.nci.cagrid.introduce.extension.ExtensionTools;
import gov.nih.nci.cagrid.introduce.extension.ExtensionsLoader;
import gov.nih.nci.cagrid.introduce.extension.ServiceModificationUIPanel;
import gov.nih.nci.cagrid.introduce.info.ServiceInformation;
import gov.nih.nci.cagrid.introduce.portal.IntroduceLookAndFeel;
import gov.nih.nci.cagrid.introduce.portal.modification.discovery.NamespaceTypeDiscoveryComponent;
import gov.nih.nci.cagrid.introduce.portal.modification.properties.ServicePropertiesTable;
import gov.nih.nci.cagrid.introduce.portal.modification.security.ServiceSecurityPanel;
import gov.nih.nci.cagrid.introduce.portal.modification.services.ServicesJTree;
import gov.nih.nci.cagrid.introduce.portal.modification.services.methods.MethodViewer;
import gov.nih.nci.cagrid.introduce.portal.modification.services.methods.MethodsTable;
import gov.nih.nci.cagrid.introduce.portal.modification.services.resourceproperties.ModifyResourcePropertiesPanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespaceTypeConfigurePanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespaceTypeTreeNode;
import gov.nih.nci.cagrid.introduce.portal.modification.types.NamespacesJTree;
import gov.nih.nci.cagrid.introduce.portal.modification.types.SchemaElementTypeConfigurePanel;
import gov.nih.nci.cagrid.introduce.portal.modification.types.SchemaElementTypeTreeNode;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.namespace.QName;
import org.projectmobius.portal.GridPortalComponent;
import org.projectmobius.portal.PortalResourceManager;
/**
* @author <A HREF="MAILTO:hastings@bmi.osu.edu">Shannon Hastings </A>
* @author <A HREF="MAILTO:oster@bmi.osu.edu">Scott Oster </A>
* @author <A HREF="MAILTO:langella@bmi.osu.edu">Stephen Langella </A>
*/
public class ModificationViewer extends GridPortalComponent {
private javax.swing.JPanel jContentPane = null;
private JPanel mainPanel = null;
private JPanel operationsPanel = null;
private JPanel buttonPanel = null;
private JButton cancel = null;
private JPanel selectPanel = null;
private MethodsTable methodsTable = null;
private JScrollPane methodsScrollPane = null;
private File methodsDirectory = null;
private ServiceDescription introService;
private Properties serviceProperties = null;
private JButton addMethodButton = null;
private JButton saveButton = null;
private JButton removeButton = null;
private JButton modifyButton = null; // @jve:decl-index=0:
private JPanel operationsButtonPanel = null;
private JButton undoButton = null;
private boolean dirty = false;
private JTabbedPane contentTabbedPane = null;
private ServiceSecurityPanel securityPanel = null;
private JLabel serviceNameLabel = null;
private JTextField serviceName = null;
private JLabel packageLabel = null;
private JTextField packageName = null;
private JLabel lastSavedLabel = null;
private JTextField lastSaved = null;
private JLabel saveLocationLabel = null;
private JTextField saveLocation = null;
private JPanel namespacePanel = null;
private JPanel discoveryPanel = null;
private JPanel namespaceConfigurationPanel = null;
private JPanel discoveryButtonPanel = null;
private JButton namespaceAddButton = null;
private JButton namespaceRemoveButton = null;
private JScrollPane namespaceTableScrollPane = null;
private NamespacesJTree namespaceJTree = null;
private JPanel namespaceTypePropertiesPanel = null;
private NamespaceTypeConfigurePanel namespaceTypeConfigurationPanel = null;
private SchemaElementTypeConfigurePanel schemaElementTypeConfigurationPanel = null;
private ServiceInformation info = null;
private JTabbedPane discoveryTabbedPane = null;
private JPanel namespaceConfPanel = null;
private JPanel servicePropertiesPanel = null;
private JPanel servicePropertiesTableContainerPanel = null;
private JScrollPane servicePropertiesTableScrollPane = null;
private ServicePropertiesTable servicePropertiesTable = null;
private JPanel servicePropertiesControlPanel = null;
private JButton addServiceProperyButton = null;
private JButton removeServicePropertyButton = null;
private JTextField servicePropertyKeyTextField = null;
private JTextField servicePropertyValueTextField = null;
private JLabel servicePropertiesKeyLabel = null;
private JLabel servicePropertiesValueLabel = null;
private JPanel servicePropertiesButtonPanel = null;
private JPanel resourceesTabbedPanel = null;
private JPanel resourcesPanel = null;
private JScrollPane resourcesScrollPane = null;
private ServicesJTree resourcesJTree = null;
private JPanel resourcePropertiesPanel = null;
private ModifyResourcePropertiesPanel rpHolderPanel = null;
/**
* This is the default constructor
*/
public ModificationViewer() {
super();
// throw a thread out so that i can make sure that if the chooser is
// canceled i can dispose of this frame
Thread th = createChooserThread();
th.start();
}
public ModificationViewer(File methodsDirectory) {
super();
this.methodsDirectory = methodsDirectory;
try {
initialize();
} catch (Exception e) {
// should never get here but in case.....
e.printStackTrace();
}
}
private Thread createChooserThread() {
Thread th = new Thread() {
public void run() {
try {
chooseService();
} catch (Exception e) {
e.printStackTrace();
}
if (methodsDirectory == null) {
ModificationViewer.this.dispose();
return;
}
File file = new File(methodsDirectory.getAbsolutePath()
+ File.separator + "introduce.xml");
if (file.exists() && file.canRead()) {
try {
initialize();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this,
e.getMessage());
ModificationViewer.this.dispose();
}
} else {
JOptionPane
.showMessageDialog(
ModificationViewer.this,
"Directory "
+ methodsDirectory
.getAbsolutePath()
+ " does not seem to be an introduce service");
ModificationViewer.this.dispose();
}
}
};
return th;
}
private void loadServiceProps() {
try {
serviceProperties = new Properties();
serviceProperties.load(new FileInputStream(this.methodsDirectory
.getAbsolutePath()
+ File.separator
+ IntroduceConstants.INTRODUCE_PROPERTIES_FILE));
serviceProperties.setProperty(
IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR,
methodsDirectory.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void chooseService() throws Exception {
String dir = ResourceManager.promptDir(this, null);
if (dir != null) {
this.methodsDirectory = new File(dir);
}
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() throws Exception {
if (this.methodsDirectory != null) {
this.introService = (ServiceDescription) Utils.deserializeDocument(
this.methodsDirectory.getAbsolutePath() + File.separator
+ "introduce.xml", ServiceDescription.class);
if (introService.getIntroduceVersion() == null
|| !introService.getIntroduceVersion().equals(
IntroduceConstants.INTRODUCE_VERSION)) {
throw new Exception(
"Introduce version in project does not match version provided by Introduce Toolkit ( "
+ IntroduceConstants.INTRODUCE_VERSION
+ " ): "
+ introService.getIntroduceVersion());
}
loadServiceProps();
this.info = new ServiceInformation(introService, serviceProperties,
methodsDirectory);
this.setContentPane(getJContentPane());
this.setTitle("Modify Service Interface");
this.setFrameIcon(IntroduceLookAndFeel.getModifyIcon());
this.pack();
}
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private javax.swing.JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new javax.swing.JPanel();
jContentPane.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
gridBagConstraints13.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints13.weightx = 1.0;
gridBagConstraints13.weighty = 1.0;
gridBagConstraints13.gridx = 0;
gridBagConstraints13.gridy = 0;
gridBagConstraints13.insets = new java.awt.Insets(2, 2, 2, 2);
jContentPane.add(getMainPanel(), gridBagConstraints13);
}
return jContentPane;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getMainPanel() {
if (mainPanel == null) {
GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
gridBagConstraints13.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints13.weighty = 1.0;
gridBagConstraints13.gridx = 0;
gridBagConstraints13.gridy = 1;
gridBagConstraints13.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints13.weightx = 1.0;
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints11.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints11.gridheight = 0;
gridBagConstraints11.gridwidth = 0;
gridBagConstraints11.gridx = 0;
gridBagConstraints11.gridy = 3;
gridBagConstraints11.weighty = 1.0D;
gridBagConstraints11.fill = java.awt.GridBagConstraints.HORIZONTAL;
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
gridBagConstraints2.gridx = 0;
gridBagConstraints2.gridy = 2;
gridBagConstraints2.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints2.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints2.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints3.gridx = 0;
gridBagConstraints3.gridy = 0;
gridBagConstraints3.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints3.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints3.fill = java.awt.GridBagConstraints.HORIZONTAL;
mainPanel.add(getButtonPanel(), gridBagConstraints2);
mainPanel.add(getSelectPanel(), gridBagConstraints3);
mainPanel.add(getContentTabbedPane(), gridBagConstraints13);
}
return mainPanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing. gridBagConstraints41.gridx = 1; JPanel
*/
private JPanel getMethodsPanel() {
if (operationsPanel == null) {
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints.gridy = 0;
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
operationsPanel = new JPanel();
operationsPanel.setLayout(new GridBagLayout());
gridBagConstraints4.weightx = 1.0;
gridBagConstraints4.weighty = 1.0;
gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints4.gridwidth = 2;
gridBagConstraints4.gridx = 0;
gridBagConstraints4.gridy = 0;
operationsPanel.add(getMethodsScrollPane(), gridBagConstraints4);
operationsPanel.add(getMethodsButtonPanel(), gridBagConstraints);
}
return operationsPanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getButtonPanel() {
if (buttonPanel == null) {
GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
gridBagConstraints10.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints10.gridy = 0;
gridBagConstraints10.fill = java.awt.GridBagConstraints.NONE;
gridBagConstraints10.gridx = 2;
GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
gridBagConstraints9.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints9.gridy = 0;
gridBagConstraints9.gridx = 1;
GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
gridBagConstraints8.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints8.gridy = 0;
gridBagConstraints8.gridx = 0;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
buttonPanel.add(getUndoButton(), gridBagConstraints8);
buttonPanel.add(getSaveButton(), gridBagConstraints9);
buttonPanel.add(getCancel(), gridBagConstraints10);
}
return buttonPanel;
}
/**
* This method initializes jButton1
*
* @return javax.swing.JButton
*/
private JButton getCancel() {
if (cancel == null) {
cancel = new JButton(PortalLookAndFeel.getCloseIcon());
cancel.setText("Cancel");
// cancel.setIcon(GumsLookAndFeel.getCloseIcon());
cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dispose();
}
});
}
return cancel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getSelectPanel() {
if (selectPanel == null) {
GridBagConstraints gridBagConstraints24 = new GridBagConstraints();
gridBagConstraints24.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints24.gridy = 1;
gridBagConstraints24.weightx = 1.0;
gridBagConstraints24.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints24.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints24.gridx = 3;
GridBagConstraints gridBagConstraints23 = new GridBagConstraints();
gridBagConstraints23.gridx = 2;
gridBagConstraints23.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints23.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints23.gridy = 1;
saveLocationLabel = new JLabel();
saveLocationLabel.setText("Location");
saveLocationLabel.setFont(new java.awt.Font("Dialog",
java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
gridBagConstraints22.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints22.gridy = 1;
gridBagConstraints22.weightx = 1.0;
gridBagConstraints22.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints22.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints22.gridx = 1;
GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
gridBagConstraints21.gridx = 0;
gridBagConstraints21.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints21.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints21.gridy = 1;
lastSavedLabel = new JLabel();
lastSavedLabel.setText("Last Saved");
lastSavedLabel.setFont(new java.awt.Font("Dialog",
java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints20 = new GridBagConstraints();
gridBagConstraints20.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints20.gridy = 0;
gridBagConstraints20.weightx = 1.0;
gridBagConstraints20.gridx = 3;
GridBagConstraints gridBagConstraints19 = new GridBagConstraints();
gridBagConstraints19.gridx = 2;
gridBagConstraints19.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints19.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints19.gridy = 0;
packageLabel = new JLabel();
packageLabel.setText("Package");
packageLabel.setFont(new java.awt.Font("Dialog",
java.awt.Font.BOLD, 12));
GridBagConstraints gridBagConstraints18 = new GridBagConstraints();
gridBagConstraints18.gridx = 0;
gridBagConstraints18.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints18.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints18.gridy = 0;
GridBagConstraints gridBagConstraints17 = new GridBagConstraints();
gridBagConstraints17.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints17.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints17.gridx = 1;
gridBagConstraints17.gridy = 0;
gridBagConstraints17.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints17.weightx = 1.0;
serviceNameLabel = new JLabel();
serviceNameLabel.setText("Service Name");
serviceNameLabel.setFont(new java.awt.Font("Dialog",
java.awt.Font.BOLD, 12));
selectPanel = new JPanel();
selectPanel.setLayout(new GridBagLayout());
selectPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
null, "Properties",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION, null,
PortalLookAndFeel.getPanelLabelColor()));
selectPanel.add(serviceNameLabel, gridBagConstraints18);
selectPanel.add(getServiceName(), gridBagConstraints17);
selectPanel.add(packageLabel, gridBagConstraints19);
selectPanel.add(getPackageName(), gridBagConstraints20);
selectPanel.add(lastSavedLabel, gridBagConstraints21);
selectPanel.add(getLastSaved(), gridBagConstraints22);
selectPanel.add(saveLocationLabel, gridBagConstraints23);
selectPanel.add(getSaveLocation(), gridBagConstraints24);
}
return selectPanel;
}
/**
* This method initializes jTable
*
* @return javax.swing.JTable
*/
private MethodsTable getMethodsTable() {
if (methodsTable == null) {
methodsTable = new MethodsTable(introService.getServices()
.getService(0).getMethods(), this.methodsDirectory,
this.serviceProperties);
methodsTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
dirty = true;
performMethodModify();
}
}
});
}
return methodsTable;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getMethodsScrollPane() {
if (methodsScrollPane == null) {
methodsScrollPane = new JScrollPane();
methodsScrollPane.setViewportView(getMethodsTable());
}
return methodsScrollPane;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getAddMethodButton() {
if (addMethodButton == null) {
addMethodButton = new JButton(PortalLookAndFeel.getAddIcon());
addMethodButton.setText("Add");
addMethodButton.setToolTipText("add new operation");
addMethodButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
MethodType method = new MethodType();
method.setName("newMethod");
MethodTypeOutput output = new MethodTypeOutput();
output.setQName(new QName("", "void"));
method.setOutput(output);
// add new method to array in bean
// this seems to be a wierd way be adding things....
MethodType[] newMethods;
int newLength = 0;
if (introService.getServices().getService(0)
.getMethods() != null
&& introService.getServices().getService(0)
.getMethods().getMethod() != null) {
newLength = introService.getServices()
.getService(0).getMethods().getMethod().length + 1;
newMethods = new MethodType[newLength];
System.arraycopy(
introService.getServices()
.getService(0).getMethods()
.getMethod(), 0, newMethods, 0,
introService.getServices()
.getService(0).getMethods()
.getMethod().length);
} else {
newLength = 1;
newMethods = new MethodType[newLength];
}
newMethods[newLength - 1] = method;
MethodsType methodsType = new MethodsType();
methodsType.setMethod(newMethods);
introService.getServices().getService(0)
.setMethods(methodsType);
getMethodsTable().addRow(method);
performMethodModify();
}
});
}
return addMethodButton;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getSaveButton() {
if (saveButton == null) {
saveButton = new JButton(PortalLookAndFeel.getSaveIcon());
saveButton.setText("Save");
saveButton.setToolTipText("modify and rebuild service");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
saveModifications();
}
});
}
return saveButton;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getRemoveButton() {
if (removeButton == null) {
removeButton = new JButton(PortalLookAndFeel.getRemoveIcon());
removeButton.setText("Remove");
removeButton.setToolTipText("remove selected operation");
removeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
int row = getMethodsTable().getSelectedRow();
if ((row < 0) || (row >= getMethodsTable().getRowCount())) {
PortalUtils
.showErrorMessage("Please select a method to remove.");
return;
}
int oldSelectedRow = getMethodsTable().getSelectedRow();
getMethodsTable().removeRow(oldSelectedRow);
if (oldSelectedRow == 0) {
oldSelectedRow++;
}
if (getMethodsTable().getRowCount() > 0) {
getMethodsTable().setRowSelectionInterval(
oldSelectedRow - 1, oldSelectedRow - 1);
}
}
});
}
return removeButton;
}
private void resetMethodSecurityIfServiceSecurityChanged() throws Exception {
boolean update = false;
ServiceSecurity service = introService.getServices().getService(0)
.getServiceSecurity();
ServiceSecurity curr = securityPanel.getServiceSecurity();
// This should be cleaned up some
if ((service == null) && (curr == null)) {
update = false;
} else if ((service != null) && (curr == null)) {
update = true;
} else if ((service == null) && (curr != null)) {
update = true;
} else if (!service.equals(curr)) {
update = true;
}
if (update) {
MethodsType mt = this.introService.getServices().getService(0)
.getMethods();
List changes = new ArrayList();
if (mt != null) {
introService.getServices().getService(0).setServiceSecurity(
curr);
MethodType[] methods = mt.getMethod();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if ((methods[i].getMethodSecurity() != null)
&& (!CommonTools.equals(curr, methods[i]
.getMethodSecurity()))) {
methods[i].setMethodSecurity(null);
changes.add(methods[i].getName());
}
}
}
if (changes.size() > 0) {
StringBuffer sb = new StringBuffer();
sb
.append("Service security configuration changed, the security configurations for the following methods were reset:\n");
for (int i = 0; i < changes.size(); i++) {
String method = (String) changes.get(i);
sb.append(" " + (i + 1) + ") " + method);
}
PortalUtils.showMessage(sb.toString());
}
}
}
}
private void performMethodModify() {
try {
this.resetMethodSecurityIfServiceSecurityChanged();
} catch (Exception e) {
e.printStackTrace();
PortalUtils.showErrorMessage(e);
return;
}
MethodType method = getMethodsTable().getSelectedMethodType();
if (method == null) {
PortalUtils.showErrorMessage("Please select a method to modify.");
return;
}
// TODO: check this.... setting this for now......
PortalResourceManager.getInstance().getGridPortal()
.addGridPortalComponent(new MethodViewer(method, info));
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getModifyButton() {
if (modifyButton == null) {
modifyButton = new JButton(IntroduceLookAndFeel.getModifyIcon());
modifyButton.setText("Modify");
modifyButton.setToolTipText("modify seleted operation");
modifyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
dirty = true;
performMethodModify();
}
});
}
return modifyButton;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getMethodsButtonPanel() {
if (operationsButtonPanel == null) {
GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
gridBagConstraints7.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints7.gridy = 1;
gridBagConstraints7.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints7.gridx = 0;
GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
gridBagConstraints6.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints6.gridy = 2;
gridBagConstraints6.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints6.gridx = 0;
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints5.gridy = 0;
gridBagConstraints5.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints5.gridx = 0;
operationsButtonPanel = new JPanel();
operationsButtonPanel.setLayout(new GridBagLayout());
operationsButtonPanel
.add(getAddMethodButton(), gridBagConstraints5);
operationsButtonPanel.add(getModifyButton(), gridBagConstraints6);
operationsButtonPanel.add(getRemoveButton(), gridBagConstraints7);
}
return operationsButtonPanel;
}
/**
* This method initializes undoButton
*
* @return javax.swing.JButton
*/
private JButton getUndoButton() {
if (undoButton == null) {
undoButton = new JButton(IntroduceLookAndFeel.getUndoIcon());
undoButton.setText("Undo");
undoButton.setToolTipText("roll back to last save state");
undoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int decision = JOptionPane.showConfirmDialog(
ModificationViewer.this,
"Are you sure you wish to roll back.");
if (decision == JOptionPane.OK_OPTION) {
BusyDialogRunnable r = new BusyDialogRunnable(
PortalResourceManager.getInstance()
.getGridPortal(), "Undo") {
public void process() {
System.out
.println("Loading in last known save for this project");
try {
if (!dirty) {
setProgressText("restoring from local cache");
ResourceManager
.restoreLatest(
serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP),
serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME),
serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_DESTINATION_DIR));
}
dispose();
PortalResourceManager.getInstance()
.getGridPortal()
.addGridPortalComponent(
new ModificationViewer(
methodsDirectory));
} catch (Exception e1) {
// e1.printStackTrace();
JOptionPane
.showMessageDialog(
ModificationViewer.this,
"Unable to roll back, there may be no older versions available");
return;
}
}
};
Thread th = new Thread(r);
th.start();
}
}
});
}
return undoButton;
}
/**
* This method initializes contentTabbedPane
*
* @return javax.swing.JTabbedPane
*/
private JTabbedPane getContentTabbedPane() {
if (contentTabbedPane == null) {
contentTabbedPane = new JTabbedPane();
contentTabbedPane.addTab("Types", null, getNamespacePanel(), null);
contentTabbedPane.addTab("Operations", null, getMethodsPanel(),
null);
contentTabbedPane.addTab("Metadata", null,
getResourcePropertiesPanel(), null);
contentTabbedPane.addTab("Service Properties", null,
getServicePropertiesPanel(), null);
contentTabbedPane.addTab("Service Contexts", null,
getResourceesTabbedPanel(), null);
contentTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
getNamespaceJTree().setNamespaces(info.getNamespaces());
getResourcesJTree().setServices(info.getServices());
getMethodsTable().clearTable();
getMethodsTable().setMethods(
info.getServices().getService(0).getMethods());
getRpHolderPanel().reInitialize(
info.getServices().getService(0)
.getResourcePropertiesList(),
info.getNamespaces());
}
});
// diable the metadata tab if they've specified not to sync metadata
ResourcePropertiesListType metadataList = this.introService
.getServices().getService(0).getResourcePropertiesList();
if (metadataList != null
&& metadataList.getSynchronizeResourceFramework() != null
&& !metadataList.getSynchronizeResourceFramework()
.booleanValue()) {
// Disable the tab
contentTabbedPane.setEnabledAt(
contentTabbedPane.getTabCount() - 1, false);
}
contentTabbedPane
.addTab("Security", null, getSecurityPanel(), null);
// add a tab for each extension...
ExtensionsType exts = introService.getExtensions();
if (exts != null && exts.getExtension() != null) {
ExtensionType[] extsTypes = exts.getExtension();
for (int i = 0; i < extsTypes.length; i++) {
ServiceExtensionDescriptionType extDtype = ExtensionsLoader
.getInstance().getServiceExtension(
extsTypes[i].getName());
try {
if (extDtype.getServiceModificationUIPanel() != null
&& !extDtype.getServiceModificationUIPanel()
.equals("")) {
ServiceModificationUIPanel extPanel = ExtensionTools
.getServiceModificationUIPanel(extDtype
.getName(), info);
contentTabbedPane.addTab(extDtype.getDisplayName(),
null, extPanel, null);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this,
"Cannot load extension: "
+ extDtype.getDisplayName());
}
}
}
}
return contentTabbedPane;
}
/**
* This method initializes securityPanel
*
* @return javax.swing.JPanel
*/
private ServiceSecurityPanel getSecurityPanel() {
if (securityPanel == null) {
try {
securityPanel = new ServiceSecurityPanel(introService
.getServices().getService(0).getServiceSecurity());
} catch (Exception e) {
e.printStackTrace();
PortalUtils.showErrorMessage(e);
}
}
return securityPanel;
}
/**
* This method initializes serviceName
*
* @return javax.swing.JTextField
*/
private JTextField getServiceName() {
if (serviceName == null) {
serviceName = new JTextField();
serviceName.setEditable(false);
serviceName.setFont(new java.awt.Font("Dialog",
java.awt.Font.ITALIC, 12));
serviceName
.setText(serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME));
}
return serviceName;
}
/**
* This method initializes packageName
*
* @return javax.swing.JTextField
*/
private JTextField getPackageName() {
if (packageName == null) {
packageName = new JTextField();
packageName.setText(serviceProperties
.getProperty("introduce.skeleton.package"));
packageName.setFont(new java.awt.Font("Dialog",
java.awt.Font.ITALIC, 12));
packageName.setEditable(false);
}
return packageName;
}
/**
* This method initializes lastSaved
*
* @return javax.swing.JTextField
*/
private JTextField getLastSaved() {
if (lastSaved == null) {
lastSaved = new JTextField();
lastSaved.setEditable(false);
lastSaved.setFont(new java.awt.Font("Dialog", java.awt.Font.ITALIC,
12));
setLastSaved(serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP));
}
return lastSaved;
}
private void setLastSaved(String savedDate) {
Date date;
if (savedDate.equals("0")) {
date = new Date();
} else {
date = new Date(Long.parseLong(savedDate));
}
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
lastSaved.setText(formatter.format(date));
}
/**
* This method initializes location
*
* @return javax.swing.JTextField
*/
private JTextField getSaveLocation() {
if (saveLocation == null) {
saveLocation = new JTextField();
saveLocation.setText(methodsDirectory.getAbsolutePath());
saveLocation.setFont(new java.awt.Font("Dialog",
java.awt.Font.ITALIC, 12));
saveLocation.setEditable(false);
}
return saveLocation;
}
/**
* This method initializes namespacePanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespacePanel() {
if (namespacePanel == null) {
namespacePanel = new JPanel();
namespacePanel.setLayout(new GridLayout(1, 2));
namespacePanel.add(getNamespaceConfigurationPanel());
namespacePanel.add(getNamespaceConfPanel());
}
return namespacePanel;
}
/**
* This method initializes discoveryPanel
*
* @return javax.swing.JPanel
*/
private JPanel getDiscoveryPanel() {
if (discoveryPanel == null) {
GridBagConstraints gridBagConstraints27 = new GridBagConstraints();
gridBagConstraints27.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints27.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints27.gridx = 0;
gridBagConstraints27.gridy = 1;
GridBagConstraints gridBagConstraints16 = new GridBagConstraints();
gridBagConstraints16.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints16.weighty = 1.0;
gridBagConstraints16.weightx = 1.0;
gridBagConstraints16.gridx = 0;
gridBagConstraints16.gridy = 0;
gridBagConstraints16.insets = new java.awt.Insets(2, 2, 2, 2);
discoveryPanel = new JPanel();
discoveryPanel.setLayout(new GridBagLayout());
discoveryPanel
.setBorder(javax.swing.BorderFactory
.createTitledBorder(
null,
"Select Type",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Dialog",
java.awt.Font.BOLD, 12),
PortalLookAndFeel.getPanelLabelColor()));
discoveryPanel.add(getDiscoveryTabbedPane(), gridBagConstraints16);
discoveryPanel.add(getDiscoveryButtonPanel(), gridBagConstraints27);
}
return discoveryPanel;
}
/**
* This method initializes namespaceConfigurationPanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespaceConfigurationPanel() {
if (namespaceConfigurationPanel == null) {
GridBagConstraints gridBagConstraints29 = new GridBagConstraints();
gridBagConstraints29.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints29.weighty = 1.0D;
gridBagConstraints29.gridx = 0;
gridBagConstraints29.gridy = 0;
gridBagConstraints29.gridwidth = 1;
gridBagConstraints29.gridheight = 2;
gridBagConstraints29.weightx = 1.0D;
namespaceConfigurationPanel = new JPanel();
namespaceConfigurationPanel.setLayout(new GridBagLayout());
namespaceConfigurationPanel.add(getNamespaceTableScrollPane(),
gridBagConstraints29);
}
return namespaceConfigurationPanel;
}
/**
* This method initializes discoveryButtonPanel
*
* @return javax.swing.JPanel
*/
private JPanel getDiscoveryButtonPanel() {
if (discoveryButtonPanel == null) {
GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
gridBagConstraints31.gridx = 1;
gridBagConstraints31.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints31.gridy = 0;
GridBagConstraints gridBagConstraints30 = new GridBagConstraints();
gridBagConstraints30.gridx = 0;
gridBagConstraints30.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints30.gridy = 0;
discoveryButtonPanel = new JPanel();
discoveryButtonPanel.setLayout(new GridBagLayout());
discoveryButtonPanel.add(getNamespaceAddButton(),
gridBagConstraints30);
discoveryButtonPanel.add(getNamespaceRemoveButton(),
gridBagConstraints31);
}
return discoveryButtonPanel;
}
/**
* This method initializes namespaceAddButton
*
* @return javax.swing.JButton
*/
private JButton getNamespaceAddButton() {
if (namespaceAddButton == null) {
namespaceAddButton = new JButton();
namespaceAddButton.setText("Add");
namespaceAddButton.setIcon(PortalLookAndFeel.getAddIcon());
namespaceAddButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
NamespaceType type = ((NamespaceTypeDiscoveryComponent) getDiscoveryTabbedPane()
.getSelectedComponent())
.createNamespaceType(new File(
methodsDirectory
+ File.separator
+ "schema"
+ File.separator
+ info
.getIntroduceServiceProperties()
.getProperty(
IntroduceConstants.INTRODUCE_SKELETON_SERVICE_NAME)));
if (type != null) {
getNamespaceJTree().addNode(type);
} else {
JOptionPane.showMessageDialog(
ModificationViewer.this,
"Error retrieving schema.");
}
}
});
}
return namespaceAddButton;
}
/**
* This method initializes namespaceRemoveButton
*
* @return javax.swing.JButton
*/
private JButton getNamespaceRemoveButton() {
if (namespaceRemoveButton == null) {
namespaceRemoveButton = new JButton();
namespaceRemoveButton.setText("Remove");
namespaceRemoveButton.setIcon(PortalLookAndFeel.getRemoveIcon());
namespaceRemoveButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
if (getNamespaceJTree().getCurrentNode() instanceof NamespaceTypeTreeNode) {
NamespaceType type = (NamespaceType) getNamespaceJTree()
.getCurrentNode().getUserObject();
if (!type.getNamespace().equals(
IntroduceConstants.W3CNAMESPACE)) {
getNamespaceJTree()
.removeSelectedNode();
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(
ModificationViewer.this,
"Please select namespace to Remove");
}
}
});
}
return namespaceRemoveButton;
}
/**
* This method initializes namespaceTableScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getNamespaceTableScrollPane() {
if (namespaceTableScrollPane == null) {
namespaceTableScrollPane = new JScrollPane();
namespaceTableScrollPane.setViewportView(getNamespaceJTree());
}
return namespaceTableScrollPane;
}
/**
* This method initializes namespaceJTree
*
* @return javax.swing.JTree
*/
private NamespacesJTree getNamespaceJTree() {
if (namespaceJTree == null) {
namespaceJTree = new NamespacesJTree(introService.getNamespaces(),
true);
namespaceJTree
.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(
javax.swing.event.TreeSelectionEvent e) {
DefaultMutableTreeNode node = getNamespaceJTree()
.getCurrentNode();
if (node instanceof NamespaceTypeTreeNode) {
getNamespaceTypeConfigurationPanel()
.setNamespaceType(
(NamespaceType) ((NamespaceTypeTreeNode) node)
.getUserObject());
getSchemaElementTypeConfigurationPanel()
.clear();
} else if (node instanceof SchemaElementTypeTreeNode) {
NamespaceTypeTreeNode parentNode = (NamespaceTypeTreeNode) node
.getParent();
NamespaceType nsType = (NamespaceType) parentNode
.getUserObject();
if (nsType.getNamespace().equals(
IntroduceConstants.W3CNAMESPACE)) {
getSchemaElementTypeConfigurationPanel()
.setSchemaElementType(
(SchemaElementType) ((SchemaElementTypeTreeNode) node)
.getUserObject(),
false);
} else {
getSchemaElementTypeConfigurationPanel()
.setSchemaElementType(
(SchemaElementType) ((SchemaElementTypeTreeNode) node)
.getUserObject(),
true);
}
getNamespaceTypeConfigurationPanel()
.setNamespaceType(nsType);
} else {
getNamespaceTypeConfigurationPanel().clear();
getSchemaElementTypeConfigurationPanel()
.clear();
}
}
});
}
return namespaceJTree;
}
/**
* This method initializes namespaceTypePropertiesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespaceTypePropertiesPanel() {
if (namespaceTypePropertiesPanel == null) {
GridBagConstraints gridBagConstraints33 = new GridBagConstraints();
gridBagConstraints33.gridx = 0;
gridBagConstraints33.weightx = 1.0D;
gridBagConstraints33.gridy = 0;
gridBagConstraints33.fill = GridBagConstraints.BOTH;
GridBagConstraints gridBagConstraints34 = new GridBagConstraints();
gridBagConstraints34.gridx = 0;
gridBagConstraints34.weightx = 1.0D;
gridBagConstraints34.gridy = 1;
gridBagConstraints34.fill = GridBagConstraints.BOTH;
namespaceTypePropertiesPanel = new JPanel();
namespaceTypePropertiesPanel.setLayout(new GridBagLayout());
namespaceTypePropertiesPanel.add(
getNamespaceTypeConfigurationPanel(), gridBagConstraints33);
namespaceTypePropertiesPanel.add(
getSchemaElementTypeConfigurationPanel(),
gridBagConstraints34);
}
return namespaceTypePropertiesPanel;
}
/**
* This method initializes namespaceTypeCconfigurationPanel
*
* @return javax.swing.JPanel
*/
private NamespaceTypeConfigurePanel getNamespaceTypeConfigurationPanel() {
if (namespaceTypeConfigurationPanel == null) {
namespaceTypeConfigurationPanel = new NamespaceTypeConfigurePanel();
namespaceTypeConfigurationPanel
.setName("namespaceTypeCconfigurationPanel");
}
return namespaceTypeConfigurationPanel;
}
/**
* This method initializes schemaElementTypeConfigurationPanel
*
* @return javax.swing.JPanel
*/
private SchemaElementTypeConfigurePanel getSchemaElementTypeConfigurationPanel() {
if (schemaElementTypeConfigurationPanel == null) {
schemaElementTypeConfigurationPanel = new SchemaElementTypeConfigurePanel();
}
return schemaElementTypeConfigurationPanel;
}
/**
* This method initializes discoveryTabbedPane
*
* @return javax.swing.JTabbedPane
*/
private JTabbedPane getDiscoveryTabbedPane() {
if (discoveryTabbedPane == null) {
discoveryTabbedPane = new JTabbedPane();
List discoveryTypes = ExtensionsLoader.getInstance()
.getDiscoveryExtensions();
if (discoveryTypes != null) {
for (int i = 0; i < discoveryTypes.size(); i++) {
DiscoveryExtensionDescriptionType dd = (DiscoveryExtensionDescriptionType) discoveryTypes
.get(i);
try {
NamespaceTypeDiscoveryComponent comp = gov.nih.nci.cagrid.introduce.portal.ExtensionTools
.getNamespaceTypeDiscoveryComponent(dd
.getName());
if (comp != null) {
discoveryTabbedPane.addTab(dd.getDisplayName(),
comp);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(ModificationViewer.this,
"Error loading discovery type: "
+ dd.getDisplayName());
}
}
}
}
return discoveryTabbedPane;
}
private void saveModifications() {
int confirmed = JOptionPane.showConfirmDialog(ModificationViewer.this,
"Are you sure you want to save?", "Confirm Save",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.OK_OPTION) {
try {
resetMethodSecurityIfServiceSecurityChanged();
} catch (Exception ex) {
ex.printStackTrace();
PortalUtils.showErrorMessage(ex);
}
BusyDialogRunnable r = new BusyDialogRunnable(PortalResourceManager
.getInstance().getGridPortal(), "Save") {
public void process() {
try {
// walk the namespaces and make sure they are valid
NamespacesType namespaces = introService
.getNamespaces();
if (namespaces != null
&& namespaces.getNamespace() != null) {
for (int i = 0; i < namespaces.getNamespace().length; i++) {
NamespaceType namespace = namespaces
.getNamespace(i);
if (namespace.getPackageName() != null) {
if (!CommonTools
.isValidPackageName(namespace
.getPackageName())) {
setErrorMessage("Error: Invalid package name for namespace "
+ namespace.getNamespace()
+ " : "
+ namespace.getPackageName());
return;
}
}
}
}
// walk the methods table and create the
// new MethodsType array
setProgressText("editing methods");
MethodType[] methodsArray = new MethodType[methodsTable
.getRowCount()];
for (int i = 0; i < methodsArray.length; i++) {
MethodType methodInstance = methodsTable
.getMethodType(i);
methodsArray[i] = methodInstance;
}
MethodsType methods = new MethodsType();
methods.setMethod(methodsArray);
introService.getServices().getService(0).setMethods(
methods);
introService.getServices().getService(0)
.setServiceSecurity(
securityPanel.getServiceSecurity());
// walk the service properties
setProgressText("editing service properties");
ServiceProperties properties = new ServiceProperties();
ServicePropertiesProperty[] propArr = new ServicePropertiesProperty[getServicePropertiesTable()
.getRowCount()];
for (int i = 0; i < propArr.length; i++) {
propArr[i] = getServicePropertiesTable()
.getRowData(i);
}
properties.setProperty(propArr);
introService.setServiceProperties(properties);
// walk the metadata
/*
* setProgressText("editing service metadata object");
* ResourcePropertyType[] propertyTypes =
* getRpHolderPanel().getConfiguredResourceProperties();
* ResourcePropertiesListType propertyList = new
* ResourcePropertiesListType();
* propertyList.setResourceProperty(propertyTypes);
* introService.getServices().getService(0).setResourcePropertiesList(propertyList);
*/
// check the methods to make sure they are valid.......
if (introService.getServices() != null
&& introService.getServices().getService() != null) {
for (int serviceI = 0; serviceI < introService
.getServices().getService().length; serviceI++) {
ServiceType service = introService
.getServices().getService(serviceI);
if (service.getMethods() != null
&& service.getMethods().getMethod() != null) {
List methodNames = new ArrayList();
if (service.getMethods() != null
&& service.getMethods().getMethod() != null) {
for (int methodI = 0; methodI < service
.getMethods().getMethod().length; methodI++) {
MethodType method = methods
.getMethod(methodI);
if (!(methodNames.contains(method
.getName()))) {
methodNames.add(method
.getName());
} else {
setErrorMessage("The service "
+ service.getName()
+ " has duplicate methods "
+ method.getName());
return;
}
}
}
}
}
}
// save the metadata and methods and then call the
// resync and build
setProgressText("writting service document");
Utils.serializeDocument(methodsDirectory
.getAbsolutePath()
+ File.separator + "introduce.xml",
introService,
IntroduceConstants.INTRODUCE_SKELETON_QNAME);
// call the sync tools
setProgressText("sychronizing skeleton");
SyncTools sync = new SyncTools(methodsDirectory);
sync.sync();
// build the synchronized service
setProgressText("rebuilding skeleton");
String cmd = CommonTools.getAntCommand("clean all",
methodsDirectory.getAbsolutePath());
Process p = CommonTools.createAndOutputProcess(cmd);
p.waitFor();
if (p.exitValue() != 0) {
setErrorMessage("Error: Unable to rebuild the skeleton");
return;
}
dirty = false;
setProgressText("loading service properties");
loadServiceProps();
setLastSaved(serviceProperties
.getProperty(IntroduceConstants.INTRODUCE_SKELETON_TIMESTAMP));
this.setProgressText("");
} catch (Exception e1) {
e1.printStackTrace();
setErrorMessage("Error: " + e1.getMessage());
return;
}
}
};
Thread th = new Thread(r);
th.start();
}
}
/**
* This method initializes namespaceConfPanel
*
* @return javax.swing.JPanel
*/
private JPanel getNamespaceConfPanel() {
if (namespaceConfPanel == null) {
namespaceConfPanel = new JPanel();
namespaceConfPanel.setLayout(new BoxLayout(namespaceConfPanel,
BoxLayout.Y_AXIS));
namespaceConfPanel.add(getDiscoveryPanel());
namespaceConfPanel.add(getNamespaceTypePropertiesPanel());
}
return namespaceConfPanel;
}
/**
* This method initializes servicePropertiesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesPanel() {
if (servicePropertiesPanel == null) {
GridBagConstraints gridBagConstraints26 = new GridBagConstraints();
gridBagConstraints26.gridx = 0;
gridBagConstraints26.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints26.weightx = 1.0D;
gridBagConstraints26.weighty = 1.0D;
gridBagConstraints26.gridy = 0;
GridBagConstraints gridBagConstraints25 = new GridBagConstraints();
gridBagConstraints25.gridx = 0;
gridBagConstraints25.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints25.gridy = 1;
servicePropertiesPanel = new JPanel();
servicePropertiesPanel.setLayout(new GridBagLayout());
servicePropertiesPanel.add(
getServicePropertiesTableContainerPanel(),
gridBagConstraints26);
servicePropertiesPanel.add(getServicePropertiesControlPanel(),
gridBagConstraints25);
}
return servicePropertiesPanel;
}
/**
* This method initializes servicePropertiesTableContainerPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesTableContainerPanel() {
if (servicePropertiesTableContainerPanel == null) {
GridBagConstraints gridBagConstraints28 = new GridBagConstraints();
gridBagConstraints28.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints28.gridx = 0;
gridBagConstraints28.gridy = 0;
gridBagConstraints28.weightx = 1.0;
gridBagConstraints28.weighty = 1.0;
gridBagConstraints28.insets = new java.awt.Insets(5, 5, 5, 5);
servicePropertiesTableContainerPanel = new JPanel();
servicePropertiesTableContainerPanel.setLayout(new GridBagLayout());
servicePropertiesTableContainerPanel
.add(getServicePropertiesTableScrollPane(),
gridBagConstraints28);
}
return servicePropertiesTableContainerPanel;
}
/**
* This method initializes servicePropertiesTableScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getServicePropertiesTableScrollPane() {
if (servicePropertiesTableScrollPane == null) {
servicePropertiesTableScrollPane = new JScrollPane();
servicePropertiesTableScrollPane
.setViewportView(getServicePropertiesTable());
}
return servicePropertiesTableScrollPane;
}
/**
* This method initializes servicePropertiesTable
*
* @return javax.swing.JTable
*/
private ServicePropertiesTable getServicePropertiesTable() {
if (servicePropertiesTable == null) {
servicePropertiesTable = new ServicePropertiesTable(info
.getServiceProperties());
}
return servicePropertiesTable;
}
/**
* This method initializes servicePropertiesControlPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesControlPanel() {
if (servicePropertiesControlPanel == null) {
GridBagConstraints gridBagConstraints42 = new GridBagConstraints();
gridBagConstraints42.gridx = 1;
gridBagConstraints42.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints42.gridwidth = 1;
gridBagConstraints42.gridheight = 4;
gridBagConstraints42.gridy = 0;
GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
gridBagConstraints41.gridx = 0;
gridBagConstraints41.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints41.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints41.gridy = 2;
servicePropertiesValueLabel = new JLabel();
servicePropertiesValueLabel.setText("Default Value:");
GridBagConstraints gridBagConstraints40 = new GridBagConstraints();
gridBagConstraints40.gridx = 0;
gridBagConstraints40.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints40.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints40.gridy = 0;
servicePropertiesKeyLabel = new JLabel();
servicePropertiesKeyLabel.setText("Key:");
GridBagConstraints gridBagConstraints39 = new GridBagConstraints();
gridBagConstraints39.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints39.gridy = 3;
gridBagConstraints39.weightx = 1.0;
gridBagConstraints39.insets = new java.awt.Insets(2, 2, 10, 10);
gridBagConstraints39.gridx = 0;
GridBagConstraints gridBagConstraints38 = new GridBagConstraints();
gridBagConstraints38.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints38.gridy = 1;
gridBagConstraints38.weightx = 1.0;
gridBagConstraints38.insets = new java.awt.Insets(2, 2, 10, 10);
gridBagConstraints38.gridx = 0;
servicePropertiesControlPanel = new JPanel();
servicePropertiesControlPanel.setLayout(new GridBagLayout());
servicePropertiesControlPanel.add(getServicePropertyKeyTextField(),
gridBagConstraints38);
servicePropertiesControlPanel.add(
getServicePropertyValueTextField(), gridBagConstraints39);
servicePropertiesControlPanel.add(servicePropertiesKeyLabel,
gridBagConstraints40);
servicePropertiesControlPanel.add(servicePropertiesValueLabel,
gridBagConstraints41);
servicePropertiesControlPanel.add(
getServicePropertiesButtonPanel(), gridBagConstraints42);
}
return servicePropertiesControlPanel;
}
/**
* This method initializes addServiceProperyButton
*
* @return javax.swing.JButton
*/
private JButton getAddServiceProperyButton() {
if (addServiceProperyButton == null) {
addServiceProperyButton = new JButton();
addServiceProperyButton.setText("Add");
addServiceProperyButton.setIcon(PortalLookAndFeel.getAddIcon());
addServiceProperyButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (getServicePropertyKeyTextField().getText()
.length() > 0) {
ServicePropertiesProperty prop = new ServicePropertiesProperty();
prop.setKey(getServicePropertyKeyTextField()
.getText());
prop
.setValue(getServicePropertyValueTextField()
.getText());
getServicePropertiesTable().addRow(prop);
} else {
JOptionPane
.showMessageDialog(
ModificationViewer.this,
"You must at least enter a key name for the property");
}
}
});
}
return addServiceProperyButton;
}
/**
* This method initializes removeServicePropertyButton
*
* @return javax.swing.JButton
*/
private JButton getRemoveServicePropertyButton() {
if (removeServicePropertyButton == null) {
removeServicePropertyButton = new JButton();
removeServicePropertyButton.setText("Remove");
removeServicePropertyButton.setIcon(PortalLookAndFeel
.getRemoveIcon());
removeServicePropertyButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
getServicePropertiesTable().removeSelectedRow();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
return removeServicePropertyButton;
}
/**
* This method initializes servicePropertyKeyTextField
*
* @return javax.swing.JTextField
*/
private JTextField getServicePropertyKeyTextField() {
if (servicePropertyKeyTextField == null) {
servicePropertyKeyTextField = new JTextField();
}
return servicePropertyKeyTextField;
}
/**
* This method initializes servicePropertyValueTextField
*
* @return javax.swing.JTextField
*/
private JTextField getServicePropertyValueTextField() {
if (servicePropertyValueTextField == null) {
servicePropertyValueTextField = new JTextField();
}
return servicePropertyValueTextField;
}
/**
* This method initializes servicePropertiesButtonPanel
*
* @return javax.swing.JPanel
*/
private JPanel getServicePropertiesButtonPanel() {
if (servicePropertiesButtonPanel == null) {
GridBagConstraints gridBagConstraints37 = new GridBagConstraints();
gridBagConstraints37.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints37.gridy = 0;
gridBagConstraints37.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints37.gridx = 0;
GridBagConstraints gridBagConstraints32 = new GridBagConstraints();
gridBagConstraints32.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints32.gridy = 1;
gridBagConstraints32.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints32.gridx = 0;
servicePropertiesButtonPanel = new JPanel();
servicePropertiesButtonPanel.setLayout(new GridBagLayout());
servicePropertiesButtonPanel.add(getRemoveServicePropertyButton(),
gridBagConstraints32);
servicePropertiesButtonPanel.add(getAddServiceProperyButton(),
gridBagConstraints37);
}
return servicePropertiesButtonPanel;
}
/**
* This method initializes servicesTabbedPanel
*
* @return javax.swing.JPanel
*/
private JPanel getResourceesTabbedPanel() {
if (resourceesTabbedPanel == null) {
GridBagConstraints gridBagConstraints45 = new GridBagConstraints();
gridBagConstraints45.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints45.gridy = 0;
gridBagConstraints45.weightx = 1.0D;
gridBagConstraints45.weighty = 1.0D;
gridBagConstraints45.gridx = 1;
resourceesTabbedPanel = new JPanel();
resourceesTabbedPanel.setLayout(new GridBagLayout());
resourceesTabbedPanel
.add(getResourcesPanel(), gridBagConstraints45);
}
return resourceesTabbedPanel;
}
/**
* This method initializes resourcesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getResourcesPanel() {
if (resourcesPanel == null) {
GridBagConstraints gridBagConstraints46 = new GridBagConstraints();
gridBagConstraints46.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints46.gridx = 0;
gridBagConstraints46.gridy = 0;
gridBagConstraints46.weightx = 1.0;
gridBagConstraints46.weighty = 1.0;
gridBagConstraints46.insets = new java.awt.Insets(2, 2, 2, 2);
resourcesPanel = new JPanel();
resourcesPanel.setLayout(new GridBagLayout());
resourcesPanel.add(getResourcesScrollPane(), gridBagConstraints46);
}
return resourcesPanel;
}
/**
* This method initializes resourcesScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getResourcesScrollPane() {
if (resourcesScrollPane == null) {
resourcesScrollPane = new JScrollPane();
resourcesScrollPane
.setPreferredSize(new java.awt.Dimension(252, 84));
resourcesScrollPane.setViewportView(getResourcesJTree());
}
return resourcesScrollPane;
}
/**
* This method initializes resourcesJTree
*
* @return javax.swing.JTree
*/
private ServicesJTree getResourcesJTree() {
if (resourcesJTree == null) {
resourcesJTree = new ServicesJTree(info.getServices(), info);
resourcesJTree.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
super.focusGained(e);
getResourcesJTree().setServices(info.getServices());
}
});
}
return resourcesJTree;
}
/**
* This method initializes resourcePropertiesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getResourcePropertiesPanel() {
if (resourcePropertiesPanel == null) {
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridy = 0;
gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints1.weightx = 1.0D;
gridBagConstraints1.weighty = 1.0D;
gridBagConstraints1.gridx = 0;
resourcePropertiesPanel = new JPanel();
resourcePropertiesPanel.setLayout(new GridBagLayout());
resourcePropertiesPanel
.add(getRpHolderPanel(), gridBagConstraints1);
}
return resourcePropertiesPanel;
}
/**
* This method initializes rpHolderPanel
*
* @return javax.swing.JPanel
*/
private ModifyResourcePropertiesPanel getRpHolderPanel() {
if (rpHolderPanel == null) {
if (info.getServices().getService(0).getResourcePropertiesList() == null) {
ResourcePropertiesListType properties = new ResourcePropertiesListType();
info.getServices().getService(0).setResourcePropertiesList(
properties);
}
rpHolderPanel = new ModifyResourcePropertiesPanel(info
.getServices().getService(0).getResourcePropertiesList(),
info.getNamespaces(), false);
}
return rpHolderPanel;
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.csstudio.diirt.util.preferences;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.StringButtonFieldEditor;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
/**
* Preference page for configuring diirt preferences primarily the Location of
* the diirt configuration folder.
*
* In addition it has a directory view which shows all the individual
* configuration files. Double click on any file will result in opening that
* file with the configured default editor
*
* @author Kunal Shroff
*
*/
public class DiirtPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String PLATFORM_URI_PREFIX = "platform:";
private ScopedPreferenceStore store;
private TreeViewer tv;
private StringButtonFieldEditor diirtPathEditor;
public DiirtPreferencePage() {
}
@Override
protected Control createContents(Composite parent) {
Composite top = new Composite(parent, SWT.LEFT);
top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
top.setLayout(new GridLayout());
diirtPathEditor = new StringButtonFieldEditor("diirt.home", "&Diirt configuration directory:", top) {
private String lastPath = store.getString("diirt.home");
@Override
protected String changePressed() {
DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SHEET);
if (lastPath != null) {
try {
lastPath = getSubsitutedPath(lastPath);
if (new File(lastPath).exists()) {
File lastDir = new File(lastPath);
dialog.setFilterPath(lastDir.getCanonicalPath());
}
} catch (IOException e) {
dialog.setFilterPath(lastPath);
}
}
String dir = dialog.open();
if (dir != null) {
dir = dir.trim();
if (dir.length() == 0) {
return null;
}
lastPath = dir;
}
tv.setInput(dir);
tv.refresh();
return dir;
}
};
diirtPathEditor.setChangeButtonText("Browse");
diirtPathEditor.setPage(this);
diirtPathEditor.setPreferenceStore(getPreferenceStore());
diirtPathEditor.load();
// Detailed view of all the configuration files
Composite treeComposite = new Composite(parent, SWT.NONE);
treeComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
treeComposite.setLayout(new GridLayout(1, false));
// Create the tree viewer to display the file tree
tv = new TreeViewer(treeComposite);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
try {
tv.setInput(getSubsitutedPath(store.getString("diirt.home")));
} catch (IOException e1) {
setErrorMessage(e1.getMessage());
}
tv.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
TreeSelection selection = (TreeSelection) event.getSelection();
File sel = (File) selection.getFirstElement();
try {
if (sel.isFile()) {
Program.launch(sel.getCanonicalPath());
}
} catch (IOException e) {
setErrorMessage(e.getMessage());
}
}
});
return parent;
}
@Override
public void init(IWorkbench workbench) {
store = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.csstudio.diirt.util.preferences");
store.addPropertyChangeListener((PropertyChangeEvent event) -> {
if (event.getProperty() == "diirt.home") {
setMessage("Restart is needed", ERROR);
}
});
setPreferenceStore(store);
setDescription("Diirt preference page");
}
@Override
public boolean performOk() {
try {
File lastDir = new File(getSubsitutedPath(diirtPathEditor.getStringValue()));
if (lastDir.exists()) {
diirtPathEditor.store();
tv.setInput(store.getString("diirt.home"));
} else {
setErrorMessage("Invalid config location");
}
} catch (Exception e1) {
setErrorMessage(e1.getMessage());
}
return super.performOk();
}
/**
* handles the platform urls
*
* @param path
* @return
* @throws MalformedURLException
* @throws IOException
*/
private String getSubsitutedPath(String path) throws MalformedURLException, IOException{
if(path != null && !path.isEmpty()){
if(path.startsWith(PLATFORM_URI_PREFIX)){
return FileLocator.resolve(new URL(path)).getPath().toString();
}
else{
return path;
}
} else{
return "root";
}
}
@Override
protected void performDefaults() {
diirtPathEditor.loadDefault();
super.performDefaults();
};
/**
* This class provides the content for the tree in FileTree
*/
class FileTreeContentProvider implements ITreeContentProvider {
File root = new File("root");
/**
* Gets the children of the specified object
*
* @param arg0 the parent object
* @return Object[]
*/
public Object[] getChildren(Object arg0) {
// Return the files and subdirectories in this directory
return ((File) arg0).listFiles();
}
/**
* Gets the parent of the specified object
*
* @param arg0
* the object
* @return Object
*/
public Object getParent(Object arg0) {
// Return this file's parent file
return ((File) arg0).getParentFile();
}
/**
* Returns whether the passed object has children
*
* @param arg0 the parent object
* @return boolean
*/
public boolean hasChildren(Object arg0) {
// Get the children
Object[] obj = getChildren(arg0);
// Return whether the parent has children
return obj == null ? false : obj.length > 0;
}
/**
* Gets the root element(s) of the tree
*
* @param arg0 the input data
* @return Object[]
*/
public Object[] getElements(Object arg0) {
return root.listFiles();
}
/**
* Disposes any created resources
*/
public void dispose() {
// Nothing to dispose
}
/**
* Called when the input changes
*
* @param arg0 the viewer
* @param arg1 the old input
* @param arg2 the new input
*/
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
try {
root = new File((String)arg2);
} catch (Exception e) {
root = new File("root");
}
}
}
/**
* This class provides the labels for the file tree
*/
class FileTreeLabelProvider implements ILabelProvider {
/**
* Constructs a FileTreeLabelProvider
*/
public FileTreeLabelProvider() {
}
/**
* Gets the text to display for a node in the tree
*
* @param arg0
* the node
* @return String
*/
public String getText(Object arg0) {
// Get the name of the file
String text = ((File) arg0).getName();
// If name is blank, get the path
if (text.length() == 0) {
text = ((File) arg0).getPath();
}
return text;
}
/**
* Called when this LabelProvider is being disposed
*/
public void dispose() {
}
/**
* Returns whether changes to the specified property on the specified
* element would affect the label for the element
*
* @param arg0
* the element
* @param arg1
* the property
* @return boolean
*/
public boolean isLabelProperty(Object arg0, String arg1) {
return false;
}
/**
* Removes the listener
*
* @param arg0 the listener to remove
*/
public void removeListener(ILabelProviderListener arg0) {
}
@Override
public Image getImage(Object element) {
return null;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
}
}
|
package com.cloud.storage.template;
import com.cloud.storage.StorageLayer;
import com.cloud.utils.Pair;
import com.cloud.utils.UriUtils;
import com.cloud.utils.net.Proxy;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.storage.command.DownloadCommand.ResourceType;
import org.apache.cloudstack.utils.imagestore.ImageStoreUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Download a template file using HTTP
*/
public class HttpTemplateDownloader extends ManagedContextRunnable implements TemplateDownloader {
public static final Logger s_logger = LoggerFactory.getLogger(HttpTemplateDownloader.class.getName());
private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
private static final int CHUNK_SIZE = 1024 * 1024;
private final HttpClient client;
private final HttpMethodRetryHandler myretryhandler;
public TemplateDownloader.Status status = TemplateDownloader.Status.NOT_STARTED;
public String errorString = " ";
public long downloadTime = 0;
public long totalBytes;
StorageLayer _storage;
boolean inited = true;
private final String downloadUrl;
private String toFile = "";
private long remoteSize = 0;
private GetMethod request = null;
private boolean resume = false;
private DownloadCompleteCallback completionCallback = null;
private String toDir;
private final long maxTemplateSizeInBytes;
private ResourceType resourceType = ResourceType.TEMPLATE;
public HttpTemplateDownloader(final StorageLayer storageLayer, final String downloadUrl, final String toDir, final DownloadCompleteCallback callback,
final long maxTemplateSizeInBytes, final String user, final String password, final Proxy proxy, final ResourceType resourceType) {
_storage = storageLayer;
this.downloadUrl = downloadUrl;
setToDir(toDir);
status = TemplateDownloader.Status.NOT_STARTED;
this.resourceType = resourceType;
this.maxTemplateSizeInBytes = maxTemplateSizeInBytes;
totalBytes = 0;
client = new HttpClient(s_httpClientManager);
myretryhandler = (method, exception, executionCount) -> {
if (executionCount >= 2) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (!method.isRequestSent()) {
// Retry if the request has not been sent fully or
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
};
try {
request = new GetMethod(downloadUrl);
request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
completionCallback = callback;
//this.request.setFollowRedirects(false);
final File f = File.createTempFile("dnld", "tmp_", new File(toDir));
if (_storage != null) {
_storage.setWorldReadableAndWriteable(f);
}
toFile = f.getAbsolutePath();
final Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl);
if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
if (proxy.getUserName() != null) {
final Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
client.getState().setProxyCredentials(AuthScope.ANY, proxyCreds);
}
}
if (user != null && password != null) {
client.getParams().setAuthenticationPreemptive(true);
final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
} else {
s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second());
}
} catch (final IllegalArgumentException iae) {
errorString = iae.getMessage();
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
inited = false;
} catch (final Exception ex) {
errorString = "Unable to start download -- check url? ";
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
s_logger.warn("Exception in constructor -- " + ex.toString());
}
}
@Override
protected void runInContext() {
try {
download(resume, completionCallback);
} catch (final Exception e) {
s_logger.warn("Caught exception during download " + e.getMessage(), e);
errorString = "Failed to install: " + e.getMessage();
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
}
}
@Override
public long download(final boolean resume, final DownloadCompleteCallback callback) {
switch (status) {
case ABORTED:
case UNRECOVERABLE_ERROR:
case DOWNLOAD_FINISHED:
return 0;
default:
}
int bytes = 0;
final File file = new File(toFile);
try {
long localFileSize = 0;
if (file.exists() && resume) {
localFileSize = file.length();
s_logger.info("Resuming download to file (current size)=" + localFileSize);
}
final Date start = new Date();
int responseCode = 0;
if (localFileSize > 0) {
// require partial content support for resume
request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
errorString = "HTTP Server does not support partial get";
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
return 0;
}
} else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
return 0; //FIXME: retry?
}
final Header contentLengthHeader = request.getResponseHeader("Content-Length");
boolean chunked = false;
long remoteSize2 = 0;
if (contentLengthHeader == null) {
final Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
errorString = " Failed to receive length of download ";
return 0; //FIXME: what status do we put here? Do we retry?
} else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
chunked = true;
}
} else {
remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
if (remoteSize2 == 0) {
status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
final String downloaded = "(download complete remote=" + remoteSize + "bytes)";
errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
downloadTime = 0;
return 0;
}
}
if (remoteSize == 0) {
remoteSize = remoteSize2;
}
if (remoteSize > maxTemplateSizeInBytes) {
s_logger.info("Remote size is too large: " + remoteSize + " , max=" + maxTemplateSizeInBytes);
status = Status.UNRECOVERABLE_ERROR;
errorString = "Download file size is too large";
return 0;
}
if (remoteSize == 0) {
remoteSize = maxTemplateSizeInBytes;
}
final URL url = new URL(getDownloadUrl());
final InputStream in = url.openStream();
final RandomAccessFile out = new RandomAccessFile(file, "rw");
out.seek(localFileSize);
s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize=" + remoteSize + " , max size=" + maxTemplateSizeInBytes);
final byte[] block = new byte[CHUNK_SIZE];
long offset = 0;
boolean done = false;
boolean verifiedFormat = false;
status = TemplateDownloader.Status.IN_PROGRESS;
while (!done && status != Status.ABORTED && offset <= remoteSize) {
if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
out.write(block, 0, bytes);
offset += bytes;
out.seek(offset);
totalBytes += bytes;
if (!verifiedFormat && (offset >= 1048576 || offset >= remoteSize)) { //let's check format after we get 1MB or full file
String uripath = null;
try {
final URI str = new URI(getDownloadUrl());
uripath = str.getPath();
} catch (final URISyntaxException e) {
s_logger.warn("Invalid download url: " + getDownloadUrl() + ", This should not happen since we have validated the url before!!");
}
final String unsupportedFormat = ImageStoreUtil.checkTemplateFormat(file.getAbsolutePath(), uripath);
if (unsupportedFormat == null || !unsupportedFormat.isEmpty()) {
try {
request.abort();
out.close();
in.close();
} catch (final Exception ex) {
s_logger.debug("Error on http connection : " + ex.getMessage());
}
status = Status.UNRECOVERABLE_ERROR;
errorString = "Template content is unsupported, or mismatch between selected format and template content. Found : " + unsupportedFormat;
return 0;
}
s_logger.debug("Verified format of downloading file " + file.getAbsolutePath() + " is supported");
verifiedFormat = true;
}
} else {
done = true;
}
}
out.getFD().sync();
final Date finish = new Date();
String downloaded = "(incomplete download)";
if (totalBytes >= remoteSize) {
status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
downloaded = "(download complete remote=" + remoteSize + "bytes)";
}
errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
downloadTime += finish.getTime() - start.getTime();
in.close();
out.close();
return totalBytes;
} catch (final HttpException hte) {
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
errorString = hte.getMessage();
} catch (final IOException ioe) {
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; //probably a file write error?
errorString = ioe.getMessage();
} finally {
if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
file.delete();
}
request.releaseConnection();
if (callback != null) {
callback.downloadComplete(status);
}
}
return 0;
}
public String getDownloadUrl() {
return downloadUrl;
}
@Override
public boolean stopDownload() {
switch (getStatus()) {
case IN_PROGRESS:
if (request != null) {
request.abort();
}
status = TemplateDownloader.Status.ABORTED;
return true;
case UNKNOWN:
case NOT_STARTED:
case RECOVERABLE_ERROR:
case UNRECOVERABLE_ERROR:
case ABORTED:
status = TemplateDownloader.Status.ABORTED;
case DOWNLOAD_FINISHED:
final File f = new File(toFile);
if (f.exists()) {
f.delete();
}
return true;
default:
return true;
}
}
@Override
public int getDownloadPercent() {
if (remoteSize == 0) {
return 0;
}
return (int) (100.0 * totalBytes / remoteSize);
}
@Override
public TemplateDownloader.Status getStatus() {
return status;
}
@Override
public void setStatus(final TemplateDownloader.Status status) {
this.status = status;
}
@Override
public long getDownloadTime() {
return downloadTime;
}
@Override
public long getDownloadedBytes() {
return totalBytes;
}
@Override
public String getDownloadError() {
return errorString;
}
@Override
public void setDownloadError(final String error) {
errorString = error;
}
@Override
public String getDownloadLocalPath() {
return getToFile();
}
public String getToFile() {
final File file = new File(toFile);
return file.getAbsolutePath();
}
public boolean isResume() {
return resume;
}
@Override
public void setResume(final boolean resume) {
this.resume = resume;
}
@Override
public boolean isInited() {
return inited;
}
@Override
public long getMaxTemplateSizeInBytes() {
return maxTemplateSizeInBytes;
}
public String getToDir() {
return toDir;
}
public void setToDir(final String toDir) {
this.toDir = toDir;
}
public ResourceType getResourceType() {
return resourceType;
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import com.kauailabs.nav6.frc.BufferingSerialPort;
import com.kauailabs.nav6.frc.IMU;
import com.kauailabs.nav6.frc.IMUAdvanced;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.visa.VisaException;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends SimpleRobot {
BufferingSerialPort serial_port;
//IMU imu; // Alternatively, use IMUAdvanced for advanced features
IMUAdvanced imu;
boolean first_iteration;
public RobotTemplate() {
try {
serial_port = new BufferingSerialPort(57600);
// You can add a second parameter to modify the
// update rate (in hz) from 4 to 100. The default is 100.
// If you need to minimize CPU load, you can set it to a
// lower value, as shown here, depending upon your needs.
// You can also use the IMUAdvanced class for advanced
// features.
byte update_rate_hz = 20;
//imu = new IMU(serial_port,update_rate_hz);
imu = new IMUAdvanced(serial_port,update_rate_hz);
} catch (VisaException ex) {
ex.printStackTrace();
}
if ( imu != null ) {
LiveWindow.addSensor("IMU", "Gyro", imu);
}
first_iteration = true;
}
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
while (isOperatorControl() && isEnabled()) {
boolean is_calibrating = imu.isCalibrating();
if ( first_iteration && !is_calibrating ) {
Timer.delay( 0.3 );
imu.zeroYaw();
first_iteration = false;
}
SmartDashboard.putBoolean("IMU_Connected", imu.isConnected());
SmartDashboard.putNumber("IMU_Yaw", imu.getYaw());
SmartDashboard.putNumber("IMU_Pitch", imu.getPitch());
SmartDashboard.putNumber("IMU_Roll", imu.getRoll());
SmartDashboard.putNumber("IMU_CompassHeading", imu.getCompassHeading());
SmartDashboard.putNumber("IMU_Update_Count", imu.getUpdateCount());
SmartDashboard.putNumber("IMU_Byte_Count", imu.getByteCount());
// If you are using the IMUAdvanced class, you can also access the following
// additional functions, at the expense of some extra processing
// that occurs on the CRio processor
SmartDashboard.putNumber("IMU_Accel_X", imu.getWorldLinearAccelX());
SmartDashboard.putNumber("IMU_Accel_Y", imu.getWorldLinearAccelY());
SmartDashboard.putBoolean("IMU_IsMoving", imu.isMoving());
SmartDashboard.putNumber("IMU_Temp_C", imu.getTempC());
SmartDashboard.putBoolean("IMU_IsCalibrating", imu.isCalibrating());
Timer.delay(0.2);
}
}
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
}
|
package net.devh.boot.grpc.server.serverfactory;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import org.springframework.core.io.Resource;
import com.google.common.net.InetAddresses;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.channel.epoll.EpollServerDomainSocketChannel;
import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import net.devh.boot.grpc.server.config.ClientAuth;
import net.devh.boot.grpc.server.config.GrpcServerProperties;
import net.devh.boot.grpc.server.config.GrpcServerProperties.Security;
/**
* Factory for shaded netty based grpc servers.
*
* @author Michael (yidongnan@gmail.com)
* @since 5/17/16
*/
public class ShadedNettyGrpcServerFactory
extends AbstractGrpcServerFactory<io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder> {
/**
* Creates a new shaded netty server factory with the given properties.
*
* @param properties The properties used to configure the server.
* @param serverConfigurers The server configurers to use. Can be empty.
*/
public ShadedNettyGrpcServerFactory(final GrpcServerProperties properties,
final List<GrpcServerConfigurer> serverConfigurers) {
super(properties, serverConfigurers);
}
@Override
protected NettyServerBuilder newServerBuilder() {
final String address = getAddress();
final int port = getPort();
if (address.startsWith("unix:
return NettyServerBuilder
.forAddress(new DomainSocketAddress(address.substring(7)))
.channelType(EpollServerDomainSocketChannel.class);
} else if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
return NettyServerBuilder.forPort(port);
} else {
return NettyServerBuilder.forAddress(new InetSocketAddress(InetAddresses.forString(address), port));
}
}
@Override
// Keep this in sync with NettyGrpcServerFactory#configureKeepAlive
protected void configureKeepAlive(final NettyServerBuilder builder) {
if (this.properties.isEnableKeepAlive()) {
builder.keepAliveTime(this.properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(this.properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS);
}
builder.permitKeepAliveTime(this.properties.getPermitKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.permitKeepAliveWithoutCalls(this.properties.isPermitKeepAliveWithoutCalls());
}
@Override
// Keep this in sync with NettyGrpcServerFactory#configureSecurity
protected void configureSecurity(final NettyServerBuilder builder) {
final Security security = this.properties.getSecurity();
if (security.isEnabled()) {
final Resource certificateChain =
requireNonNull(security.getCertificateChain(), "certificateChain not configured");
final Resource privateKey = requireNonNull(security.getPrivateKey(), "privateKey not configured");
SslContextBuilder sslContextBuilder;
try (InputStream certificateChainStream = certificateChain.getInputStream();
InputStream privateKeyStream = privateKey.getInputStream()) {
sslContextBuilder = GrpcSslContexts.forServer(certificateChainStream, privateKeyStream,
security.getPrivateKeyPassword());
} catch (IOException | RuntimeException e) {
throw new IllegalArgumentException("Failed to create SSLContext (PK/Cert)", e);
}
if (security.getClientAuth() != ClientAuth.NONE) {
sslContextBuilder.clientAuth(of(security.getClientAuth()));
final Resource trustCertCollection = security.getTrustCertCollection();
if (trustCertCollection != null) {
try (InputStream trustCertCollectionStream = trustCertCollection.getInputStream()) {
sslContextBuilder.trustManager(trustCertCollectionStream);
} catch (IOException | RuntimeException e) {
throw new IllegalArgumentException("Failed to create SSLContext (TrustStore)", e);
}
}
}
if (security.getCiphers() != null && !security.getCiphers().isEmpty()) {
sslContextBuilder.ciphers(security.getCiphers());
}
if (security.getProtocols() != null && security.getProtocols().length > 0) {
sslContextBuilder.protocols(security.getProtocols());
}
try {
builder.sslContext(sslContextBuilder.build());
} catch (final SSLException e) {
throw new IllegalStateException("Failed to create ssl context for grpc server", e);
}
}
}
/**
* Converts the given client auth option to netty's client auth.
*
* @param clientAuth The client auth option to convert.
* @return The converted client auth option.
*/
protected static io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth of(final ClientAuth clientAuth) {
switch (clientAuth) {
case NONE:
return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.NONE;
case OPTIONAL:
return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.OPTIONAL;
case REQUIRE:
return io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.REQUIRE;
default:
throw new IllegalArgumentException("Unsupported ClientAuth: " + clientAuth);
}
}
}
|
package net.mgsx.game.examples.platformer.rendering;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.ashley.core.Family;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.shaders.BaseShader;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ShaderProvider;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import net.mgsx.game.core.GamePipeline;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.core.annotations.Asset;
import net.mgsx.game.core.annotations.Editable;
import net.mgsx.game.core.annotations.EditableSystem;
import net.mgsx.game.core.annotations.Storable;
import net.mgsx.game.core.components.Hidden;
import net.mgsx.game.core.helpers.FilesShaderProgram;
import net.mgsx.game.examples.platformer.sensors.WaterZone;
import net.mgsx.game.plugins.g3d.components.G3DModel;
import net.mgsx.game.plugins.g3d.systems.G3DRendererSystem;
// TODO refactor things up here ... FBO ... shaders ...
@Storable("example.platformer.post-processing")
@EditableSystem("Post Processing Effects")
public class PlatformerPostProcessing extends EntitySystem
{
private FrameBuffer fbo, fbo2, blurA, blurB;
private Sprite screenSprite;
private SpriteBatch batch;
@Editable
transient public FilesShaderProgram blurProgram;
@Asset("shaders/flat-vertex.glsl") // -vertex.glsl -fragment.glsl
public ShaderProgram flatProgram;
private ShaderProgram postProcessShader;
private float time;
private int timeLocation;
private int worldLocation;
private int frequencyLocation;
private int rateLocation;
private int texture1Location, texture2Location;
private Vector2 world = new Vector2();
private ModelBatch modelBatch;
Renderable renderable = new Renderable();
Shader flatShader;
private GameScreen engine;
private G3DRendererSystem renderSystem;
private boolean shadersLoaded = false;
public PlatformerPostProcessing(GameScreen engine) {
super(GamePipeline.AFTER_RENDER);
this.engine = engine;
}
public FrameBuffer getMainTarget(){
return fbo;
}
@Override
public void addedToEngine(Engine engine) {
super.addedToEngine(engine);
renderSystem = engine.getSystem(G3DRendererSystem.class);
// loadShaders();
}
private Family waterEntity = Family.all(G3DModel.class, WaterZone.class).exclude(Hidden.class).get();
private Family nonwaterEntity = Family.all(G3DModel.class).exclude(WaterZone.class).exclude(Hidden.class).get();
// private Array<ModelInstance> waterModels = new Array<ModelInstance>();
// private Array<ModelInstance> nonWaterModels = new Array<ModelInstance>();
public static class Settings
{
@Editable public float speed = 1.5f;
@Editable public float frequency = 100f;
@Editable public float rate = 0.01f;
@Editable public boolean enabled = false;
@Editable public boolean blur = true;
@Editable public float nearStart = -3;
@Editable public float nearEnd = -5;
@Editable public float farStart = 13;
@Editable public float farEnd = 17f;
@Editable public boolean debugDepth;
@Editable public boolean debugConfusion;
@Editable public boolean debugLimits;
@Editable public float blurSize = 1.5f;
}
@Editable public Settings settings = new Settings();
@Override
public void update(float deltaTime)
{
if(!shadersLoaded){
loadShaders();
shadersLoaded = true;
}
if(!settings.enabled) return;
fbo.end();
renderSystem.fboStack.pop();
// TODO find a way to see FBO (FBO stack ? push/pop/bind ... etc ...
if(!settings.debugDepth)
fbo2.begin();
Gdx.gl.glClearColor(0,0,0,0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(engine.camera);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
flatProgram.begin();
flatProgram.setUniformf("waterFactor", 1.f);
for(Entity e : getEngine().getEntitiesFor(waterEntity)){
modelBatch.render(e.getComponent(G3DModel.class).modelInstance, flatShader);
}
engine.camera.near = 1f;
engine.camera.far = 200.f;
modelBatch.flush();
flatProgram.end();
flatProgram.begin();
//modelBatch.render(waterModels);
flatProgram.setUniformf("waterFactor", 0.0f);
//modelBatch.render(nonWaterModels);
for(Entity e : getEngine().getEntitiesFor(nonwaterEntity)){
modelBatch.render(e.getComponent(G3DModel.class).modelInstance, flatShader);
}
flatProgram.end();
modelBatch.end();
if(!settings.debugDepth)
fbo2.end();
if(settings.debugDepth){
return;
}
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
if(settings.blur )
{
blurA.begin();
batch.setShader(blurProgram.program());
batch.begin();
blurProgram.program().setUniformf("dir", new Vector2(settings.blurSize / (float)Gdx.graphics.getWidth(),0));
batch.draw(fbo.getColorBufferTexture(), 0, 0);
batch.end();
blurA.end();
blurB.begin();
batch.setShader(blurProgram.program());
batch.begin();
blurProgram.program().setUniformf("dir", new Vector2(0, settings.blurSize / (float)Gdx.graphics.getHeight()));
batch.draw(blurA.getColorBufferTexture(), 0, 0);
batch.end();
blurB.end();
}
time += deltaTime * settings.speed;
float d = engine.camera.unproject(new Vector3()).z;
d = 4;
Vector3 v = engine.camera.project(new Vector3(0,0,d));
world.set(-v.x / Gdx.graphics.getWidth(), -v.y / Gdx.graphics.getHeight());
batch.setShader(postProcessShader);
batch.disableBlending();
batch.begin();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
blurA.getColorBufferTexture().bind(0);
fbo2.getColorBufferTexture().bind(1);
blurB.getColorBufferTexture().bind(2);
Gdx.gl.glActiveTexture(GL20.GL_TEXTURE0);
PerspectiveCamera perspective = (PerspectiveCamera)engine.camera;
Vector2 near = new Vector2(
(settings.nearStart + perspective.position.z - perspective.near) / (perspective.far - perspective.near),
(settings.nearEnd + perspective.position.z - perspective.near) / (perspective.far - perspective.near));
Vector2 far = new Vector2(
(settings.farStart + perspective.position.z - perspective.near) / (perspective.far - perspective.near),
// new Vector3(0, 0, settings.farStart).prj(engine.camera.projection).z,
//new Vector3(0, 0, 0).prj(engine.camera.combined).z,
(settings.farEnd + perspective.position.z - perspective.near) / (perspective.far - perspective.near));
postProcessShader.setUniformf("focusNear", near);
postProcessShader.setUniformf("focusFar", far);
postProcessShader.setUniformi(texture1Location, 1);
postProcessShader.setUniformi(texture2Location, 2);
postProcessShader.setUniformf(timeLocation, time);
postProcessShader.setUniformf(worldLocation, world);
postProcessShader.setUniformf(frequencyLocation, settings.frequency);
postProcessShader.setUniformf(rateLocation, settings.rate);
screenSprite.draw(batch);
batch.end();
}
void validate()
{
int w = Gdx.graphics.getWidth();
int h = Gdx.graphics.getHeight();
if(fbo == null || fbo.getWidth() != w || fbo.getHeight() != h)
{
if(fbo != null){
fbo.dispose();
fbo2.dispose();
blurA.dispose();
blurB.dispose();
}
fbo = new FrameBuffer(Format.RGBA8888, w, h, true);
fbo2 = new FrameBuffer(Format.RGBA8888, w, h, true);
blurA = new FrameBuffer(Format.RGBA8888, w, h, false);
blurB = new FrameBuffer(Format.RGBA8888, w, h, false);
screenSprite = new Sprite(fbo.getColorBufferTexture(), w, h);
screenSprite.setFlip(false, true);
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(batch.getProjectionMatrix()); // XXX necessary ?
}
}
private ShaderProgram loadShader(FileHandle vertex, FileHandle fragment)
{
ShaderProgram sp = new ShaderProgram(
prefix(vertex),
prefix(fragment));
return sp;
}
private String prefix(FileHandle shaderFile) {
String code = "";
if(settings.debugDepth) code += "#define DEBUG_DEPTH\n";
if(settings.debugConfusion) code += "#define DEBUG_CONFUSION\n";
if(settings.debugLimits) code += "#define DEBUG_LIMITS\n";
code += shaderFile.readString();
return code;
}
@Editable
public void loadShaders()
{
// TODO unload before ...
// TODO Auto-generated method stub
// postProcessShader = SpriteBatch.createDefaultShader();
postProcessShader = loadShader(
Gdx.files.internal("shaders/water-vertex.glsl"),
Gdx.files.internal("shaders/water-fragment.glsl"));
postProcessShader.begin();
if(!postProcessShader.isCompiled()){
System.err.println(postProcessShader.getLog());
}
postProcessShader.end();
timeLocation = postProcessShader.getUniformLocation("u_time");
worldLocation = postProcessShader.getUniformLocation("u_world");
frequencyLocation = postProcessShader.getUniformLocation("u_frequency");
rateLocation = postProcessShader.getUniformLocation("u_rate");
texture1Location = postProcessShader.getUniformLocation("u_texture1");
texture2Location = postProcessShader.getUniformLocation("u_texture2");
blurProgram = new FilesShaderProgram(
Gdx.files.internal("shaders/blurx-vertex.glsl"),
Gdx.files.internal("shaders/blurx-fragment.glsl"));
flatShader = new BaseShader() {
@Override
public void init() {
register(DefaultShader.Inputs.projTrans, DefaultShader.Setters.projViewWorldTrans);
// TODO Auto-generated method stub
Renderable renderable = new Renderable();
MeshBuilder mb = new MeshBuilder();
VertexAttributes attributes = new VertexAttributes(VertexAttribute.Position());
mb.begin(attributes);
renderable.meshPart.mesh = mb.end();
init(flatProgram, renderable);
program = flatProgram;
}
@Override
public int compareTo(Shader other) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean canRender(Renderable instance) {
// TODO Auto-generated method stub
return true;
}
};
flatShader.init();
modelBatch = new ModelBatch(new ShaderProvider() {
@Override
public Shader getShader(Renderable renderable) {
return flatShader;
}
@Override
public void dispose() {
}
});
batch = new SpriteBatch(1, postProcessShader);
}
}
|
package org.springframework.ide.vscode.commons.javadoc;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IField;
import org.springframework.ide.vscode.commons.java.IJavaElement;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.languageserver.JavadocParams;
import org.springframework.ide.vscode.commons.languageserver.JavadocResponse;
import org.springframework.ide.vscode.commons.languageserver.STS4LanguageClient;
import org.springframework.ide.vscode.commons.util.Renderable;
import org.springframework.ide.vscode.commons.util.Renderables;
public class JdtLsJavadocProvider implements IJavadocProvider {
private static final Logger log = LoggerFactory.getLogger(JdtLsJavadocProvider.class);
private STS4LanguageClient client;
private String projectUri;
public JdtLsJavadocProvider(STS4LanguageClient client, String projectUri) {
super();
this.client = client;
this.projectUri = projectUri;
}
private IJavadoc produceJavadocFromMd(JavadocResponse response) {
String md = response.getContent();
if (md != null) {
final Renderable renderableDoc = Renderables.mdBlob(md);
return new IJavadoc() {
@Override
public Renderable getRenderable() {
return renderableDoc;
}
};
}
return null;
}
private IJavadoc javadoc(IJavaElement element) {
long start = System.currentTimeMillis();
try {
log.info("Fetching javadoc {}", element.getBindingKey());
JavadocResponse response = client.javadoc(new JavadocParams(projectUri, element.getBindingKey())).get(10, TimeUnit.SECONDS);
log.info("Fetching javadoc {} took {} ms", element.getBindingKey(), System.currentTimeMillis()-start);
return produceJavadocFromMd(response);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("Fetching javadoc {} failed", element.getBindingKey(), e);
return null;
}
}
@Override
public IJavadoc getJavadoc(IType type) {
return javadoc(type);
}
@Override
public IJavadoc getJavadoc(IField field) {
return javadoc(field);
}
@Override
public IJavadoc getJavadoc(IMethod method) {
return javadoc(method);
}
@Override
public IJavadoc getJavadoc(IAnnotation annotation) {
return javadoc(annotation);
}
}
|
package com.konkerlabs.platform.registry.business.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.konkerlabs.platform.registry.business.model.Application;
import com.konkerlabs.platform.registry.business.model.Tenant;
import com.konkerlabs.platform.registry.business.model.User;
import com.konkerlabs.platform.registry.business.model.validation.CommonValidations;
import com.konkerlabs.platform.registry.business.services.api.ApplicationService;
import com.konkerlabs.platform.registry.business.services.api.PrivateStorageService;
import com.konkerlabs.platform.registry.business.services.api.ServiceResponse;
import com.konkerlabs.platform.registry.business.services.api.ServiceResponseBuilder;
import com.konkerlabs.platform.registry.storage.model.PrivateStorage;
import com.konkerlabs.platform.registry.storage.repositories.PrivateStorageRepository;
import com.konkerlabs.platform.utilities.parsers.json.JsonParsingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class PrivateStorageServiceImpl implements PrivateStorageService {
private static Logger LOG = LoggerFactory.getLogger(PrivateStorageServiceImpl.class);
@Autowired
private JsonParsingService jsonParsingService;
@Autowired
private PrivateStorageRepository privateStorageRepository;
private static final String COLLECTION_KEY_PATTERN = "[a-zA-Z0-9\\-_]{2,100}";
@Override
public ServiceResponse<PrivateStorage> save(Tenant tenant,
Application application,
User user,
String collectionName,
String collectionContent) throws JsonProcessingException {
ServiceResponse<PrivateStorage> validationResponse = validate(tenant, application, collectionName);
if (!validationResponse.isOk()) {
return validationResponse;
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
if (!jsonParsingService.isValid(collectionContent)) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_INVALID_JSON.getCode())
.build();
}
if (isPrivateStorageFull(tenant)) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_IS_FULL.getCode())
.build();
}
Map<String, Object> content = jsonParsingService.toMap(collectionContent);
if (!content.containsKey("_id")) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_NO_COLLECTION_ID_FIELD.getCode())
.build();
}
collectionName = getCollectionName(tenant, application, collectionName);
PrivateStorage fromDB = privateStorageRepository.findById(collectionName, content.get("_id").toString());
if (Optional.ofNullable(fromDB).isPresent()) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_COLLECTION_CONTENT_ALREADY_EXISTS.getCode())
.build();
}
privateStorageRepository.save(collectionName, content);
return ServiceResponseBuilder.<PrivateStorage>ok()
.withResult(PrivateStorage.builder()
.collectionName(collectionName)
.collectionContent(jsonParsingService.toJsonString(content))
.build())
.build();
}
private String getCollectionName(Tenant tenant, Application application, String collectionName) {
return MessageFormat.format("{0}-{1}-{2}", tenant.getDomainName(), application.getName(), collectionName);
}
private boolean isPrivateStorageFull(Tenant tenant) {
Long privateStorageSizeByte = Optional.ofNullable(tenant.getPrivateStorageSize()).orElse(0l);
Long limitSize = 1073741824l;
return privateStorageSizeByte.compareTo(limitSize) > 0;
}
@Override
public ServiceResponse<PrivateStorage> update(Tenant tenant,
Application application,
User user,
String collectionName,
String collectionContent) throws JsonProcessingException {
ServiceResponse<PrivateStorage> validationResponse = validate(tenant, application, collectionName);
if (!validationResponse.isOk()) {
return validationResponse;
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
if (!jsonParsingService.isValid(collectionContent)) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_INVALID_JSON.getCode())
.build();
}
if (isPrivateStorageFull(tenant)) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_IS_FULL.getCode())
.build();
}
Map<String, Object> content = jsonParsingService.toMap(collectionContent);
if (!content.containsKey("_id")) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_NO_COLLECTION_ID_FIELD.getCode())
.build();
}
collectionName = getCollectionName(tenant, application, collectionName);
PrivateStorage fromDB = privateStorageRepository.findById(collectionName, content.get("_id").toString());
if (!Optional.ofNullable(fromDB).isPresent()) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_COLLECTION_CONTENT_DOES_NOT_EXIST.getCode())
.build();
}
PrivateStorage privateStorage = privateStorageRepository.update(collectionName, content);
return ServiceResponseBuilder.<PrivateStorage>ok()
.withResult(privateStorage)
.build();
}
@Override
public ServiceResponse<PrivateStorage> remove(Tenant tenant,
Application application,
User user,
String collectionName,
String id) throws JsonProcessingException {
ServiceResponse<PrivateStorage> validationResponse = validate(tenant, application, collectionName);
if (!validationResponse.isOk()) {
return validationResponse;
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
if (!Optional.ofNullable(id).isPresent()) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_COLLECTION_ID_IS_NULL.getCode())
.build();
}
collectionName = getCollectionName(tenant, application, collectionName);
PrivateStorage fromDB = privateStorageRepository.findById(collectionName, id);
if (!Optional.ofNullable(fromDB).isPresent()) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_COLLECTION_CONTENT_DOES_NOT_EXIST.getCode())
.build();
}
privateStorageRepository.remove(collectionName, id);
return ServiceResponseBuilder.<PrivateStorage>ok()
.withMessage(Messages.PRIVATE_STORAGE_REMOVED_SUCCESSFULLY.getCode())
.build();
}
@Override
public ServiceResponse<List<PrivateStorage>> findAll(Tenant tenant,
Application application,
User user,
String collectionName) throws JsonProcessingException {
ServiceResponse<List<PrivateStorage>> validationResponse = validate(tenant, application, collectionName);
if (!validationResponse.isOk()) {
return validationResponse;
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<List<PrivateStorage>>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
collectionName = getCollectionName(tenant, application, collectionName);
return ServiceResponseBuilder.<List<PrivateStorage>>ok()
.withResult(privateStorageRepository.findAll(collectionName))
.build();
}
@Override
public ServiceResponse<PrivateStorage> findById(Tenant tenant,
Application application,
User user,
String collectionName,
String id) throws JsonProcessingException {
ServiceResponse<PrivateStorage> validationResponse = validate(tenant, application, collectionName);
if (!validationResponse.isOk()) {
return validationResponse;
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
if (!Optional.ofNullable(id).isPresent()) {
return ServiceResponseBuilder.<PrivateStorage>error()
.withMessage(Validations.PRIVATE_STORAGE_COLLECTION_ID_IS_NULL.getCode())
.build();
}
collectionName = getCollectionName(tenant, application, collectionName);
return ServiceResponseBuilder.<PrivateStorage>ok()
.withResult(privateStorageRepository.findById(collectionName, id))
.build();
}
@Override
public ServiceResponse<List<String>> listCollections(Tenant tenant, Application application, User user) {
if (!Optional.ofNullable(tenant).isPresent()) {
return ServiceResponseBuilder.<List<String>>error().withMessage(CommonValidations.TENANT_NULL.getCode()).build();
}
if (!Optional.ofNullable(application).isPresent()) {
return ServiceResponseBuilder.<List<String>>error()
.withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build();
}
if (Optional.ofNullable(user.getApplication()).isPresent()
&& !application.equals(user.getApplication())) {
return ServiceResponseBuilder.<List<String>>error()
.withMessage(ApplicationService.Validations.APPLICATION_HAS_NO_PERMISSION.getCode())
.build();
}
List<String> collectionsName = privateStorageRepository.listCollections()
.stream()
.filter(f -> f.contains("-".concat(application.getName())))
.map(c -> c.substring(c.lastIndexOf(application.getName()) + application.getName().length() + 1))
.collect(Collectors.toList());
return ServiceResponseBuilder.<List<String>>ok()
.withResult(collectionsName)
.build();
}
private <T> ServiceResponse<T> validate(Tenant tenant, Application application, String collectionName) {
if (!Optional.ofNullable(tenant).isPresent()) {
return ServiceResponseBuilder.<T>error().withMessage(CommonValidations.TENANT_NULL.getCode()).build();
}
if (!Optional.ofNullable(application).isPresent()) {
return ServiceResponseBuilder.<T>error()
.withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()).build();
}
if (!Optional.ofNullable(collectionName).isPresent()
|| !collectionName.matches(COLLECTION_KEY_PATTERN)) {
return ServiceResponseBuilder.<T>error()
.withMessage(Validations.PRIVATE_STORAGE_INVALID_COLLECTION_NAME.getCode())
.build();
}
return ServiceResponseBuilder.<T>ok()
.build();
}
}
|
package com.redhat.ceylon.eclipse.code.refactor;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getProjectTypeChecker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.RenameParticipant;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberOrTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.DocLink;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportMemberOrType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberOrTypeExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedType;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.vfs.IFileVirtualFile;
public class RenameJavaElementRefactoringParticipant extends RenameParticipant {
private IMember javaDeclaration;
protected boolean initialize(Object element) {
javaDeclaration= (IMember) element;
return getArguments().getUpdateReferences() &&
getProjectTypeChecker(javaDeclaration.getJavaProject().getProject())!=null;
}
public String getName() {
return "Rename participant for Ceylon source";
}
public RefactoringStatus checkConditions(IProgressMonitor pm,
CheckConditionsContext context) {
return new RefactoringStatus();
}
public Change createChange(IProgressMonitor pm) throws CoreException {
final IProject project = javaDeclaration.getJavaProject().getProject();
final String newName = getArguments().getNewName();
final String oldName = javaDeclaration.getElementName();
final HashMap<IFile,Change> changes= new HashMap<IFile,Change>();
TypeChecker tc = getProjectTypeChecker(project);
if (tc==null) return null;
for (PhasedUnit phasedUnit: tc.getPhasedUnits().getPhasedUnits()) {
final List<ReplaceEdit> edits = new ArrayList<ReplaceEdit>();
Tree.CompilationUnit cu = phasedUnit.getCompilationUnit();
cu.visit(new Visitor() {
@Override
public void visit(ImportMemberOrType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(QualifiedMemberOrTypeExpression that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclaration());
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(QualifiedType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
protected void visitIt(Tree.Identifier id, Declaration dec) {
visitIt(id.getText(), id.getStartIndex(), dec);
}
protected void visitIt(String name, int offset, Declaration dec) {
if (dec!=null && dec.getQualifiedNameString()
.equals(getQualifiedName(javaDeclaration)) &&
name.equals(javaDeclaration.getElementName())) {
edits.add(new ReplaceEdit(offset, oldName.length(), newName));
}
}
protected String getQualifiedName(IMember dec) {
IJavaElement parent = dec.getParent();
if (parent instanceof ICompilationUnit) {
return parent.getParent().getElementName() + "::" +
dec.getElementName();
}
else if (dec.getDeclaringType()!=null) {
return getQualifiedName(dec.getDeclaringType()) + "." +
dec.getElementName();
}
else {
return "@";
}
}
@Override
public void visit(DocLink that) {
super.visit(that);
//TODO: fix copy/paste from RenameRefactoring
String text = that.getText();
int scopeIndex = text.indexOf("::");
int start = scopeIndex<0 ? 0 : scopeIndex+2;
Integer offset = that.getStartIndex();
Declaration base = that.getBase();
if (base!=null) {
int index = text.indexOf('.', start);
String name = index<0 ?
text.substring(start) :
text.substring(start, index);
visitIt(name, offset+start, base);
start = index;
int i=0;
List<Declaration> qualified = that.getQualified();
if (qualified!=null) {
while (start>0 && i<qualified.size()) {
index = text.indexOf('.', start);
name = index<0 ?
text.substring(start) :
text.substring(start, index);
visitIt(name, offset+start, qualified.get(i++));
start = index;
}
}
}
}
});
if (!edits.isEmpty()) {
try {
IFile file = ((IFileVirtualFile) phasedUnit.getUnitFile()).getFile();
TextFileChange change= new TextFileChange(file.getName(), file);
change.setEdit(new MultiTextEdit());
changes.put(file, change);
for (ReplaceEdit edit: edits) {
change.addEdit(edit);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (changes.isEmpty())
return null;
CompositeChange result= new CompositeChange("Ceylon source changes");
for (Iterator<Change> iter= changes.values().iterator(); iter.hasNext();) {
result.add((Change) iter.next());
}
return result;
}
}
|
package com.orientechnologies.orient.etl.transformer;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.ETLBaseTest;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class OLogTransformerTest extends ETLBaseTest {
@Test
public void testPrefix() throws Exception {
ByteArrayOutputStream output = getByteArrayOutputStream();
String cfgJson = "{source: { content: { value: 'id,text\n1,Hello\n2,Bye'} }, extractor : { csv: {} }, transformers : [{ log : {prefix:'-> '}}], loader : { test: {} } }";
process(cfgJson);
List<ODocument> res = getResult();
ODocument doc = res.get(0);
String[] stringList = output.toString().split(System.getProperty("line.separator"));
assertEquals("[1:log] INFO -> {id:1,text:Hello}", stringList[1]);
assertEquals("[2:log] INFO -> {id:2,text:Bye}", stringList[2]);
}
@Test
public void testPostfix() throws Exception {
ByteArrayOutputStream output = getByteArrayOutputStream();
String cfgJson = "{source: { content: { value: 'id,text\n1,Hello\n2,Bye'} }, extractor : { csv : {} }, transformers : [{ log : {postfix:'-> '}}], loader : { test: {} } }";
process(cfgJson);
List<ODocument> res = getResult();
ODocument doc = res.get(0);
String[] stringList = output.toString().split(System.getProperty("line.separator"));
assertEquals("[1:log] INFO {id:1,text:Hello}-> ", stringList[1]);
assertEquals("[2:log] INFO {id:2,text:Bye}-> ", stringList[2]);
}
private ByteArrayOutputStream getByteArrayOutputStream() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
System.setOut(new PrintStream(output, true));
return output;
}
}
|
package org.opensingular.requirement.module.wicket.view.printer;
import org.apache.commons.io.IOUtils;
import org.opensingular.lib.commons.util.Loggable;
import org.opensingular.requirement.commons.box.action.config.EnabledPrintsPerSessionMap;
import org.opensingular.requirement.commons.service.ExtratoGeneratorService;
import org.springframework.beans.factory.ObjectFactory;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Optional;
@Controller
public class PrintFormController implements Loggable {
@Inject
private ExtratoGeneratorService extratoGeneratorService;
@Autowired
private ObjectFactory<EnabledPrintsPerSessionMap> enabledPrintsPerSessionMapObjectFactory;
/**
* Method responsible for find the requiriment by the UUID, and generate the PDF in a new tab, if the requiriment exists.
* <p>
* This method is called by ExtratoAction of the requiriment's box.
*
* @param response The httpServlet response, responsible for show the 410 error, if the UUID have already be used, or the file PDF.
* @param uuid The uuid of the requiriment.
* @throws IOException
*/
@RequestMapping(value = {"/requirement/printmf/{uuid}", "/worklist/printmf/{uuid}"}, method = RequestMethod.GET)
public void printMainForm(HttpServletResponse response, @PathVariable String uuid) throws IOException {
Optional<Long> possibleRequirementCod = enabledPrintsPerSessionMapObjectFactory.getObject().pop(uuid);
if (!possibleRequirementCod.isPresent()) {
response.sendRedirect("/public/error/410");
return;
}
Optional<File> optPdf = extratoGeneratorService.generatePdfFile(possibleRequirementCod.get());
optPdf.ifPresent(pdf -> {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"" + pdf.getName() + "\"");
response.setContentLength((int) pdf.length());
try (FileInputStream fis = new FileInputStream(pdf)) {
IOUtils.copy(fis, response.getOutputStream());
} catch (IOException e) {
getLogger().error("Error obtaing the File", e);
}
});
}
}
|
package nl.tno.fpai.demo.scenario.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicLong;
import nl.tno.fpai.demo.scenario.ScenarioManager;
import nl.tno.fpai.demo.scenario.data.Connection;
import nl.tno.fpai.demo.scenario.data.IdSet;
import nl.tno.fpai.demo.scenario.data.Scenario;
import nl.tno.fpai.demo.scenario.data.ScenarioConfiguration;
import nl.tno.fpai.demo.scenario.data.ScenarioConfiguration.Type;
import org.flexiblepower.messaging.ConnectionManager;
import org.flexiblepower.messaging.ConnectionManager.EndpointPort;
import org.flexiblepower.messaging.ConnectionManager.ManagedEndpoint;
import org.flexiblepower.messaging.ConnectionManager.PotentialConnection;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.metatype.AttributeDefinition;
import org.osgi.service.metatype.MetaTypeInformation;
import org.osgi.service.metatype.MetaTypeService;
import org.osgi.service.metatype.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.annotation.component.Activate;
import aQute.bnd.annotation.component.Component;
import aQute.bnd.annotation.component.ConfigurationPolicy;
import aQute.bnd.annotation.component.Deactivate;
import aQute.bnd.annotation.component.Reference;
import aQute.bnd.annotation.metatype.Configurable;
import aQute.bnd.annotation.metatype.Meta;
@Component(immediate = true,
provide = { ScenarioManager.class },
designate = ScenarioManagerImpl.Config.class,
configurationPolicy = ConfigurationPolicy.optional)
public class ScenarioManagerImpl implements ScenarioManager {
public interface Config {
@Meta.AD(deflt = "scenarios.xml",
description = "The file that should be loaded during activation.",
required = false)
String filename();
}
private static final Logger log = LoggerFactory.getLogger(ScenarioManagerImpl.class);
private ConfigurationAdmin configurationAdmin;
@Reference
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
private MetaTypeService metatype;
@Reference
public void setMetatype(MetaTypeService metatype) {
this.metatype = metatype;
}
public ConnectionManager connectionManager;
@Reference
public void setConnectionManager(ConnectionManager connectionManager) {
this.connectionManager = connectionManager;
}
private final Set<Configuration> configurations = Collections.synchronizedSet(new HashSet<Configuration>());
private final Set<PotentialConnection> activeConnections = Collections.synchronizedSet(new HashSet<PotentialConnection>());
private Map<String, Scenario> scenarios;
@Activate
public void activate(BundleContext context, Map<String, ?> properties) throws Exception {
Config config = Configurable.createConfigurable(Config.class, properties);
String filename = config.filename();
File file = new File(filename);
InputStream is = null;
if (file.exists() && file.isFile() && file.canRead()) {
is = new FileInputStream(file);
} else {
is = getClass().getClassLoader().getResourceAsStream(filename);
}
try {
if (is == null) {
throw new FileNotFoundException("Can not find the file with name: " + filename);
}
scenarios = ScenarioReader.readScenarios(new InputStreamReader(is));
if (log.isDebugEnabled()) {
log.debug("Loaded scenarios");
for (Entry<String, Scenario> entry : scenarios.entrySet()) {
log.debug("Loaded scenario [{}]\n{}", entry.getKey(), entry.getValue());
}
}
} catch (Exception ex) {
log.warn("Could not load scenarios from file [" + filename + "]", ex);
throw ex;
} finally {
is.close();
}
setStatus("Loaded scenario's, nothing started");
log.info(" ............
log.info("The demonstrator has started, go to http://localhost:8080 to see the demonstration");
log.info(" ------------============------------ ");
}
@Deactivate
public void deactivate() {
// purgeAll();
}
@Override
public Set<String> getScenarios() {
return scenarios.keySet();
}
@Override
public synchronized void startScenario(String name) {
Scenario scenario = scenarios.get(name);
if (scenario != null) {
purgeAll();
startScenario(scenario);
setStatus("Loaded scenario [" + name + "]");
}
}
private volatile String status;
private volatile int count, total;
private void setStatus(int count) {
this.count = count;
if (log.isDebugEnabled()) {
log.debug("Status = {}", getStatus());
}
}
private void setStatus(String status) {
setStatus(status, 0);
}
private void setStatus(String status, int total) {
count = 0;
this.total = total;
this.status = status;
if (log.isDebugEnabled()) {
log.debug("Status = {}", getStatus());
}
}
public String getStatus() {
if (total <= 0) {
return status;
} else {
return status + " " + count + "/" + total;
}
}
private void purgeAll() {
int count = 0;
setStatus("Purging old configurations", configurations.size());
for (Configuration configuration : configurations) {
try {
configuration.delete();
setStatus(++count);
} catch (IOException e) {
log.warn("Could not delete configuration " + configuration, e);
}
}
for (PotentialConnection conn : activeConnections) {
conn.disconnect();
}
configurations.clear();
activeConnections.clear();
setStatus("Loaded scenario's, nothing started");
}
private void startScenario(Scenario scenario) {
setStatus("Starting scenario [" + scenario.getName() + "] ", scenario.getConfigurations().size());
Map<String, Set<String>> idMap = new HashMap<String, Set<String>>();
idMap = new HashMap<String, Set<String>>();
// Generate the needed ids
AtomicLong idGenerator = new AtomicLong();
for (IdSet idSet : scenario.getIdSets().values()) {
Set<String> ids = new HashSet<String>();
for (int i = 0; i < idSet.getCount(); i++) {
ids.add(Long.toString(idGenerator.getAndIncrement()));
}
idMap.put(idSet.getName(), ids);
}
Map<String, List<String>> refs = new HashMap<String, List<String>>();
int count = 0;
for (ScenarioConfiguration config : scenario.getConfigurations()) {
List<String> pids = startConfiguration(config, idMap);
String ref = config.getReference();
if (ref != null && !pids.isEmpty()) {
refs.put(ref, pids);
}
setStatus(++count);
}
for (Connection connection : scenario.getConnections()) {
List<String> fromPids = refs.get(connection.getFromRef());
List<String> toPids = refs.get(connection.getToRef());
for (String fromPid : fromPids) {
for (String toPid : toPids) {
EndpointPort fromPort = findPort(fromPid, connection.getFromPort());
EndpointPort toPort = findPort(toPid, connection.getToPort());
if (fromPort != null && toPort != null) {
PotentialConnection conn = fromPort.getPotentialConnection(toPort);
if (conn != null) {
conn.connect();
activeConnections.add(conn);
}
}
}
}
}
}
private EndpointPort findPort(String pid, String portName) {
ManagedEndpoint endpoint = connectionManager.getEndpoint(pid);
if (endpoint == null) {
synchronized (connectionManager) {
try {
connectionManager.wait(1000);
} catch (InterruptedException e) {
}
endpoint = connectionManager.getEndpoint(pid);
if (endpoint == null) {
return null;
}
}
}
return endpoint.getPort(portName);
}
private List<String> startConfiguration(ScenarioConfiguration config, Map<String, Set<String>> idMap) {
List<String> pids = new ArrayList<String>();
try {
Bundle bundle = getBundle(config.getBundleId());
if (bundle != null) {
Set<String> ids = idMap.get(config.getIdRef());
if (ids != null) {
for (String id : ids) {
pids.add(startConfiguration(config, bundle, id, idMap));
}
} else {
String id = UUID.randomUUID().toString();
pids.add(startConfiguration(config, bundle, id, idMap));
}
} else {
log.info("Ignoring configuration, the given bundle can not be found\n" + config);
}
} catch (Exception ex) {
log.error("Could not create configuration", ex);
}
return pids;
}
private String startConfiguration(ScenarioConfiguration config,
Bundle bundle,
String id,
Map<String, Set<String>> idMap) throws IOException {
Dictionary<String, String[]> properties = translateProperties(config.getProperties(), id, idMap);
MetaTypeInformation metaTypeInformation = metatype.getMetaTypeInformation(bundle);
ObjectClassDefinition objectClassDefinition = metaTypeInformation.getObjectClassDefinition(config.getId(), null);
Dictionary<String, Object> transformedProperties = transformTypes(objectClassDefinition, properties);
Configuration configuration;
if (config.getType() == Type.MULTIPLE) {
configuration = configurationAdmin.createFactoryConfiguration(config.getId(), bundle.getLocation());
} else {
configuration = configurationAdmin.getConfiguration(config.getId(), bundle.getLocation());
}
configuration.update(transformedProperties);
configurations.add(configuration);
return configuration.getPid();
}
private Dictionary<String, String[]> translateProperties(Map<String, String> properties,
String id,
Map<String, Set<String>> idMap) {
Dictionary<String, String[]> result = new Hashtable<String, String[]>();
for (Entry<String, String> entry : properties.entrySet()) {
result.put(entry.getKey(), translateValue(Arrays.asList(entry.getValue().split(",")), id, idMap));
}
return result;
}
private String[] translateValue(List<String> values, String id, Map<String, Set<String>> idMap) {
List<String> newValues = new ArrayList<String>(values.size());
for (String value : values) {
newValues.add(value.replace("%id%", id));
}
List<String> toReplace = new ArrayList<String>();
for (Entry<String, Set<String>> idEntry : idMap.entrySet()) {
toReplace.clear();
String toMatch = "%" + idEntry.getKey() + "%";
Iterator<String> it = newValues.iterator();
while (it.hasNext()) {
String value = it.next();
if (value.contains(toMatch)) {
toReplace.add(value);
it.remove();
}
}
for (String value : toReplace) {
for (String replace : idEntry.getValue()) {
newValues.add(value.replace(toMatch, replace));
}
}
}
if (newValues.size() == 0) {
return null;
} else if (newValues.size() == 1) {
return new String[] { newValues.get(0) };
} else {
return newValues.toArray(new String[newValues.size()]);
}
}
private Dictionary<String, Object> transformTypes(ObjectClassDefinition objectClassDefinition,
Dictionary<String, String[]> properties) {
Dictionary<String, Object> result = new Hashtable<String, Object>();
for (AttributeDefinition attributeDefinition : objectClassDefinition.getAttributeDefinitions(ObjectClassDefinition.ALL)) {
String key = attributeDefinition.getID();
String[] current = properties.get(key);
if (current == null) {
current = attributeDefinition.getDefaultValue();
if (current == null) {
log.warn("Missing property for key [{}] on {}", key, objectClassDefinition.getName());
current = new String[] { "" };
}
}
if (attributeDefinition.getCardinality() < 0) {
// Should use a vector
Vector<Object> vector = new Vector<Object>(current.length);
for (String value : current) {
vector.add(parse(attributeDefinition.getType(), value));
}
} else if (attributeDefinition.getCardinality() > 0) {
// Should use an array
result.put(key, parse(attributeDefinition.getType(), current));
} else {
// Must be a single value
result.put(key, parse(attributeDefinition.getType(), current[0]));
}
}
return result;
}
private Object parse(int type, String[] value) {
switch (type) {
case AttributeDefinition.BOOLEAN: {
boolean[] array = new boolean[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Boolean.parseBoolean(value[ix]);
}
return array;
}
case AttributeDefinition.BYTE: {
byte[] array = new byte[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Byte.parseByte(value[ix]);
}
return array;
}
case AttributeDefinition.CHARACTER: {
char[] array = new char[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = value[ix].isEmpty() ? ' ' : value[ix].charAt(0);
}
return array;
}
case AttributeDefinition.DOUBLE: {
double[] array = new double[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Double.parseDouble(value[ix]);
}
return array;
}
case AttributeDefinition.FLOAT: {
float[] array = new float[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Float.parseFloat(value[ix]);
}
return array;
}
case AttributeDefinition.INTEGER: {
int[] array = new int[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Integer.parseInt(value[ix]);
}
return array;
}
case AttributeDefinition.LONG: {
long[] array = new long[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Long.parseLong(value[ix]);
}
return array;
}
case AttributeDefinition.SHORT: {
short[] array = new short[value.length];
for (int ix = 0; ix < array.length; ix++) {
array[ix] = Short.parseShort(value[ix]);
}
return array;
}
default: {
return value;
}
}
}
private Object parse(int type, String value) {
switch (type) {
case AttributeDefinition.BOOLEAN:
return Boolean.parseBoolean(value);
case AttributeDefinition.BYTE:
return Byte.parseByte(value);
case AttributeDefinition.CHARACTER:
return value.isEmpty() ? ' ' : value.charAt(0);
case AttributeDefinition.DOUBLE:
return Double.parseDouble(value);
case AttributeDefinition.FLOAT:
return Float.parseFloat(value);
case AttributeDefinition.INTEGER:
return Integer.parseInt(value);
case AttributeDefinition.LONG:
return Long.parseLong(value);
case AttributeDefinition.SHORT:
return Short.parseShort(value);
default:
return value;
}
}
private Bundle getBundle(String bundleId) {
for (Bundle bundle : FrameworkUtil.getBundle(getClass()).getBundleContext().getBundles()) {
if (bundleId.equals(bundle.getSymbolicName())) {
return bundle;
}
}
return null;
}
}
|
package org.eclipse.mylyn.internal.sandbox.ui.hyperlinks;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.IHyperlink;
/**
* @author Jingwen Ou
*/
public class JavaResourceHyperlinkExtension extends AbstractResourceHyperlinkExtension {
private static final String JAVA_PREFIX = "java\\sclass\\s";
@Override
protected String getResourceExpressions() {
return JAVA_PREFIX + DEFAULT_QUALIFIED_NAME;
}
@Override
protected boolean isResourceExists(String resourceName) {
return true;
}
@Override
protected IHyperlink createHyperlinkInstance(IRegion region, String resourceName) {
return new JavaResourceHyperlink(region, resourceName);
}
}
|
package server;
import java.lang.ClassNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.EOFException;
import java.lang.Thread;
import utils.Buffer;
import utils.PriorityBuffer;
import utils.Log;
import utils.Matrix;
import utils.NetworkNode;
import utils.Request;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
public class SimpleServer extends NetworkNode {
private ServerSocket socketServer = null;
private Socket socket = null;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
private int BUFFER_SIZE = 1000;
private PriorityBuffer<Request> buffer = new PriorityBuffer<Request>(BUFFER_SIZE);
private boolean receiveFinished = false;
private long computeTime = 0L;
public SimpleServer(String port) {
this.setPort(port);
}
private Thread t = new Thread(new Runnable() {
public void run() {
outputStream = getSocketOutputStream(socket);
int sleepTime = 0;
Request r;
try{
while ((r=buffer.take()) !=null) {
r.setServerProcessingTimeStamp(new DateTime());
long startComputeTime = computeTime;
Matrix response = compute( r.getMatrix() , r.getExposant() );
r.setCalculationTime(computeTime - startComputeTime);
Request dataToSend = r;
dataToSend.setMatrix(response);
dataToSend.setServerSendingTimeStamp(new DateTime());
Log.print("Sending request #" + r.getId());
send( dataToSend , outputStream);
}
send( null, outputStream);
} catch (InterruptedException e){
Log.error("Interrupeted while waiting");
}
}
});
public void start() {
Log.print("Server - start()");
try {
socketServer = new ServerSocket(this.getPort());
socket = socketServer.accept();
} catch (IOException e) {
Log.error("Server start() - Cannot connect sockets");
}
Log.print("Connection established : " + socketServer.getLocalSocketAddress());
inputStream = getSocketInputStream(socket);
t.start();
int i = 1;
while (true) {
Request r = receive(inputStream);
if(r != null){
r.setServerReceivingTimeStamp(new DateTime());
}
else {
Log.print("All the data were received...");
receiveFinished = true;
break;
}
Log.print("Request received: #" + r.getId());
if( ! buffer.add(r) ) {
Log.print("Buffer is full");
}
r = null;
i++;
}
try{
t.join();
} catch (InterruptedException e){
Log.error("Unable to join receiving thread");
}
Log.print("Server - end start()");
}
public void stop() {
try {
outputStream.close();
inputStream.close();
socketServer.close();
socket.close();
} catch (IOException e) {
Log.error("IOException - Server.stop()");
e.printStackTrace();
}
Log.print("Server - end stop()");
}
private Matrix compute(Matrix m, int exposant) {
long startTime = System.nanoTime();
Matrix result = new Matrix(m.matrixPowered(exposant), m.getSize());
computeTime += (System.nanoTime() - startTime);
return result;
}
}
|
package gov.nih.nci.calab.service.util;
public class CalabConstants {
public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String STORAGE_BOX = "Box";
public static final String STORAGE_SHELF = "Shelf";
public static final String STORAGE_RACK = "Rack";
public static final String STORAGE_FREEZER = "Freezer";
public static final String STORAGE_ROOM = "Room";
public static final String STORAGE_LAB = "Lab";
public static final String MASK_STATUS = "Masked";
public static final String OTHER = "Other";
public static final String ALIQUOT = "Aliquot";
public static final String SAMPLE_CONTAINER = "Sample_container";
public static final String RUN = "Run";
public static final String FILEUPLOAD_PROPERTY = "fileupload.properties";
public static final String EMPTY = "N/A";
public static final String INPUT = "input";
public static final String OUTPUT = "output";
}
|
package bg.elsys.ip.rest;
public class Car {
private int id;
private String name;
private Color color;
public Car(int id, String name, Color color) {
this.id = id;
this.name = name;
this.color = color;
}
public Car(String name, Color color) {
this(CarsData.getInstance().getNextId(), name, color);
}
public Car() {
this("", null);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
|
package gov.nih.nci.cananolab.util;
import java.util.HashMap;
import java.util.Map;
public class CaNanoLabConstants {
public static final String DOMAIN_MODEL_NAME = "caNanoLab";
public static final String SDK_BEAN_JAR = "caNanoLabSDK-beans.jar";
public static final String CSM_APP_NAME = "caNanoLab";
public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy";
// File upload
public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties";
public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles";
public static final String EMPTY = "N/A";
// caNanoLab property file
public static final String CANANOLAB_PROPERTY = "caNanoLab.properties";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES,
BOOLEAN_NO };
public static final String DEFAULT_SAMPLE_PREFIX = "NANO-";
public static final String DEFAULT_APP_OWNER = "NCICB";
public static final String APP_OWNER;
public static final String VIEW_COL_DELIMITER = "~~~";
public static final String VIEW_CLASSNAME_DELIMITER = "!!!";
static {
String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY,
"applicationOwner").trim();
if (appOwner == null || appOwner.length() == 0)
appOwner = DEFAULT_APP_OWNER;
APP_OWNER = appOwner;
}
public static final String SAMPLE_PREFIX;
static {
String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY,
"samplePrefix");
if (samplePrefix == null || samplePrefix.length() == 0)
samplePrefix = DEFAULT_SAMPLE_PREFIX;
SAMPLE_PREFIX = samplePrefix;
}
public static final String GRID_INDEX_SERVICE_URL;
static {
String gridIndexServiceURL = PropertyReader.getProperty(
CANANOLAB_PROPERTY, "gridIndexServiceURL").trim();
GRID_INDEX_SERVICE_URL = gridIndexServiceURL;
}
/*
* The following Strings are nano specific
*
*/
public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER };
// TODO, cleanup
// public static final String REPORT = "Report";
public static final String ASSOCIATED_FILE = "Other Associated File";
public static final String PROTOCOL_FILE = "Protocol File";
public static final String FOLDER_PARTICLE = "particles";
// public static final String FOLDER_REPORT = "reports";
public static final String FOLDER_PUBLICATION = "publications";
public static final String FOLDER_PROTOCOL = "protocols";
public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] {
"Free Radicals", "Peroxide" };
public static final String CHARACTERIZATION_FILE = "characterizationFile";
public static final int MAX_VIEW_TITLE_LENGTH = 23;
public static final String CSM_DATA_CURATOR = APP_OWNER + "_DataCurator";
public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher";
public static final String CSM_ADMIN = APP_OWNER + "_Administrator";
public static final String CSM_PUBLIC_GROUP = "Public";
public static final String[] VISIBLE_GROUPS = new String[] {
CSM_DATA_CURATOR, CSM_RESEARCHER };
public static final String AUTO_COPY_ANNOTATION_PREFIX = "COPY";
public static final String AUTO_COPY_ANNNOTATION_VIEW_COLOR = "red";
public static final String CSM_READ_ROLE = "R";
public static final String CSM_DELETE_ROLE = "D";
public static final String CSM_EXECUTE_ROLE = "E";
public static final String CSM_CURD_ROLE = "CURD";
public static final String CSM_CUR_ROLE = "CUR";
public static final String CSM_READ_PRIVILEGE = "READ";
public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE";
public static final String CSM_DELETE_PRIVILEGE = "DELETE";
public static final String CSM_CREATE_PRIVILEGE = "CREATE";
public static final String CSM_PG_SAMPLE = "sample";
public static final String CSM_PG_PROTOCOL = "protocol";
public static final String CSM_PG_PARTICLE = "nanoparticle";
public static final String CSM_PG_PUBLICATION = "publication";
public static final String PHYSICAL_CHARACTERIZATION_CLASS_NAME = "Physical Characterization";
public static final String IN_VITRO_CHARACTERIZATION_CLASS_NAME = "In Vitro Characterization";
public static final short CHARACTERIZATION_ROOT_DISPLAY_ORDER = 0;
public static final Map<String, Integer> CHARACTERIZATION_ORDER_MAP = new HashMap<String, Integer>();
static {
CHARACTERIZATION_ORDER_MAP.put(new String("Physical Characterization"),
new Integer(0));
CHARACTERIZATION_ORDER_MAP.put(new String("In Vitro Characterization"),
new Integer(1));
CHARACTERIZATION_ORDER_MAP.put(new String("Toxicity"), new Integer(2));
CHARACTERIZATION_ORDER_MAP.put(new String("Cytotoxicity"), new Integer(
3));
CHARACTERIZATION_ORDER_MAP.put(new String("Immunotoxicity"),
new Integer(4));
CHARACTERIZATION_ORDER_MAP.put(new String("Blood Contact"),
new Integer(5));
CHARACTERIZATION_ORDER_MAP.put(new String("Immune Cell Function"),
new Integer(6));
}
/* image file name extension */
public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN",
"DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE",
"JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD",
"PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD",
"RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM",
"YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG",
"STD", "SVG", "SXD", "WMF" };
public static final String[] PRIVATE_DISPATCHES = { "create", "delete",
"setupUpdate", "setupDeleteAll", "add", "remove" };
public static final String PHYSICAL_ASSAY_PROTOCOL = "physical assay";
public static final String INVITRO_ASSAY_PROTOCOL = "in vitro assay";
public static final String NODE_UNAVAILABLE = "Unable to connect to the grid location that you selected";
// default discovery internal for grid index server
public static final int DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS = 20;
public static final String DOMAIN_MODEL_VERSION = "1.4";
public static final String GRID_SERVICE_PATH = "wsrf-canano/services/cagrid/CaNanoLabService";
}
|
package org.csstudio.sds.components.ui.internal.figures;
import java.util.Calendar;
import org.csstudio.platform.ui.util.CustomMediaFactory;
import org.csstudio.sds.components.ui.internal.figureparts.Range;
import org.csstudio.sds.components.ui.internal.figureparts.RoundScale;
import org.csstudio.sds.components.ui.internal.figureparts.AbstractScale.LabelSide;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
/**
* To avoid to start CSS frequently to see the
* drawing result of the widget figure, this program simply draw the widget figure on a shell.
* <p>
* This is a common java program, <b>not</b> a JUnit test.
* </p>
* @author Xihui Chen
*
*/
public class WidgetFigureTest {
public static void main(String[] args) {
final Shell shell = new Shell();
final LightweightSystem lws = new LightweightSystem(shell);
final Figure parent = new Figure();
parent.setBackgroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_WHITE));
parent.setLayoutManager(new XYLayout());
lws.setContents(parent);
shell.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event event) {
parent.removeAll();
Rectangle testFigureBounds = new Rectangle(0,
0, shell.getBounds().width, shell.getBounds().height);
Rectangle scaleBounds = new Rectangle(10,
10, shell.getBounds().width-50, shell.getBounds().height-50);
RoundScaleTest testFigure = new RoundScaleTest(scaleBounds);
//XSliderFigureTest testFigure = new XSliderFigureTest(scaleBounds);
//TankFigureTest testFigure = new TankFigureTest(scaleBounds);
//ThermoFigureTest testFigure = new ThermoFigureTest(scaleBounds);
parent.add(testFigure,testFigureBounds);
lws.paint(event.gc);
}
});
shell.setSize(500, 500);
shell.open();
shell.setText("Widget Figure Test");
Display display = Display.getDefault();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
class RoundScaleTest extends Figure {
public RoundScaleTest(Rectangle bounds) {
RoundScale scale = new RoundScale();
scale.setRange(new Range(0 + 5 * 3600000d, 12*3600000d+ 5 * 3600000d));
scale.setBounds(bounds);
//scale.setTimeUnit(Calendar.MINUTE);
scale.setFormatPattern("H");
scale.setMajorGridStep(3600000);
scale.setTickLableSide(LabelSide.Secondary);
//scale.setLogScale(true);
scale.setDateEnabled(true);
scale.setStartAngle(90);
scale.setEndAngle(90.00000001);
//scale.setScaleLineVisible(false);
add(scale);
}
}
class XSliderFigureTest extends Figure {
public XSliderFigureTest(Rectangle bounds) {
ScaledSliderFigure slider = new ScaledSliderFigure();
slider.setBounds(bounds);
slider.setBackgroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_WHITE));
slider.setMaximum(1000);
slider.setMinimum(0);
slider.setValue(50);
slider.setFillColor(CustomMediaFactory.COLOR_RED);
slider.setFillBackgroundColor(CustomMediaFactory.COLOR_GRAY);
slider.setForegroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_BLACK));
slider.setTransparent(true);
slider.setHihiLevel(90);
slider.setLogScale(true);
slider.setEffect3D(true);
//slider.setHorizontal(true);
add(slider);
}
}
class TankFigureTest extends Figure {
public TankFigureTest(Rectangle bounds) {
RefreshableTankFigure tank = new RefreshableTankFigure();
tank.setBounds(bounds);
tank.setBackgroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_WHITE));
tank.setValue(50);
tank.setFillColor(CustomMediaFactory.COLOR_BLUE);
tank.setFillBackgroundColor(CustomMediaFactory.COLOR_RED);
tank.setForegroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_BLACK));
tank.setTransparent(true);
tank.setHihiLevel(90);
add(tank);
}
}
class ThermoFigureTest extends Figure {
public ThermoFigureTest(Rectangle bounds) {
RefreshableThermoFigure thermo = new RefreshableThermoFigure();
thermo.setBounds(bounds);
thermo.setBackgroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_WHITE));
thermo.setValue(28.01);
thermo.setFillColor(CustomMediaFactory.COLOR_RED);
thermo.setFillBackgroundColor(CustomMediaFactory.COLOR_GRAY);
thermo.setForegroundColor(CustomMediaFactory.getInstance().getColor(
CustomMediaFactory.COLOR_BLACK));
thermo.setTransparent(true);
thermo.setHihiLevel(90);
add(thermo);
}
}
|
package com.splicemachine.derby.stream.spark;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.sql.Activation;
import com.splicemachine.db.iapi.store.access.TransactionController;
import com.splicemachine.db.iapi.store.access.conglomerate.TransactionManager;
import com.splicemachine.db.iapi.store.raw.Transaction;
import com.splicemachine.derby.serialization.SpliceObserverInstructions;
import com.splicemachine.derby.iapi.sql.execute.SpliceOperation;
import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext;
import com.splicemachine.derby.impl.SpliceSpark;
import com.splicemachine.derby.impl.store.access.BaseSpliceTransaction;
import com.splicemachine.derby.jdbc.SpliceTransactionResourceImpl;
import com.splicemachine.si.impl.driver.SIDriver;
import com.splicemachine.stream.accumulator.BadRecordsAccumulator;
import com.splicemachine.derby.stream.iapi.OperationContext;
import com.splicemachine.si.api.txn.TxnView;
import com.splicemachine.utils.SpliceLogUtils;
import org.apache.log4j.Logger;
import org.apache.spark.Accumulable;
import org.apache.spark.Accumulator;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
public class SparkOperationContext<Op extends SpliceOperation> implements OperationContext<Op> {
protected static Logger LOG = Logger.getLogger(SparkOperationContext.class);
public SpliceObserverInstructions soi;
public SpliceTransactionResourceImpl impl;
public Activation activation;
public SpliceOperationContext context;
public Op op;
public TxnView txn;
public Accumulator<Integer> rowsRead;
public Accumulator<Integer> rowsJoinedLeft;
public Accumulator<Integer> rowsJoinedRight;
public Accumulator<Integer> rowsProduced;
public Accumulator<Integer> rowsFiltered;
public Accumulator<Integer> rowsWritten;
public Accumulable<List<String>,String> badRecordsAccumulable;
public boolean permissive;
public boolean failed;
public int numberBadRecords = 0;
private int failBadRecordCount = -1;
private byte[] operationUUID;
public SparkOperationContext() {
}
protected SparkOperationContext(Op spliceOperation) {
this.op = spliceOperation;
this.activation = op.getActivation();
try {
this.txn = spliceOperation.getCurrentTransaction();
} catch (StandardException se) {
throw new RuntimeException(se);
}
String baseName = "(" + op.resultSetNumber() + ") " + op.getName();
this.rowsRead = SpliceSpark.getContext().accumulator(0, baseName + " rows read");
this.rowsFiltered = SpliceSpark.getContext().accumulator(0, baseName + " rows filtered");
this.rowsWritten = SpliceSpark.getContext().accumulator(0, baseName + " rows written");
this.rowsJoinedLeft = SpliceSpark.getContext().accumulator(0, baseName + " rows joined left");
this.rowsJoinedRight = SpliceSpark.getContext().accumulator(0, baseName + " rows joined right");
this.rowsProduced= SpliceSpark.getContext().accumulator(0, baseName + " rows produced");
this.badRecordsAccumulable = SpliceSpark.getContext().accumulable(new ArrayList<String>(), baseName+" BadRecords",new BadRecordsAccumulator());
this.operationUUID = spliceOperation.getUniqueSequenceID();
}
protected SparkOperationContext(Activation activation) {
this.op = null;
this.activation = activation;
try {
TransactionController transactionExecute = activation.getLanguageConnectionContext().getTransactionExecute();
Transaction rawStoreXact = ((TransactionManager) transactionExecute).getRawStoreXact();
this.txn = ((BaseSpliceTransaction) rawStoreXact).getActiveStateTxn();
} catch (StandardException se) {
throw new RuntimeException(se);
}
this.rowsRead = SpliceSpark.getContext().accumulator(0, "rows read");
this.rowsFiltered = SpliceSpark.getContext().accumulator(0, "rows filtered");
this.rowsWritten = SpliceSpark.getContext().accumulator(0, "rows written");
this.rowsJoinedLeft = SpliceSpark.getContext().accumulator(0, "rows joined left");
this.rowsJoinedRight = SpliceSpark.getContext().accumulator(0, "rows joined right");
this.rowsProduced= SpliceSpark.getContext().accumulator(0, "rows produced");
}
public void readExternalInContext(ObjectInput in) throws IOException, ClassNotFoundException
{}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(failBadRecordCount);
out.writeBoolean(permissive);
out.writeBoolean(op!=null);
if (op!=null) {
if (soi == null)
soi = SpliceObserverInstructions.create(op.getActivation(), op);
out.writeObject(soi);
out.writeObject(op);
}
SIDriver.driver().getOperationFactory().writeTxn(txn, out);
out.writeObject(rowsRead);
out.writeObject(rowsFiltered);
out.writeObject(rowsWritten);
out.writeObject(rowsJoinedLeft);
out.writeObject(rowsJoinedRight);
out.writeObject(rowsProduced);
out.writeObject(badRecordsAccumulable);
if (operationUUID != null) {
out.writeInt(operationUUID.length);
out.write(operationUUID);
} else {
out.writeInt(-1);
}
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
failBadRecordCount = in.readInt();
permissive = in.readBoolean();
SpliceSpark.setupSpliceStaticComponents();
boolean isOp = in.readBoolean();
if (isOp) {
soi = (SpliceObserverInstructions) in.readObject();
op = (Op) in.readObject();
}
txn = SIDriver.driver().getOperationFactory().readTxn(in);
rowsRead = (Accumulator) in.readObject();
rowsFiltered = (Accumulator) in.readObject();
rowsWritten = (Accumulator) in.readObject();
rowsJoinedLeft = (Accumulator<Integer>) in.readObject();
rowsJoinedRight = (Accumulator<Integer>) in .readObject();
rowsProduced = (Accumulator<Integer>) in.readObject();
badRecordsAccumulable = (Accumulable<List<String>,String>) in.readObject();
boolean prepared = false;
try {
impl = new SpliceTransactionResourceImpl();
impl.prepareContextManager();
prepared = true;
impl.marshallTransaction(txn);
if (isOp) {
activation = soi.getActivation(impl.getLcc());
context = SpliceOperationContext.newContext(activation);
op.init(context);
}
readExternalInContext(in);
} catch (Exception e) {
SpliceLogUtils.logAndThrowRuntime(LOG, e);
} finally {
if (prepared) {
impl.popContextManager();
}
}
int len = in.readInt();
if (len > 0) {
operationUUID = new byte[len];
in.readFully(operationUUID);
}
}
@Override
public void prepare() {
impl.prepareContextManager();
}
@Override
public void reset() {
impl.resetContextManager();
}
@Override
public Op getOperation() {
return op;
}
@Override
public Activation getActivation() {
return activation;
}
@Override
public TxnView getTxn() {
return txn;
}
@Override
public void recordRead() {
rowsRead.add(1);
}
@Override
public void recordFilter() {
rowsFiltered.add(1);
}
@Override
public void recordWrite() {
rowsWritten.add(1);
}
@Override
public void recordJoinedLeft() {
rowsJoinedLeft.add(1);
}
@Override
public void recordJoinedRight() {
rowsJoinedRight.add(1);
}
@Override
public void recordProduced() {
rowsProduced.add(1);
}
@Override
public long getRecordsRead() {
return rowsRead.value();
}
@Override
public long getRecordsFiltered() {
return rowsFiltered.value();
}
@Override
public long getRecordsWritten() {
return rowsWritten.value();
}
@Override
public void pushScope(String displayName) {
SpliceSpark.pushScope(displayName);
}
@Override
public void pushScope() {
SpliceSpark.pushScope(getOperation().getSparkStageName());
}
@Override
public void pushScopeForOp(Scope step) {
SpliceSpark.pushScope(getOperation().getSparkStageName() + ": " + step.displayName());
}
@Override
public void pushScopeForOp(String step) {
SpliceSpark.pushScope(getOperation().getSparkStageName() + ": " + step);
}
@Override
public void popScope() {
SpliceSpark.popScope();
}
@Override
public void recordBadRecord(String badRecord) {
numberBadRecords++;
badRecordsAccumulable.add(badRecord);
if (numberBadRecords>= this.failBadRecordCount)
failed=true;
}
@Override
public List<String> getBadRecords() {
List<SpliceOperation> operations = getOperation().getSubOperations();
List<String> badRecords = badRecordsAccumulable.value();
if (operations!=null) {
for (SpliceOperation operation : operations) {
if (operation.getOperationContext()!=null)
badRecords.addAll(operation.getOperationContext().getBadRecords());
}
}
return badRecords;
}
@Override
public byte[] getOperationUUID() {
return operationUUID;
}
@Override
public boolean isPermissive() {
return permissive;
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public void setPermissive() {
this.permissive = true;
}
@Override
public void setFailBadRecordCount(int failBadRecordCount) {
this.failBadRecordCount = failBadRecordCount;
}
}
|
package org.openhealthtools.mdht.uml.cda.ccd.operations;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.openhealthtools.mdht.uml.cda.CDAFactory;
import org.openhealthtools.mdht.uml.cda.Informant12;
import org.openhealthtools.mdht.uml.cda.Reference;
import org.openhealthtools.mdht.uml.cda.operations.CDAValidationTest;
import org.openhealthtools.mdht.uml.hl7.datatypes.CE;
import org.openhealthtools.mdht.uml.hl7.datatypes.CS;
import org.openhealthtools.mdht.uml.hl7.datatypes.DatatypesFactory;
import org.openhealthtools.mdht.uml.hl7.datatypes.II;
import org.openhealthtools.mdht.uml.hl7.vocab.x_ActRelationshipExternalReference;
/**
* This class serves as the root class for most of the JUnit 4 test cases for
* CCD. It has one test method called testAllValidations that serves to dispatch
* a large number of different tests. Each of these tests is specified by
* instances of the inner class CDATestCase. The exact collection of these
* instances is obtained by calling the abstract method getTestCases, which is
* implemented by subclasses of this class. Each of these subclasses defines the
* tests for a particular CCD Operations test.
*
* The tests themselves are defined as subclasses of CDATestCase, and all are
* defined in this file. Each specific subclass tests the validation of one
* specific feature/attribute of the CCD object under test.
*
* This "complicated" arrangement greatly reduces redundancy in the test code.
* Virtually all of the tests are the same except for the details of which
* feature to test and the exact validation operation to execute. However, there
* is no strict inheritance hierarchy that would allow one test to be defined
* and then customized by subclasses. The different CCD classes to test have a
* very mixed set of features. The solution is to define a set of test templates
* (subclasses of CDATestCase), one for each feature to test, and then have the
* CCD class specific test classes simply return the appropriate collection of
* these to a method (testAllValdations) that can execute them. This way the
* different tests can be mixed and matched to the specific CCD class being
* tested.
*
* As you read the code here and in other files, you see two different related
* variable names "objectToTest" and "eObjectToValidate." The former is used in
* the test template described above, the later is a global defined in the
* superclass to this one (CDAValidationTest) that is initialized by the setUp
* method. Ideally, there would be only a single approach (the former), but both
* work.
*/
@SuppressWarnings("nls")
public abstract class CCDValidationTest extends CDAValidationTest {
// this is a comment to be deleted
abstract protected static class CCDValidationTestCase extends
CDAValidationTestCase {
protected final String featureName;
public CCDValidationTestCase(final String featureName) {
super(featureName);
this.featureName = featureName;
}
@Override
@SuppressWarnings("synthetic-access")
public void doTest(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
try {
validateExpectFail(objectToTest, diagnostician, map);
doSet(objectToTest);
validateExpectPass(objectToTest, diagnostician, map);
} catch (final UnsupportedOperationException uoe) {
fail(CDAValidationTest
.createUnsupportedOperationFailureMessage(featureName,
uoe));
}
}
protected void doSet(final EObject objectToTest) {
doSet(objectToTest, featureName);
}
protected void doSet(final EObject objectToTest,
final String featureName) {
doSet(objectToTest, featureName, getValueToSet());
}
protected void doSet(final EObject objectToTest,
final String featureName, final Object value) {
objectToTest.eSet(objectToTest.eClass().getEStructuralFeature(
featureName), value);
}
protected void doSet(final EObject objectToTest,
final Object value) {
objectToTest.eSet(objectToTest.eClass().getEStructuralFeature(
featureName), value);
}
abstract protected Object getValueToSet();
} // CCDValidationTestCase
/**
* This class tests title validation
*/
abstract public static class TitleCCDValidationTest extends
CCDValidationTestCase {
/**
* nothing
*/
public TitleCCDValidationTest() {
super("title");
}
@Override
protected Object getValueToSet() {
return DatatypesFactory.eINSTANCE.createST();
}
} // TitleCCDValidationTest
// MoodCode Test Case
abstract protected static class MoodCodeCCDValidationTest extends
CCDValidationTestCase {
public MoodCodeCCDValidationTest() {
super("moodCode");
}
/**
* @see org.openhealthtools.mdht.uml.cda.ccd.operations.CCDValidationTest.CCDValidationTestCase#doTest(org.eclipse.emf.ecore.EObject, org.eclipse.emf.common.util.BasicDiagnostic, java.util.Map)
*/
@SuppressWarnings("synthetic-access")
@Override
public void doTest(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
try {
// The mood code is initialized to a default value so it should
// always be defined.
validateExpectPass(objectToTest, diagnostician, map);
} catch (final UnsupportedOperationException uoe) {
fail(CDAValidationTest
.createUnsupportedOperationFailureMessage("moodCode",
uoe));
}
}
@Override
protected Object getValueToSet() {
// Not used
return null;
}
} // MoodCode Validation Test
// MoodCode Value Test Case
abstract protected static class MoodCodeValueCCDValidationTest extends
CCDValidationTestCase {
public MoodCodeValueCCDValidationTest() {
super("moodCode");
}
/**
* @see org.openhealthtools.mdht.uml.cda.ccd.operations.CCDValidationTest.CCDValidationTestCase#doTest(org.eclipse.emf.ecore.EObject, org.eclipse.emf.common.util.BasicDiagnostic, java.util.Map)
*/
@SuppressWarnings("synthetic-access")
@Override
public void doTest(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
try {
for (final Object moodCodeValue : getModeCodeValues()) {
// set the value here
doSet(objectToTest,moodCodeValue);
validateExpectPass(objectToTest, diagnostician, map);
}
} catch (final UnsupportedOperationException uoe) {
fail(CDAValidationTest
.createUnsupportedOperationFailureMessage("moodCode",
uoe));
}
}
abstract List<Object> getModeCodeValues() ;
@Override
protected Object getValueToSet() {
// Not used
return null;
}
} // MoodCode Value Validation Test
/**
* Validate Text Test Case
*/
abstract public static class TextCCDValidationTest extends
CCDValidationTestCase {
/**
* nothing
*/
public TextCCDValidationTest() {
super("text");
}
@Override
protected Object getValueToSet() {
return CDAFactory.eINSTANCE.createStrucDocText();
}
} // TextCCDValidationTest
/**
* Validate Id Test Case
*/
abstract public static class IDCCDValidationTest extends
CCDValidationTestCase {
/**
* Nothing
*/
public IDCCDValidationTest() {
super("id");
}
@Override
protected Object getValueToSet() {
final BasicEList<II> retValue = new BasicEList<II>();
retValue.add(DatatypesFactory.eINSTANCE.createII());
return retValue;
}
} // IDCCDValidationTest
// Validate Status Code Test Case
abstract protected static class StatusCodeCCDValidationTest extends
CCDValidationTestCase {
protected final String statusCode;
protected final String statusCodeCodeSystem;
public StatusCodeCCDValidationTest(final String statusCode,
final String statusCodeCodeSystem) {
super("statusCode");
this.statusCode = statusCode;
this.statusCodeCodeSystem = statusCodeCodeSystem;
}
@Override
protected Object getValueToSet() {
final CS retValue = DatatypesFactory.eINSTANCE.createCS();
retValue.setCode(statusCode);
retValue.setCodeSystem(statusCodeCodeSystem);
return retValue;
}
} // StatusCodeCCDValidationTest
// Validate Code Test Case
/**
* This class is a JUnit4 test case.
*/
public abstract static class CodeCCDValidationTest extends
CCDValidationTestCase {
private final String code;
private final String codeSystem;
/**
* @param code
* @param codeSystem
*/
public CodeCCDValidationTest(final String code, final String codeSystem) {
super("code");
this.code = code;
this.codeSystem = codeSystem;
}
@Override
protected Object getValueToSet() {
final CE retValue = DatatypesFactory.eINSTANCE.createCE();
retValue.setCode(code);
retValue.setCodeSystem(codeSystem);
return retValue;
}
} // CodeCCDValidationTest
/**
* Validate Effective Time Test Case
*/
abstract public static class EffectiveTimeCCDValidationTest extends
CCDValidationTestCase {
/**
* nothing
*/
public EffectiveTimeCCDValidationTest() {
super("effectiveTime");
}
@Override
protected Object getValueToSet() {
return DatatypesFactory.eINSTANCE.createIVL_TS();
}
} // EffectiveTimeCCDValidationTest
// Validate Observation Value Test Case
abstract protected static class ObservationValueCCDValidationTest extends
CCDValidationTestCase {
protected String observationValueCodeSystem;
public ObservationValueCCDValidationTest(
final String observationValueCodeSystem) {
super("value");
this.observationValueCodeSystem = observationValueCodeSystem;
}
@Override
protected Object getValueToSet() {
final EList<CE> retValue = new BasicEList<CE>();
final CE ce = DatatypesFactory.eINSTANCE.createCE();
ce.setCodeSystem(observationValueCodeSystem);
retValue.add(ce);
return retValue;
}
} // ObservationValueCCDValidationTest
// Validate Entry Test Case
abstract protected static class EntryCCDValidationTest extends
CCDValidationTestCase {
public EntryCCDValidationTest() {
super("entry");
}
} // EntryCCDValidationTest
// Validate Entry Relationship Test Case
abstract protected static class EntryRelationshipCCDValidationTest extends
CCDValidationTestCase {
public EntryRelationshipCCDValidationTest() {
super("entryRelationship");
}
} // EntryRelationshipCCDValidationTest
// Validate Information Source Test Case
abstract protected static class InformationSourceCCDValidationTest extends
CCDValidationTestCase {
private static final String INFORMANT_FEATURE_NAME = "informant";
private static final String REFERENCE_FEATURE_NAME = "reference";
public InformationSourceCCDValidationTest() {
super(INFORMANT_FEATURE_NAME);
}
@SuppressWarnings( { "unchecked", "synthetic-access" })
@Override
public void doTest(final EObject objectToTest,
final BasicDiagnostic diagnostician,
final Map<Object, Object> map) {
try {
final EStructuralFeature referenceFeature = objectToTest
.eClass().getEStructuralFeature(REFERENCE_FEATURE_NAME);
validateExpectFail(objectToTest, diagnostician, map);
// The informant collection can be non-empty
final EList<Informant12> informants = new BasicEList<Informant12>();
informants.add(CDAFactory.eINSTANCE.createInformant12());
doSet(objectToTest, INFORMANT_FEATURE_NAME, informants);
validateExpectPass(objectToTest, diagnostician, map);
// Or, if empty
objectToTest.eUnset(objectToTest.eClass()
.getEStructuralFeature(INFORMANT_FEATURE_NAME));
final Reference ref = CDAFactory.eINSTANCE.createReference();
ref.setTypeCode(x_ActRelationshipExternalReference.XCRPT);
((EList<Reference>) objectToTest.eGet(referenceFeature))
.add(ref);
validateExpectPass(objectToTest, diagnostician, map);
} catch (final UnsupportedOperationException uoe) {
fail(CDAValidationTest
.createUnsupportedOperationFailureMessage(
INFORMANT_FEATURE_NAME, uoe));
}
}
@Override
protected Object getValueToSet() {
// Not used in this test
return null;
}
} // InformationSourceCCDValidationTest
} // CCDValidationTest
|
package io.trigger.parse;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import com.google.gson.JsonObject;
import com.parse.ManifestInfo;
import com.parse.ParseAnalytics;
import com.parse.ParsePushBroadcastReceiver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.json.JSONException;
import org.json.JSONObject;
import io.trigger.forge.android.core.ForgeActivity;
import io.trigger.forge.android.core.ForgeApp;
import io.trigger.forge.android.core.ForgeLog;
import io.trigger.forge.android.modules.parse.Constant;
public class ForgePushBroadcastReceiver extends ParsePushBroadcastReceiver {
private static final String channelId = "default";
private static final String channelDescription = "Default";
private static ArrayList<HashMap<String, String>> history = new ArrayList<HashMap<String, String>>();
@Override
public void onPushOpen(Context context, Intent intent) {
ForgeLog.d("io.trigger.parse.ForgePushBroadcastReceiver onPushOpen");
ParseAnalytics.trackAppOpenedInBackground(intent);
Intent activity = new Intent(context, ForgeActivity.class);
activity.putExtras(intent.getExtras());
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
if (hasUpdateNotificationsFeature()) {
history.clear();
}
}
@Override
protected void onPushDismiss(Context context, Intent intent) {
ForgeLog.d("io.trigger.parse.ForgePushBroadcastReceiver onPushDismiss");
super.onPushDismiss(context, intent);
if (hasUpdateNotificationsFeature()) {
history.clear();
}
}
@Override
protected NotificationCompat.Builder getNotification(Context context, Intent intent) {
ForgeLog.d("io.trigger.parse.ForgePushBroadcastReceiver getNotification");
if (VisibilityManager.isVisible() && !hasShowNotificationsWhileVisibleFeature()) {
return null;
}
if (hasUpdateNotificationsFeature()) {
if (updateNotification(context, intent)) {
ForgeLog.d("io.trigger.parse.ForgePushBroadcastReceiver createUpdatableNotification success");
return null; // successfully built and sent it
} else {
ForgeLog.e("io.trigger.parse.ForgePushBroadcastReceiver error failed to create updatable notification. Falling back.");
}
}
NotificationCompat.Builder builder = super.getNotification(context, intent);
if (hasBackgroundColourFeature()) {
builder = setBackgroundColor(builder);
}
return builder;
}
protected JSONObject getPushData(Intent intent) {
ForgeLog.d("io.trigger.parse.ForgePushBroadcastReceiver getPushData");
try {
return new JSONObject(intent.getStringExtra("com.parse.Data"));
} catch (JSONException e) {
ForgeLog.e("io.trigger.parse.ForgePushBroadcastReceiver: Unexpected JSONException when receiving push data: " + e.getLocalizedMessage());
return null;
}
}
protected boolean updateNotification(Context context, Intent intent) {
JSONObject pushData = this.getPushData(intent);
if (pushData == null) {
ForgeLog.e("io.trigger.parse.ForgePushBroadcastReceiver createUpdatableNotification received null pushData");
return false;
}
if (!(pushData.has("alert") || pushData.has("title"))) {
ForgeLog.e("io.trigger.parse.ForgePushBroadcastReceiver createUpdatableNotification requires either an alert or title");
return false;
}
HashMap<String, String> message = new HashMap<String, String>();
message.put("alert", pushData.optString("alert", "Notification received."));
message.put("title", pushData.optString("title", ManifestInfo.getDisplayName(context)));
history.add(message);
String packageName = context.getPackageName();
Bundle extras = intent.getExtras();
Random random = new Random();
Intent contentIntent = new Intent("com.parse.push.intent.OPEN");
contentIntent.setPackage(packageName);
contentIntent.putExtras(extras);
int contentIntentRequestCode = random.nextInt();
PendingIntent pendingContentIntent = PendingIntent.getBroadcast(context, contentIntentRequestCode, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent deleteIntent = new Intent("com.parse.push.intent.DELETE");
deleteIntent.setPackage(packageName);
deleteIntent.putExtras(extras);
int deleteIntentRequestCode = random.nextInt();
PendingIntent pendingDeleteIntent = PendingIntent.getBroadcast(context, deleteIntentRequestCode, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle(message.get("title"))
.setContentText(message.get("alert"))
.setSmallIcon(this.getSmallIconId(context, intent))
.setLargeIcon(this.getLargeIcon(context, intent))
.setContentIntent(pendingContentIntent)
.setDeleteIntent(pendingDeleteIntent)
.setAutoCancel(true)
.setChannelId(channelId) // TODO
.setDefaults(-1);
if (history.size() > 1) {
String text = history.size() + " messages received";
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i = 0; i < history.size(); i++) {
inboxStyle.addLine(history.get(i).get("alert"));
}
inboxStyle.setSummaryText(text);
builder.setStyle(inboxStyle);
builder.setContentText(text);
builder.setNumber(history.size());
} else {
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message.get("alert")));
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
channelDescription,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
if (hasBackgroundColourFeature()) {
builder = setBackgroundColor(builder);
}
Notification notification = builder.build();
if (notification == null) {
return false;
}
try {
notificationManager.notify(1, notification);
} catch (SecurityException e) {
builder.setDefaults(5);
notificationManager.notify(1, builder.build());
return false;
}
return true;
}
private boolean hasUpdateNotificationsFeature() {
JsonObject config = ForgeApp.configForModule(Constant.MODULE_NAME);
return config.has("android") &&
config.getAsJsonObject("android").has("updateNotifications") &&
config.getAsJsonObject("android").get("updateNotifications").getAsBoolean();
}
private boolean hasShowNotificationsWhileVisibleFeature() {
JsonObject config = ForgeApp.configForModule(Constant.MODULE_NAME);
return config.has("android") &&
config.getAsJsonObject("android").has("showNotificationsWhileVisible") &&
config.getAsJsonObject("android").get("showNotificationsWhileVisible").getAsBoolean();
}
private boolean hasBackgroundColourFeature() {
JsonObject config = ForgeApp.configForModule(Constant.MODULE_NAME);
return config.has("android") &&
config.getAsJsonObject("android").has("backgroundColour");
}
private NotificationCompat.Builder setBackgroundColor(NotificationCompat.Builder builder) {
JsonObject config = ForgeApp.configForModule(Constant.MODULE_NAME);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
String colourString = config.getAsJsonObject("android").get("backgroundColour").getAsString();
builder.setColor(Color.parseColor(colourString));
} catch (IllegalArgumentException e) {
ForgeLog.e("Invalid color string for parse.android.backgroundColour: " + e.getMessage());
}
}
return builder;
}
}
|
package org.xins.types;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.xins.util.MandatoryArgumentChecker;
/**
* Enumeration type. An enumeration type only accepts a limited set of
* possible values.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<A href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</A>)
*/
public abstract class EnumType extends Type {
// Class fields
// Class functions
// Constructors
protected EnumType(String name, EnumItem[] items)
throws IllegalArgumentException {
super(name, String.class);
_namesToValues = new HashMap();
_valuesToNames = new HashMap();
// TODO: Use ArrayMap ?
int count = items == null ? 0 : items.length;
String[] values = new String[count];
int actualItems = 0;
for (int i = 0; i < count; i++) {
EnumItem item = items[i];
if (item != null) {
String itemName = item.getName();
String itemValue = item.getValue();
_namesToValues.put(itemName, itemValue);
_valuesToNames.put(itemValue, itemName);
values[actualItems++] = itemValue;
}
}
_values = new String[actualItems];
System.arraycopy(values, 0, _values, 0, actualItems);
}
// Fields
/**
* Map that links symbolic names to enumeration values.
*/
private final Map _namesToValues;
/**
* Map that links enumeration values to their symbolic names.
*/
private final Map _valuesToNames;
/**
* The list of accepted values.
*/
private final String[] _values;
// Methods
protected final boolean isValidValueImpl(String value) {
for (int i = 0; i < _values.length; i++) {
if (_values[i].equals(value)) {
return true;
}
}
return false;
}
protected final Object fromStringImpl(String value) {
return value;
}
public final String getByName(String name) {
return (String) _namesToValues.get(name);
}
public final String getByValue(String value) {
return (String) _valuesToNames.get(value);
}
}
|
package com.akjava.gwt.poseeditor.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.akjava.bvh.client.BVH;
import com.akjava.bvh.client.BVHMotion;
import com.akjava.bvh.client.BVHNode;
import com.akjava.bvh.client.BVHParser;
import com.akjava.bvh.client.BVHParser.ParserListener;
import com.akjava.bvh.client.BVHWriter;
import com.akjava.bvh.client.threejs.AnimationBoneConverter;
import com.akjava.bvh.client.threejs.AnimationDataConverter;
import com.akjava.bvh.client.threejs.BVHConverter;
import com.akjava.gwt.html5.client.HTML5InputRange;
import com.akjava.gwt.html5.client.extra.HTML5Builder;
import com.akjava.gwt.three.client.THREE;
import com.akjava.gwt.three.client.core.Geometry;
import com.akjava.gwt.three.client.core.Intersect;
import com.akjava.gwt.three.client.core.Matrix4;
import com.akjava.gwt.three.client.core.Object3D;
import com.akjava.gwt.three.client.core.Projector;
import com.akjava.gwt.three.client.core.Vector3;
import com.akjava.gwt.three.client.core.Vector4;
import com.akjava.gwt.three.client.core.Vertex;
import com.akjava.gwt.three.client.extras.GeometryUtils;
import com.akjava.gwt.three.client.extras.ImageUtils;
import com.akjava.gwt.three.client.extras.loaders.JSONLoader;
import com.akjava.gwt.three.client.extras.loaders.JSONLoader.LoadHandler;
import com.akjava.gwt.three.client.gwt.GWTGeometryUtils;
import com.akjava.gwt.three.client.gwt.GWTThreeUtils;
import com.akjava.gwt.three.client.gwt.SimpleDemoEntryPoint;
import com.akjava.gwt.three.client.gwt.ThreeLog;
import com.akjava.gwt.three.client.gwt.animation.AnimationBone;
import com.akjava.gwt.three.client.gwt.animation.AnimationBonesData;
import com.akjava.gwt.three.client.gwt.animation.AnimationData;
import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem;
import com.akjava.gwt.three.client.gwt.animation.AnimationKey;
import com.akjava.gwt.three.client.gwt.animation.BoneLimit;
import com.akjava.gwt.three.client.gwt.animation.NameAndVector3;
import com.akjava.gwt.three.client.gwt.animation.WeightBuilder;
import com.akjava.gwt.three.client.gwt.animation.ik.CDDIK;
import com.akjava.gwt.three.client.gwt.animation.ik.IKData;
import com.akjava.gwt.three.client.lights.Light;
import com.akjava.gwt.three.client.materials.Material;
import com.akjava.gwt.three.client.objects.Mesh;
import com.akjava.gwt.three.client.renderers.WebGLRenderer;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class PoseEditor extends SimpleDemoEntryPoint{
private BVH bvh;
protected JsArray<AnimationBone> bones;
private AnimationData animationData;
@Override
protected void beforeUpdate(WebGLRenderer renderer) {
if(root!=null){
root.setPosition((double)positionXRange.getValue()/10, (double)positionYRange.getValue()/10, (double)positionZRange.getValue()/10);
root.getRotation().set(Math.toRadians(rotationRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()));
}
}
@Override
public void resized(int width, int height) {
super.resized(width, height);
leftBottom(bottomPanel);
}
@Override
protected void initializeOthers(WebGLRenderer renderer) {
canvas.setClearColorHex(0x333333);
scene.add(THREE.AmbientLight(0xffffff));
Light pointLight = THREE.DirectionalLight(0xffffff,1);
pointLight.setPosition(0, 10, 300);
scene.add(pointLight);
Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem
pointLight2.setPosition(0, 10, -300);
//scene.add(pointLight2);
root=THREE.Object3D();
scene.add(root);
Geometry geo=THREE.PlaneGeometry(100, 100,10,10);
Mesh mesh=THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0xaaaaaa).wireFrame().build());
mesh.setRotation(Math.toRadians(-90), 0, 0);
root.add(mesh);
//line removed,because of flicking
Mesh xline=GWTGeometryUtils.createLineMesh(THREE.Vector3(-50, 0, 0.001), THREE.Vector3(50, 0, 0.001), 0x880000,3);
//root.add(xline);
Mesh zline=GWTGeometryUtils.createLineMesh(THREE.Vector3(0, 0, -50), THREE.Vector3(0, 0, 50), 0x008800,3);
//root.add(zline);
selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
root.add(selectionMesh);
selectionMesh.setVisible(false);
//line flicked think something
loadBVH("pose.bvh");
IKData ikdata1=new IKData();
//ikdata1.setTargetPos(THREE.Vector3(0, 20, 0));
ikdata1.setLastBoneName("Head");
ikdata1.setBones(new String[]{"Neck1","Neck","Spine","LowerBack"});
//ikdata1.setBones(new String[]{"Neck1","Neck","Spine1","Spine","LowerBack"});
ikdata1.setIteration(9);
ikdatas.add(ikdata1);
IKData ikdata0=new IKData();
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata0.setLastBoneName("RightHand");
ikdata0.setBones(new String[]{"RightForeArm","RightArm"});
// ikdata0.setBones(new String[]{"RightForeArm","RightArm","RightShoulder"});
ikdata0.setIteration(7);
ikdatas.add(ikdata0);
IKData ikdata=new IKData();
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata.setLastBoneName("RightFoot");
ikdata.setBones(new String[]{"RightLeg","RightUpLeg"});
ikdata.setIteration(5);
ikdatas.add(ikdata);
IKData ikdata2=new IKData();
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata2.setLastBoneName("LeftHand");
//ikdata2.setBones(new String[]{"LeftForeArm","LeftArm","LeftShoulder"});
ikdata2.setBones(new String[]{"LeftForeArm","LeftArm"});
ikdata2.setIteration(7);
ikdatas.add(ikdata2);
IKData ikdata3=new IKData();
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata3.setLastBoneName("LeftFoot");
ikdata3.setBones(new String[]{"LeftLeg","LeftUpLeg"});
ikdata3.setIteration(5);
ikdatas.add(ikdata3);
//updateIkLabels();
//calcurate by bvh 80_*
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-118, 0, 0, 60, -170, 0));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-180, 180, -60, 91, -180, 180));
boneLimits.put("RightShoulder",BoneLimit.createBoneLimit(0, 0, 0, 0,0, 0));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -170, 0, 0, 0));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50));
boneLimits.put("LeftShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 91, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-45, 45, -45, 45, -45, 45));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-15, 15, -15, 15, -15, 15));
*/
//there are gimbal lock problem angle must be under 90
/*
* to manual change to joint angle,keep under 90 is better.
but gimbal lock problem happend alreay at IK result converted to eular angle
*/
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-89, 10, 0, 89, -10, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -40, 89, -50,89));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-89, 10, -89.9, 0, -10, 10));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -89, 40, -89, 50));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, 0, 40));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 89, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, -40, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 89, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-35, 35, -35, 35, -35, 35));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
//manual
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-91, 10, 0, 150, -10, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -40, 91, -50, 120));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-89, 10, -150, 0, -10, 10));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 40));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-91, 91, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -40, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-91, 91, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-35, 35, -35, 35, -35, 35));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
*/
}
Map<String,BoneLimit> boneLimits=new HashMap<String,BoneLimit>();
private void updateIkLabels(){
//log(""+boneNamesBox);
boneNamesBox.clear();
if(currentSelectionName!=null){
setEnableBoneRanges(true,false);//no root
for(int i=0;i<getCurrentIkData().getBones().size();i++){
boneNamesBox.addItem(getCurrentIkData().getBones().get(i));
}
boneNamesBox.setSelectedIndex(0);
}else if(selectedBone!=null){
setEnableBoneRanges(true,true);
boneNamesBox.addItem(selectedBone);
boneNamesBox.setSelectedIndex(0);
updateBoneRanges();
}else{
setEnableBoneRanges(false,false);
}
}
private void setEnableBoneRanges(boolean rotate,boolean pos){
rotationBoneRange.setEnabled(rotate);
rotationBoneYRange.setEnabled(rotate);
rotationBoneZRange.setEnabled(rotate);
positionXBoneRange.setEnabled(pos);
positionYBoneRange.setEnabled(pos);
positionZBoneRange.setEnabled(pos);
}
int ikdataIndex=1;
List<IKData> ikdatas=new ArrayList<IKData>();
private String currentSelectionName;
Mesh selectionMesh;
final Projector projector=THREE.Projector();
@Override
public void onMouseClick(ClickEvent event) {
//not work correctly on zoom
//Vector3 pos=GWTUtils.toWebGLXY(event.getX(), event.getY(), camera, screenWidth, screenHeight);
// targetPos.setX(pos.getX());
//targetPos.setY(pos.getY());
//doCDDIk();
//doPoseIkk(0);
}
private boolean isSelectedIk(){
return currentSelectionName!=null;
}
private void switchSelectionIk(String name){
currentSelectionName=name;
currentMatrixs=AnimationBonesData.cloneMatrix(ab.getBonesMatrixs());
if(currentSelectionName!=null){
List<List<NameAndVector3>> result=createBases(getCurrentIkData());
//log("switchd:"+result.size());
List<NameAndVector3> tmp=result.get(result.size()-1);
for(NameAndVector3 value:tmp){
// log(value.getName()+":"+ThreeLog.get(value.getVector3()));
}
if(nearMatrix!=null){
nearMatrix.clear();
}else{
nearMatrix=new ArrayList<List<Matrix4>>();
}
for(List<NameAndVector3> nv:result){
List<Matrix4> bm=AnimationBonesData.cloneMatrix(currentMatrixs);
applyMatrix(bm, nv);
//deb
for(String bname:getCurrentIkData().getBones()){
Matrix4 mx=bm.get(ab.getBoneIndex(bname));
//log(bname+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx)));
}
nearMatrix.add(bm);
}
}else{
// log("null selected");
}
updateIkLabels();
}
public List<List<NameAndVector3>> createBases(IKData data){
int angle=45;
if(data.getLastBoneName().equals("RightFoot") || data.getLastBoneName().equals("LeftFoot")){
//something special for foot
angle=40;
}
List<List<NameAndVector3>> all=new ArrayList();
List<List<NameAndVector3>> result=new ArrayList();
for(int i=0;i<data.getBones().size();i++){
String name=data.getBones().get(i);
List<NameAndVector3> patterns=createBases(name,angle); //90 //60 is slow
all.add(patterns);
//log(name+"-size:"+patterns.size());
}
//log(data.getLastBoneName()+"-joint-size:"+all.size());
doAdd(all,result,data.getBones(),0,null,2);
return result;
}
private void doAdd(List<List<NameAndVector3>> all,
List<List<NameAndVector3>> result, List<String> boneNames, int index,List<NameAndVector3> tmp,int depth) {
if(index>=boneNames.size() || index==depth){
result.add(tmp);
return;
}
if(index==0){
tmp=new ArrayList<NameAndVector3>();
}
for(NameAndVector3 child:all.get(index)){
//copied
List<NameAndVector3> list=new ArrayList<NameAndVector3>();
for(int i=0;i<tmp.size();i++){
list.add(tmp.get(i));
}
list.add(child);
doAdd(all,result,boneNames,index+1,list,2);
}
}
private List<NameAndVector3> createBases(String name,int step){
List<NameAndVector3> patterns=new ArrayList<NameAndVector3>();
BoneLimit limit=boneLimits.get(name);
for(int x=-180;x<=180;x+=step){
for(int y=-180;y<=180;y+=step){
for(int z=-180;z<=180;z+=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
pass=false;//same as 0
}
if(pass){
// log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}else{
}
}
}
}
if(patterns.size()==0){
patterns.add(new NameAndVector3(name,0,0,0));//empty not allowd
}
return patterns;
}
@Override
public void onMouseDown(MouseDownEvent event) {
mouseDown=true;
mouseDownX=event.getX();
mouseDownY=event.getY();
//log("mouse-click:"+event.getX()+"x"+event.getY());
JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene);
//log("intersects-length:"+intersects.length());
for(int i=0;i<intersects.length();i++){
Intersect sect=intersects.get(i);
Object3D target=sect.getObject();
if(!target.getName().isEmpty()){
if(target.getName().startsWith("ik:")){
String bname=target.getName().substring(3);
for(int j=0;j<ikdatas.size();j++){
if(ikdatas.get(j).getLastBoneName().equals(bname)){
ikdataIndex=j;
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
if(!bname.equals(currentSelectionName)){
switchSelectionIk(bname);
}
selectedBone=null;
return;//ik selected
}
}
}else{
//maybe bone or root
log(target.getName());
selectedBone=target.getName();
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
switchSelectionIk(null);
return;
}
}
}
selectedBone=null;
selectionMesh.setVisible(false);
switchSelectionIk(null);
}
private String selectedBone;
@Override
public void onMouseUp(MouseUpEvent event) {
mouseDown=false;
}
@Override
public void onMouseOut(MouseOutEvent event) {
mouseDown=false;
}
@Override
public void onMouseMove(MouseMoveEvent event) {
if(mouseDown){
if(isSelectedIk()){
double diffX=event.getX()-mouseDownX;
double diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
diffX*=0.1;
diffY*=-0.1;
getCurrentIkData().getTargetPos().incrementX(diffX);
getCurrentIkData().getTargetPos().incrementY(diffY);
if(event.isShiftKeyDown()){//slow
doPoseIkk(0,false,1,getCurrentIkData());
}else if(event.isAltKeyDown()){//rapid
doPoseIkk(0,true,1,getCurrentIkData());
}else{
doPoseIkk(0,true,5,getCurrentIkData());
}
}else if(isSelectedBone()){
if(event.isAltKeyDown()){
int diffX=event.getX()-mouseDownX;
int diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
positionXBoneRange.setValue(positionXBoneRange.getValue()+diffX);
positionYBoneRange.setValue(positionYBoneRange.getValue()-diffY);
positionToBone();
if(event.isShiftKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik);
}
}
}else{
int diffX=event.getX()-mouseDownX;
int diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
rotationBoneRange.setValue(rotationBoneRange.getValue()+diffY);
rotationBoneYRange.setValue(rotationBoneYRange.getValue()+diffX);
rotToBone();
if(event.isShiftKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik);
}
}
}
}
else{//global
int diffX=event.getX()-mouseDownX;
int diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
if(event.isShiftKeyDown()){
//do rotate Z?
}else if(event.isAltKeyDown()){//pos
positionXRange.setValue(positionXRange.getValue()+diffX);
positionYRange.setValue(positionYRange.getValue()-diffY);
}else{//rotate
rotationRange.setValue(rotationRange.getValue()+diffY);
rotationYRange.setValue(rotationYRange.getValue()+diffX);
}
}
}
}
private boolean isSelectedBone(){
return !isSelectedIk() && selectedBone!=null;
}
private IKData getCurrentIkData(){
return ikdatas.get(ikdataIndex);
}
@Override
public void onMouseWheel(MouseWheelEvent event) {
if(isSelectedIk()){
double dy=event.getDeltaY()*0.2;
getCurrentIkData().getTargetPos().incrementZ(dy);
if(event.isShiftKeyDown()){//slow
doPoseIkk(0,false,1,getCurrentIkData());
}else if(event.isAltKeyDown()){//rapid
doPoseIkk(0,true,1,getCurrentIkData());
}else{
doPoseIkk(0,true,5,getCurrentIkData());
}
}else if(isSelectedBone()){
if(event.isAltKeyDown()){
int diff=event.getDeltaY();
positionZBoneRange.setValue(positionZBoneRange.getValue()+diff);
positionToBone();
if(event.isShiftKeyDown()){
//switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik);
}
}
}else{
int diff=event.getDeltaY();
rotationBoneZRange.setValue(rotationBoneZRange.getValue()+diff);
rotToBone();
if(event.isShiftKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik);
}
}
}
}
else{
//TODO make class
long t=System.currentTimeMillis();
if(mouseLast+100>t){
tmpZoom*=2;
}else{
tmpZoom=defaultZoom;
}
//GWT.log("wheel:"+event.getDeltaY());
int tmp=cameraZ+event.getDeltaY()*tmpZoom;
tmp=Math.max(minCamera, tmp);
tmp=Math.min(4000, tmp);
cameraZ=tmp;
mouseLast=t;
}
}
private HTML5InputRange positionXRange;
private HTML5InputRange positionYRange;
private HTML5InputRange positionZRange;
//private HTML5InputRange frameRange;
private HTML5InputRange rotationRange;
private HTML5InputRange rotationYRange;
private HTML5InputRange rotationZRange;
private HTML5InputRange rotationBoneRange;
private HTML5InputRange rotationBoneYRange;
private HTML5InputRange rotationBoneZRange;
private PopupPanel bottomPanel;
private HTML5InputRange currentFrameRange;
private Label currentFrameLabel;
private HTML5InputRange positionXBoneRange;
private HTML5InputRange positionYBoneRange;
private HTML5InputRange positionZBoneRange;
@Override
public void createControl(Panel parent) {
HorizontalPanel h1=new HorizontalPanel();
rotationRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationRange));
parent.add(h1);
h1.add(rotationRange);
Button reset=new Button("Reset");
reset.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationRange.setValue(0);
}
});
h1.add(reset);
HorizontalPanel h2=new HorizontalPanel();
rotationYRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange));
parent.add(h2);
h2.add(rotationYRange);
Button reset2=new Button("Reset");
reset2.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationYRange.setValue(0);
}
});
h2.add(reset2);
HorizontalPanel h3=new HorizontalPanel();
rotationZRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange));
parent.add(h3);
h3.add(rotationZRange);
Button reset3=new Button("Reset");
reset3.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationZRange.setValue(0);
}
});
h3.add(reset3);
HorizontalPanel h4=new HorizontalPanel();
positionXRange = new HTML5InputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange,10));
parent.add(h4);
h4.add(positionXRange);
Button reset4=new Button("Reset");
reset4.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXRange.setValue(0);
}
});
h4.add(reset4);
HorizontalPanel h5=new HorizontalPanel();
positionYRange = new HTML5InputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange,10));
parent.add(h5);
h5.add(positionYRange);
Button reset5=new Button("Reset");
reset5.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYRange.setValue(0);
}
});
h5.add(reset5);
//maybe z no need,there are whell-zoom
HorizontalPanel h6=new HorizontalPanel();
positionZRange = new HTML5InputRange(-300,300,0);
//parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange,10));
//parent.add(h6);
h6.add(positionZRange);
Button reset6=new Button("Reset");
reset6.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZRange.setValue(0);
}
});
h6.add(reset6);
transparentCheck = new CheckBox();
parent.add(transparentCheck);
transparentCheck.setText("transparent");
transparentCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
transparentCheck.setValue(true);
basicMaterialCheck = new CheckBox();
parent.add(basicMaterialCheck);
basicMaterialCheck.setText("BasicMaterial");
basicMaterialCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
//dont need now
/*
HorizontalPanel frames=new HorizontalPanel();
frameRange = new HTML5InputRange(0,1,0);
parent.add(HTML5Builder.createRangeLabel("Frame:", frameRange));
//parent.add(frames);
frames.add(frameRange);
*/
/*
frameRange.addListener(new HTML5InputRangeListener() {
@Override
public void changed(int newValue) {
doPose(frameRange.getValue());
}
});
*/
HorizontalPanel boneInfo=new HorizontalPanel();
parent.add(boneInfo);
boneInfo.add(new Label("Bone"));
rotateAndPosList = new ListBox();
boneInfo.add(rotateAndPosList);
rotateAndPosList.addItem("Rotation");
rotateAndPosList.addItem("Position");
rotateAndPosList.setSelectedIndex(0);
rotateAndPosList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
switchRotateAndPosList();
}
});
boneNamesBox = new ListBox();
boneNamesBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
updateBoneRanges();
}
});
parent.add(boneNamesBox);
//positions
bonePositionsPanel = new VerticalPanel();
parent.add(bonePositionsPanel);
bonePositionsPanel.setVisible(false);
HorizontalPanel h1bpos=new HorizontalPanel();
positionXBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("X-Pos:", positionXBoneRange,10));
bonePositionsPanel.add(h1bpos);
h1bpos.add(positionXBoneRange);
Button resetB1pos=new Button("Reset");
resetB1pos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXBoneRange.setValue(0);
positionToBone();
}
});
h1bpos.add(resetB1pos);
positionXBoneRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionToBone();
}
});
HorizontalPanel h2bpos=new HorizontalPanel();
positionYBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Y-Pos:", positionYBoneRange,10));
bonePositionsPanel.add(h2bpos);
h2bpos.add(positionYBoneRange);
Button reset2bpos=new Button("Reset");
reset2bpos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYBoneRange.setValue(0);
positionToBone();
}
});
h2bpos.add(reset2bpos);
positionYBoneRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionToBone();
}
});
HorizontalPanel h3bpos=new HorizontalPanel();
positionZBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Z-Pos:", positionZBoneRange,10));
bonePositionsPanel.add(h3bpos);
h3bpos.add(positionZBoneRange);
Button reset3bpos=new Button("Reset");
reset3bpos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZBoneRange.setValue(0);
positionToBone();
}
});
h3bpos.add(reset3bpos);
positionZBoneRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionToBone();
}
});
boneRotationsPanel = new VerticalPanel();
parent.add(boneRotationsPanel);
HorizontalPanel h1b=new HorizontalPanel();
rotationBoneRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationBoneRange));
boneRotationsPanel.add(h1b);
h1b.add(rotationBoneRange);
Button resetB1=new Button("Reset");
resetB1.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneRange.setValue(0);
rotToBone();
}
});
h1b.add(resetB1);
rotationBoneRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotToBone();
}
});
HorizontalPanel h2b=new HorizontalPanel();
rotationBoneYRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationBoneYRange));
boneRotationsPanel.add(h2b);
h2b.add(rotationBoneYRange);
Button reset2b=new Button("Reset");
reset2b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneYRange.setValue(0);
rotToBone();
}
});
h2b.add(reset2b);
rotationBoneYRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotToBone();
}
});
HorizontalPanel h3b=new HorizontalPanel();
rotationBoneZRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationBoneZRange));
boneRotationsPanel.add(h3b);
h3b.add(rotationBoneZRange);
Button reset3b=new Button("Reset");
reset3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneZRange.setValue(0);
rotToBone();
}
});
h3b.add(reset3b);
rotationBoneZRange.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotToBone();
}
});
updateMaterial();
positionYRange.setValue(-140);//for test
updateIkLabels();
createBottomPanel();
showControl();
}
protected void positionToBone() {
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int index=ab.getBoneIndex(name);
if(index!=0){
//limit root only
//TODO limit by bvh channel
return;
}
Vector3 angles=GWTThreeUtils.rotationToVector3(ab.getBoneMatrix(index));
Vector3 pos=THREE.Vector3(positionXBoneRange.getValue(),
positionYBoneRange.getValue()
, positionZBoneRange.getValue()).multiplyScalar(0.1);
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
ab.setBoneMatrix(index, rotMx);
doPoseByMatrix(ab);
if( isSelectedBone()){
selectionMesh.setPosition(pos);
}
}
protected void switchRotateAndPosList() {
int index=rotateAndPosList.getSelectedIndex();
if(index==0){
bonePositionsPanel.setVisible(false);
boneRotationsPanel.setVisible(true);
}else{
bonePositionsPanel.setVisible(true);
boneRotationsPanel.setVisible(false);
}
}
private void createBottomPanel(){
bottomPanel = new PopupPanel();
bottomPanel.setVisible(true);
bottomPanel.setSize("650px", "40px");
VerticalPanel main=new VerticalPanel();
bottomPanel.add(main);
bottomPanel.show();
//upper
HorizontalPanel upperPanel=new HorizontalPanel();
upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
main.add(upperPanel);
Button snap=new Button("Add");//TODO before,after
upperPanel.add(snap);
snap.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(poseFrameDatas.size(),false);
}
});
Button replace=new Button("Replace");//TODO before,after
upperPanel.add(replace);
replace.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(currentFrameRange.getValue(),true);
}
});
Button remove=new Button("Remove");
upperPanel.add(remove);
remove.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
poseFrameDatas.remove(poseFrameDataIndex);
updatePoseIndex(poseFrameDataIndex-1);
}
});
Button export=new Button("Export");
upperPanel.add(export);
export.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doExport();
}
});
HorizontalPanel pPanel=new HorizontalPanel();
main.add(pPanel);
pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
currentFrameRange = new HTML5InputRange(0,0,0);
currentFrameRange.setWidth("420px");
pPanel.add(currentFrameRange);
currentFrameRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
updatePoseIndex(currentFrameRange.getValue());
}
});
Button prev=new Button("Prev");
pPanel.add(prev);
prev.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int value=currentFrameRange.getValue();
if(value>0){
value
currentFrameRange.setValue(value);
updatePoseIndex(value);
}
}
});
Button next=new Button("Next");
pPanel.add(next);
next.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int value=currentFrameRange.getValue();
if(value<poseFrameDatas.size()-1){
value++;
currentFrameRange.setValue(value);
updatePoseIndex(value);
}
}
});
currentFrameLabel = new Label();
pPanel.add(currentFrameLabel);
super.leftBottom(bottomPanel);
}
private void insertFrame(int index,boolean overwrite){
if(index<0){
index=0;
}
List<Matrix4> matrixs=AnimationBonesData.cloneMatrix(ab.getBonesMatrixs());
List<Vector3> targets=new ArrayList<Vector3>();
for(IKData ikdata:ikdatas){
targets.add(ikdata.getTargetPos().clone());
}
PoseFrameData ps=new PoseFrameData(matrixs, targets);
if(overwrite){
poseFrameDatas.set(index,ps);
updatePoseIndex(index);
}else{
poseFrameDatas.add(index,ps);
updatePoseIndex(poseFrameDatas.size()-1);
}
}
protected void doExport() {
BVH exportBVH=new BVH();
BVHConverter converter=new BVHConverter();
BVHNode node=converter.convertBVHNode(bones);
exportBVH.setHiearchy(node);
converter.setChannels(node,0,"XYZ"); //TODO support other order
BVHMotion motion=new BVHMotion();
motion.setFrameTime(.25);
log("frame-size:"+poseFrameDatas.size());
for(PoseFrameData pose:poseFrameDatas){
double[] values=converter.matrixsToMotion(pose.getMatrixs(),BVHConverter.ROOT_POSITION_ROTATE_ONLY,"XYZ");
motion.add(values);
}
motion.setFrames(motion.getMotions().size());
exportBVH.setMotion(motion);
//log("frames:"+exportBVH.getFrames());
BVHWriter writer=new BVHWriter();
String bvhText=writer.writeToString(exportBVH);
//log(bvhText);
exportTextChrome(bvhText,"poseeditor"+exportIndex);
exportIndex++;
}
public native final void exportTextChrome(String text,String wname)/*-{
win = $wnd.open("", wname)
win.document.body.innerText =""+text+"";
}-*/;
private int exportIndex=0;
private int poseFrameDataIndex=0;
private List<PoseFrameData> poseFrameDatas=new ArrayList<PoseFrameData>();
private void updatePoseIndex(int index){
if(index==-1){
currentFrameRange.setMax(0);
currentFrameRange.setValue(0);
currentFrameLabel.setText("");
}else{
//poseIndex=index;
currentFrameRange.setMax(poseFrameDatas.size()-1);
currentFrameRange.setValue(index);
currentFrameLabel.setText((index+1)+"/"+poseFrameDatas.size());
selectFrameData(index);
}
}
private void selectFrameData(int index) {
poseFrameDataIndex=index;
PoseFrameData ps=poseFrameDatas.get(index);
//update
for(int i=0;i<ikdatas.size();i++){
Vector3 vec=ps.getTargetPositions().get(i);
ikdatas.get(i).getTargetPos().set(vec.getX(), vec.getY(), vec.getZ());
}
currentMatrixs=AnimationBonesData.cloneMatrix(ps.getMatrixs());
ab.setBonesMatrixs(currentMatrixs);
if(isSelectedIk()){
switchSelectionIk(getCurrentIkData().getLastBoneName());
}
doPoseByMatrix(ab);
updateBoneRanges();
}
private void rotToBone(){
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int index=ab.getBoneIndex(name);
//Matrix4 mx=ab.getBoneMatrix(name);
Vector3 angles=THREE.Vector3(Math.toRadians(rotationBoneRange.getValue()),
Math.toRadians(rotationBoneYRange.getValue())
, Math.toRadians(rotationBoneZRange.getValue()));
//log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
//mx.setRotationFromEuler(angles, "XYZ");
Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneMatrix(index));
//log("pos:"+ThreeLog.get(pos));
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
//log("bone-pos:"+ThreeLog.get(bones.get(index).getPos()));
Vector3 changed=GWTThreeUtils.toDegreeAngle(rotMx);
//log("seted-angle:"+ThreeLog.get(changed));
ab.setBoneMatrix(index, rotMx);
doPoseByMatrix(ab);
}
private void updateBoneRanges(){
updateBoneRotationRanges();
updateBonePositionRanges();
}
private void updateBoneRotationRanges(){
if(boneNamesBox.getSelectedIndex()==-1){
return;
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int boneIndex=ab.getBoneIndex(name);
if(boneIndex!=0){//only root has position
rotateAndPosList.setSelectedIndex(0);
switchRotateAndPosList();
}
//Quaternion q=GWTThreeUtils.jsArrayToQuaternion(bones.get(boneIndex).getRotq());
//log("bone:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(q))));
Vector3 angles=GWTThreeUtils.toDegreeAngle(ab.getBoneMatrix(name));
log("updateBoneRotationRanges():"+ThreeLog.get(angles));
int x=(int) angles.getX();
if(x==180|| x==-180){
x=0;
}
rotationBoneRange.setValue(x);
int y=(int) angles.getY();
if(y==180|| y==-180){
y=0;
}
rotationBoneYRange.setValue(y);
int z=(int) angles.getZ();
if(z==180|| z==-180){
z=0;
}
rotationBoneZRange.setValue(z);
}
private void updateBonePositionRanges(){
if(boneNamesBox.getSelectedIndex()==-1){
return;
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
Vector3 values=GWTThreeUtils.toPositionVec(ab.getBoneMatrix(name));
values.multiplyScalar(10);
int x=(int) values.getX();
positionXBoneRange.setValue(x);
int y=(int) values.getY();
positionYBoneRange.setValue(y);
int z=(int) values.getZ();
positionZBoneRange.setValue(z);
}
private Material bodyMaterial;
protected void updateMaterial() {
Material material=null;
boolean transparent=transparentCheck.getValue();
double opacity=1;
if(transparent){
opacity=0.75;
}
if(basicMaterialCheck.getValue()){
material=THREE.MeshBasicMaterial().map(ImageUtils.loadTexture("men3smart_texture2.png")).transparent(transparent).opacity(opacity).build();
}else{
material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture2.png")).transparent(transparent).opacity(opacity).build();
}
bodyMaterial=material;
if(bodyMesh!=null){
bodyMesh.setMaterial(material);
}
}
private void loadBVH(String path){
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path));
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
String bvhText=response.getText();
parseBVH(bvhText);
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("load faild:");
}
});
} catch (RequestException e) {
log(e.getMessage());
e.printStackTrace();
}
}
private Geometry baseGeometry;
protected void parseBVH(String bvhText) {
final BVHParser parser=new BVHParser();
parser.parseAsync(bvhText, new ParserListener() {
@Override
public void onFaild(String message) {
log(message);
}
@Override
public void onSuccess(BVH bv) {
bvh=bv;
AnimationBoneConverter converter=new AnimationBoneConverter();
bones = converter.convertJsonBone(bvh);
AnimationDataConverter dataConverter=new AnimationDataConverter();
dataConverter.setSkipFirst(false);
animationData = dataConverter.convertJsonAnimation(bones,bvh);
//frameRange.setMax(animationData.getHierarchy().get(0).getKeys().length());
JSONLoader loader=THREE.JSONLoader();
loader.load("men3men.js", new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
baseGeometry=geometry;
doPose(0);
insertFrame(poseFrameDatas.size(),false);//initial pose-frame
}
});
}
});
}
public static class MatrixAndVector3{
public MatrixAndVector3(){}
private Vector3 position;
public Vector3 getPosition() {
return position;
}
public void setPosition(Vector3 position) {
this.position = position;
}
private Vector3 absolutePosition;
public Vector3 getAbsolutePosition() {
return absolutePosition;
}
public void setAbsolutePosition(Vector3 absolutePosition) {
this.absolutePosition = absolutePosition;
}
public Matrix4 getMatrix() {
return matrix;
}
public void setMatrix(Matrix4 matrix) {
this.matrix = matrix;
}
private Matrix4 matrix;
}
private List<MatrixAndVector3> boneMatrix;
/*
private Vector3 calculateBonedPos(Vector3 pos,AnimationBone bone,int animationIndex){
}
*/
public static List<MatrixAndVector3> boneToBoneMatrix(JsArray<AnimationBone> bones,AnimationData animationData,int index){
List<MatrixAndVector3> boneMatrix=new ArrayList<MatrixAndVector3>();
//analyze bone matrix
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
AnimationHierarchyItem item=animationData.getHierarchy().get(i);
AnimationKey motion=item.getKeys().get(index);
//log(bone.getName());
Matrix4 mx=THREE.Matrix4();
Vector3 motionPos=AnimationBone.jsArrayToVector3(motion.getPos());
//seems same as bone
// LogUtils.log(motionPos);
mx.setTranslation(motionPos.getX(), motionPos.getY(), motionPos.getZ());
Matrix4 mx2=THREE.Matrix4();
mx2.setRotationFromQuaternion(motion.getRot());
mx.multiplySelf(mx2);
/*
Vector3 tmpRot=THREE.Vector3();
tmpRot.setRotationFromMatrix(mx);
Vector3 tmpPos=THREE.Vector3();
tmpPos.setPositionFromMatrix(mx);
*/
//LogUtils.log(tmpPos.getX()+","+tmpPos.getY()+","+tmpPos.getZ());
//LogUtils.log(Math.toDegrees(tmpRot.))
MatrixAndVector3 mv=new MatrixAndVector3();
Vector3 bpos=AnimationBone.jsArrayToVector3(bone.getPos());
mv.setPosition(bpos);//not effected self matrix
mv.setMatrix(mx);
if(bone.getParent()!=-1){
MatrixAndVector3 parentMv=boneMatrix.get(bone.getParent());
Vector3 apos=bpos.clone();
apos.addSelf(parentMv.getAbsolutePosition());
mv.setAbsolutePosition(apos);
}else{
//root
mv.setAbsolutePosition(bpos.clone());
}
boneMatrix.add(mv);
}
return boneMatrix;
}
private List<List<Integer>> bonePath;
public static List<List<Integer>> boneToPath(JsArray<AnimationBone> bones){
List<List<Integer>> data=new ArrayList<List<Integer>>();
for(int i=0;i<bones.length();i++){
List<Integer> path=new ArrayList<Integer>();
AnimationBone bone=bones.get(i);
path.add(i);
data.add(path);
while(bone.getParent()!=-1){
//path.add(bone.getParent());
path.add(0,bone.getParent());
bone=bones.get(bone.getParent());
}
}
return data;
}
private JsArray<Vector4> bodyIndices;
private JsArray<Vector4> bodyWeight;
Mesh bodyMesh;
Object3D root;
Object3D bone3D;
private CheckBox transparentCheck;
private CheckBox basicMaterialCheck;
/**
* called after load
* @param index
*/
private void doPose(int index){
for(int i=0;i<bones.length();i++){
log(bones.get(i).getName());
}
initializeBodyMesh();
initializeAnimationData(index,false);
//stepCDDIk();
doPoseByMatrix(ab);
updateBoneRanges();
/*
* trying to fix leg problem
Vector3 rootOffset=GWTThreeUtils.jsArrayToVector3(animationData.getHierarchy().get(0).getKeys().get(index).getPos());
//initial pose is base for motions
baseGeometry=GeometryUtils.clone(bodyMesh.getGeometry());
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex vertex=baseGeometry.vertices().get(i);
vertex.getPosition().subSelf(rootOffset);
}
*/
}
AnimationBonesData ab;
List<Matrix4> baseMatrixs;
private void applyMatrix(List<Matrix4> matrix,List<NameAndVector3> samples){
for(NameAndVector3 nv:samples){
int boneIndex=ab.getBoneIndex(nv.getName());
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(ab.getBoneMatrix(boneIndex)));
Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(nv.getVector3());
newMatrix.multiply(translates,newMatrix);
//log("apply-matrix");
matrix.set(boneIndex, newMatrix);
}
}
List<List<Matrix4>> nearMatrix;
private void initializeBodyMesh(){
//initializeBodyMesh
if(bodyMesh==null){//initial
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}else{
root.remove(bodyMesh);
}
}
List<Matrix4> currentMatrixs;
private void initializeAnimationData(int index,boolean resetMatrix){
//initialize AnimationBone
if(ab==null){
baseMatrixs=AnimationBonesData.boneToMatrix(bones, animationData, index);
ab=new AnimationBonesData(bones,AnimationBonesData.cloneMatrix(baseMatrixs) );
}
//TODO make automatic
//this is find base matrix ,because sometime cdd-ik faild from some position
//nearMatrix=new ArrayList<List<Matrix4>>();
//nearMatrix.add(AnimationBonesData.cloneMatrix(baseMatrixs));
/*
* for foot
List<NameAndVector3> sample=new ArrayList<NameAndVector3>();
sample.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(90, 0, 0)), 0));
sample.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(-90, 0, 0)), 0));
List<Matrix4> bm=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm, sample);
nearMatrix.add(bm);
List<NameAndVector3> sample1=new ArrayList<NameAndVector3>();
sample1.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 0)), 0));
sample1.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 45)), 0));
List<Matrix4> bm1=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm1, sample);
//ab.setBonesMatrixs(findStartMatrix("RightFoot",getCurrentIkData().getTargetPos()));//
*/
if(currentMatrixs!=null && resetMatrix){
if(nearMatrix!=null){
//need bone limit
ab.setBonesMatrixs(AnimationBonesData.cloneMatrix(findStartMatrix(getCurrentIkData().getLastBoneName(),getCurrentIkData().getTargetPos())));
}else{
ab.setBonesMatrixs(AnimationBonesData.cloneMatrix(currentMatrixs));
}
//TODO only need
}else{
}
}
private void stepCDDIk(int perLimit,IKData ikData){
//do CDDIK
//doCDDIk();
Vector3 tmp1=null,tmp2=null;
currentIkJointIndex=0;
for(int i=0;i<ikData.getIteration();i++){
String targetBoneName=ikData.getBones().get(currentIkJointIndex);
int boneIndex=ab.getBoneIndex(targetBoneName);
Vector3 lastJointPos=ab.getPosition(ikData.getLastBoneName());
//Vector3 jointPos=ab.getParentPosition(targetName);
Vector3 jointPos=ab.getPosition(targetBoneName);
Matrix4 jointRot=ab.getBoneMatrix(targetBoneName);
Vector3 beforeAngles=GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(jointRot));
String beforeAngleValue=ThreeLog.get(beforeAngles);
Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, ikData.getTargetPos());
if(newMatrix==null){//invalid value
continue;
}
//limit per angles
Vector3 angles=GWTThreeUtils.rotationToVector3(newMatrix);
Vector3 diffAngles=GWTThreeUtils.radiantToDegree(angles).subSelf(beforeAngles);
if(Math.abs(diffAngles.getX())>perLimit){
double diff=perLimit;
if(diffAngles.getX()<0){
diff*=-1;
}
diffAngles.setX(diff);
}
if(Math.abs(diffAngles.getY())>perLimit){
double diff=perLimit;
if(diffAngles.getY()<0){
diff*=-1;
}
diffAngles.setY(diff);
}
if(Math.abs(diffAngles.getZ())>perLimit){
double diff=perLimit;
if(diffAngles.getZ()<0){
diff*=-1;
}
diffAngles.setZ(diff);
}
beforeAngles.addSelf(diffAngles);
angles=GWTThreeUtils.degreeToRagiant(beforeAngles);
//log("before:"+beforeAngleValue+" after:"+ThreeLog.get(beforeAngles));
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(newMatrix));
//limit max
BoneLimit blimit=boneLimits.get(targetBoneName);
//log(targetBoneName);
//log("before-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
if(blimit!=null){
blimit.apply(angles);
}
//invalid ignore
if("NaN".equals(""+angles.getX())){
continue;
}
if("NaN".equals(""+angles.getY())){
continue;
}
if("NaN".equals(""+angles.getZ())){
continue;
}
//log("after-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
newMatrix=GWTThreeUtils.rotationToMatrix4(angles);
newMatrix.multiply(translates,newMatrix);
ab.setBoneMatrix(boneIndex, newMatrix);
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
currentIkJointIndex++;
if(currentIkJointIndex>=ikData.getBones().size()){
currentIkJointIndex=0;
}
tmp1=lastJointPos;
tmp2=jointPos;
}
}
private void doPoseIkk(int index,boolean resetMatrix,int perLimit,IKData ikdata){
initializeBodyMesh();
initializeAnimationData(index,resetMatrix);
stepCDDIk(perLimit,ikdata);
doPoseByMatrix(ab);
updateBoneRanges();
}
private List<Matrix4> findStartMatrix(String boneName,Vector3 targetPos) {
List<Matrix4> retMatrix=nearMatrix.get(0);
ab.setBonesMatrixs(retMatrix);
Vector3 tpos=ab.getPosition(boneName);
double minlength=targetPos.clone().subSelf(tpos).length();
for(int i=1;i<nearMatrix.size();i++){
List<Matrix4> mxs=nearMatrix.get(i);
ab.setBonesMatrixs(mxs);//TODO change
Vector3 tmpPos=ab.getPosition(boneName);
double tmpLength=targetPos.clone().subSelf(tmpPos).length();
if(tmpLength<minlength){
minlength=tmpLength;
retMatrix=mxs;
}
}
for(String name:getCurrentIkData().getBones()){
Matrix4 mx=retMatrix.get(ab.getBoneIndex(name));
// log(name+":"+ThreeLog.get(GWTThreeUtils.rotationToVector3(mx)));
// log(name+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx)));
}
return retMatrix;
}
/*
private void doCDDIk(){
String targetName=getCurrentIkData().getBones().get(currentIkJointIndex);
int boneIndex=ab.getBoneIndex(targetName);
Vector3 lastJointPos=ab.getPosition("RightFoot");
Vector3 jointPos=ab.getParentPosition(targetName);
Matrix4 jointRot=ab.getBoneMatrix(targetName);
Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, getCurrentIkData().getTargetPos());
ab.setBoneMatrix(boneIndex, newMatrix);
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
currentIkJointIndex++;
if(currentIkJointIndex>=getCurrentIkData().getBones().size()){
currentIkJointIndex=0;
}
doPoseByMatrix(ab);
}
*/
CDDIK cddIk=new CDDIK();
int currentIkJointIndex=0;
//private String[] ikTestNames={"RightLeg","RightUpLeg"};
//Vector3 targetPos=THREE.Vector3(-10, -3, 0);
private ListBox boneNamesBox;
private void doPoseByMatrix(AnimationBonesData animationBonesData){
List<Matrix4> boneMatrix=animationBonesData.getBonesMatrixs();
bonePath=boneToPath(bones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
//selection
//test ikk
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<bones.length();i++){
Matrix4 mv=boneMatrix.get(i);
double bsize=.5;
if(i==0){
bsize=1;
}
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(bsize,bsize, bsize),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=THREE.Vector3();
pos.setPositionFromMatrix(boneMatrix.get(i));
Vector3 rot=GWTThreeUtils.rotationToVector3(GWTThreeUtils.jsArrayToQuaternion(bones.get(i).getRotq()));
List<Integer> path=bonePath.get(i);
String boneName=bones.get(i).getName();
//log(boneName);
mesh.setName(boneName);
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself
// log(""+path.get(j));
Matrix4 mx=boneMatrix.get(path.get(j));
matrix.multiply(matrix, mx);
}
matrix.multiplyVector3(pos);
matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)));//last one
moveMatrix.add(matrix);
if(bones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(bones.get(i).getParent());
//pos.addSelf(ppos);
//log(boneName+":"+ThreeLog.get(pos)+","+ThreeLog.get(ppos));
Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
//cylinder
/* better bone faild
Vector3 halfPos=pos.clone().subSelf(ppos).multiplyScalar(0.5).addSelf(ppos);
Mesh boneMesh=THREE.Mesh(THREE.CylinderGeometry(.1,.1,.2,6), THREE.MeshLambertMaterial().color(0xffffff).build());
boneMesh.setPosition(halfPos);
boneMesh.setName(boneName);
bone3D.add(boneMesh);
BoxData data=boxDatas.get(boneName);
if(data!=null){
boneMesh.setScale(data.getScaleX(), data.getScaleY(), data.getScaleZ());
boneMesh.getRotation().setZ(Math.toRadians(data.getRotateZ()));
}
*/
for(IKData ik:ikdatas){
if(ik.getLastBoneName().equals(boneName)){
Mesh ikMesh=targetMeshs.get(boneName);
if(ikMesh==null){//at first call this from non-ik stepped.
//log("xxx");
//initial
Vector3 ikpos=pos.clone().subSelf(ppos).multiplyScalar(2).addSelf(ppos);
//ikpos=pos.clone();
ikMesh=THREE.Mesh(THREE.CubeGeometry(1, 1, 1),THREE.MeshLambertMaterial().color(0x00ff00).build());
ikMesh.setPosition(ikpos);
ikMesh.setName("ik:"+boneName);
// log(boneName+":"+ThreeLog.get(ikpos));
//log(ThreeLog.get(pos));
ik.getTargetPos().set(ikpos.getX(), ikpos.getY(), ikpos.getZ());
targetMeshs.put(boneName, ikMesh);
}else{
ikMesh.getParent().remove(ikMesh);
}
bone3D.add(ikMesh);
ikMesh.setPosition(ik.getTargetPos());
Mesh ikline=GWTGeometryUtils.createLineMesh(pos, ik.getTargetPos(), 0xffffff);
bone3D.add(ikline);
}
}
}
mesh.setRotation(rot);
mesh.setPosition(pos);
//mesh color
if(pos.getY()<0){
mesh.getMaterial().setColor(THREE.Color(0xffee00));//over color
}else if(pos.getY()<1){
mesh.getMaterial().setColor(THREE.Color(0xff8800));//over color
}
bonePositions.add(pos);
}
//Geometry geo=GeometryUtils.clone(baseGeometry);
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex baseVertex=baseGeometry.vertices().get(i);
Vector3 vertexPosition=baseVertex.getPosition().clone();
Vertex targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
String name=animationBonesData.getBoneName(boneIndex1);
/*
*
if(name.equals("RightLeg")){//test parent base
Vector3 parentPos=animationBonesData.getBaseParentBonePosition(boneIndex1);
Matrix4 tmpMatrix=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 20)));
vertexPosition.subSelf(parentPos);
tmpMatrix.multiplyVector3(vertexPosition);
vertexPosition.addSelf(parentPos);
boneIndex2=boneIndex1; //dont work without this
}*/
Vector3 bonePos=animationBonesData.getBaseBonePosition(boneIndex1);
Vector3 relatePos=bonePos.clone();
relatePos.sub(vertexPosition,bonePos);
//double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
/*
if(name.equals("RightLeg")){
Vector3 parentPos=animationBonesData.getParentPosition(boneIndex1);
relatePos.subSelf(parentPos);
Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
tmpMatrix2.multiplyVector3(relatePos);
relatePos.addSelf(parentPos);
}*/
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
Vector3 bonePos2=animationBonesData.getBaseBonePosition(boneIndex2);
Vector3 relatePos2=bonePos2.clone();
relatePos2.sub(baseVertex.getPosition(),bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}else{
if(name.equals("RightLeg")){
// Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
// tmpMatrix2.multiplyVector3(relatePos);
}
}
targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
if(bodyMesh==null){//initial
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
WeightBuilder.autoWeight(baseGeometry, bones, 2, bodyIndices, bodyWeight);
}else{
root.remove(bodyMesh);
}
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
//selection
//selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
if(isSelectedIk()){
selectionMesh.setPosition(getCurrentIkData().getTargetPos());
}
//bone3D.add(selectionMesh);
//selectionMesh.setVisible(false);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
private Map<String,Mesh> targetMeshs=new HashMap<String,Mesh>();
private ListBox rotateAndPosList;
private VerticalPanel bonePositionsPanel;
private VerticalPanel boneRotationsPanel;
/**
* @deprecated
*/
private void doPose(List<MatrixAndVector3> boneMatrix){
bonePath=boneToPath(bones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
//test ikk
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<bones.length();i++){
MatrixAndVector3 mv=boneMatrix.get(i);
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=mv.getPosition().clone();
List<Integer> path=bonePath.get(i);
String boneName=bones.get(i).getName();
//log(boneName);
Matrix4 tmpmx=boneMatrix.get(path.get(path.size()-1)).getMatrix();
Vector3 tmpp=THREE.Vector3();
tmpp.setPositionFromMatrix(tmpmx);
//log(pos.getX()+","+pos.getY()+","+pos.getZ()+":"+tmpp.getX()+","+tmpp.getY()+","+tmpp.getZ());
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself
// log(""+path.get(j));
Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix();
matrix.multiply(matrix, mx);
}
matrix.multiplyVector3(pos);
matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one
moveMatrix.add(matrix);
if(bones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(bones.get(i).getParent());
//pos.addSelf(ppos);
Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
}else{
//root action
Matrix4 mx=boneMatrix.get(0).getMatrix();
mx.multiplyVector3(pos);
}
mesh.setPosition(pos);
bonePositions.add(pos);
}
//Geometry geo=GeometryUtils.clone(baseGeometry);
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex baseVertex=baseGeometry.vertices().get(i);
Vertex targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
Vector3 bonePos=boneMatrix.get(boneIndex1).getAbsolutePosition();
Vector3 relatePos=bonePos.clone();
relatePos.sub(baseVertex.getPosition(),bonePos);
double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
Vector3 bonePos2=boneMatrix.get(boneIndex2).getAbsolutePosition();
Vector3 relatePos2=bonePos2.clone();
relatePos2.sub(baseVertex.getPosition(),bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}
targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
@Override
public String getHtml(){
String html=super.getHtml();
html+="<br/>"+"[Howto]<br/>Select Nothing:Mouse Drag=Rotatation-XY,Mouse Wheel= Zoom, +ALT Move-XY Camera";
html+="<br/>"+"Select IK(Green Box):Mouse Drag=Move IK-XY,Mouse Wheel=Move IK-Z +Shift=smoth-change +Alt=Rapid-change";
html+="<br/>"+"Select Bone(Red Box):Mouse Drag=Rotate-XY,Mouse Wheel=Rotate-Z";
html+="<br/>"+"Select Root(Red Large Box):Mouse Drag=Rotate-XY,Mouse Wheel=Rotate-Z +Shift=Follow IK +Alt=Move Position";
html+="<br/>"+"yello box means under Y:0,orange box means near Y:0";
html+="<br/>"+"<a href='http://webgl.akjava.com'>More info at webgl.akjava.com</a>";
return html;
}
}
|
package org.intermine.webservice.server.output;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
import org.intermine.api.InterMineAPI;
import org.intermine.api.query.MainHelper;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.metadata.Model;
import org.intermine.model.testmodel.Employee;
import org.intermine.objectstore.dummy.DummyResults;
import org.intermine.objectstore.dummy.ObjectStoreDummyImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.PathQuery;
/**
* @author Alexis Kalderimis
*
*/
public class JSONRowFormatterTest extends TestCase {
/**
* @param name
*/
public JSONRowFormatterTest(String name) {
super(name);
}
private ObjectStoreDummyImpl os;
private Employee tim;
private Employee gareth;
private Employee dawn;
private Employee keith;
private Employee lee;
public static SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ");
private ExportResultsIterator iterator;
private final Model model = Model.getInstanceByName("testmodel");
private Properties testProps;
StringWriter sw;
PrintWriter pw;
private final InterMineAPI dummyAPI = new DummyAPI();
Map<String, Object> attributes;
JSONRowResultProcessor processor;
@Override
protected void setUp() throws Exception {
testProps = new Properties();
testProps.load(getClass().getResourceAsStream("JSONRowFormatterTest.properties"));
os = new ObjectStoreDummyImpl();
sw = new StringWriter();
pw = new PrintWriter(sw);
attributes = new HashMap<String, Object>();
attributes.put(JSONResultFormatter.KEY_ROOT_CLASS, "Gene");
attributes.put(JSONResultFormatter.KEY_VIEWS, Arrays.asList("foo", "bar", "baz"));
attributes.put(JSONResultFormatter.KEY_MODEL_NAME, model.getName());
attributes.put(JSONRowFormatter.KEY_TITLE, "Test Results");
attributes.put(JSONRowFormatter.KEY_EXPORT_CSV_URL, "some.csv.url");
attributes.put(JSONRowFormatter.KEY_EXPORT_TSV_URL, "some.tsv.url");
attributes.put(JSONRowFormatter.KEY_PREVIOUS_PAGE, "url.to.previous");
attributes.put(JSONRowFormatter.KEY_NEXT_PAGE, "url.to.next");
attributes.put("SOME_NULL_KEY", null);
tim = new Employee();
tim.setId(new Integer(5));
tim.setName("Tim Canterbury");
tim.setAge(30);
gareth = new Employee();
gareth.setId(new Integer(6));
gareth.setName("Gareth Keenan");
gareth.setAge(32);
dawn = new Employee();
dawn.setId(new Integer(7));
dawn.setName("Dawn Tinsley");
dawn.setAge(26);
keith = new Employee();
keith.setId(new Integer(8));
keith.setName("Keith Bishop");
keith.setAge(41);
lee = new Employee();
lee.setId(new Integer(9));
lee.setName("Lee");
lee.setAge(28);
os.setResultsSize(5);
ResultsRow row1 = new ResultsRow();
row1.add(tim);
ResultsRow row2 = new ResultsRow();
row2.add(gareth);
ResultsRow row3 = new ResultsRow();
row3.add(dawn);
ResultsRow row4 = new ResultsRow();
row4.add(keith);
ResultsRow row5 = new ResultsRow();
row5.add(lee);
os.addRow(row1);
os.addRow(row2);
os.addRow(row3);
os.addRow(row4);
os.addRow(row5);
PathQuery pq = new PathQuery(model);
pq.addViews("Employee.name", "Employee.age");
Map pathToQueryNode = new HashMap();
Query q;
q = MainHelper
.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
List resultList = os.execute(q, 0, 5, true, true, new HashMap());
Results results = new DummyResults(q, resultList);
iterator = new ExportResultsIterator(pq, results, pathToQueryNode);
processor = new JSONRowResultProcessor(dummyAPI);
}
/*
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testJSONRowFormatter() {
JSONRowFormatter fmtr = new JSONRowFormatter();
assertTrue(fmtr != null);
}
public void testFormatHeader() {
JSONRowFormatter fmtr = new JSONRowFormatter();
String expected = testProps.getProperty("result.header");
assertEquals(expected, fmtr.formatHeader(attributes));
String callback = "user_defined_callback";
expected = callback + "(" + expected;
attributes.put(JSONRowFormatter.KEY_CALLBACK, callback);
assertEquals(expected, fmtr.formatHeader(attributes));
}
public void testFormatResult() {
JSONRowFormatter fmtr = new JSONRowFormatter();
String expected = testProps.getProperty("result.body");
assertEquals(expected,
fmtr.formatResult(Arrays.asList("One", "Two", "Three")));
expected = "";
assertEquals(expected, fmtr.formatResult(new ArrayList<String>()));
}
public void testFormatFooter() {
JSONRowFormatter fmtr = new JSONRowFormatter();
Date now = Calendar.getInstance().getTime();
DateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm::ss");
String executionTime = dateFormatter.format(now);
String expected = "],\"executionTime\":\"" + executionTime
+ "\",\"wasSuccessful\":true,\"error\":null,\"statusCode\":200}";
assertEquals(expected, fmtr.formatFooter(null, 200));
expected = "],\"executionTime\":\"" + executionTime
+ "\",\"wasSuccessful\":false,\"error\":\"Not feeling like it\","
+ "\"statusCode\":400}";
assertEquals(expected, fmtr.formatFooter("Not feeling like it", 400));
expected += ");";
attributes.put(JSONRowFormatter.KEY_CALLBACK, "should_not_appear_in_footer");
fmtr.formatHeader(attributes); // needs to be called to set the callback parameter
assertEquals(expected, fmtr.formatFooter("Not feeling like it", 400));
}
public void testFormatAll() throws IOException {
JSONRowFormatter fmtr = new JSONRowFormatter();
StreamedOutput out = new StreamedOutput(pw, fmtr);
out.setHeaderAttributes(attributes);
// These are the two steps the service must perform to get good JSON.
processor.write(iterator, out);
out.flush();
Date now = Calendar.getInstance().getTime();
DateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm::ss");
String executionTime = dateFormatter.format(now);
String expected = testProps.getProperty("result.all.good").replace("{0}",
executionTime);
assertTrue(pw == out.getWriter());
assertEquals(5, out.getResultsCount());
/* For debugging, as ant can't give long enough error messages */
// FileWriter fw = new FileWriter(new File("/tmp/ant_debug.txt"));
// fw.write(expected);
// fw.write(sw.toString());
// fw.close();
assertEquals(expected, sw.toString());
}
public void testFormatAllBad() {
JSONRowFormatter fmtr = new JSONRowFormatter();
StreamedOutput out = new StreamedOutput(pw, fmtr);
out.setHeaderAttributes(attributes);
// These are the two steps the service must perform to get good JSON.
processor.write(iterator, out);
out.setError("Not feeling like it.", 500);
out.flush();
Date now = Calendar.getInstance().getTime();
DateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm::ss");
String executionTime = dateFormatter.format(now);
String expected = testProps.getProperty("result.all.bad").replace("{0}",
executionTime);
assertTrue(pw == out.getWriter());
assertEquals(5, out.getResultsCount());
assertEquals(expected, sw.toString());
}
}
|
/**
* This class represents a Forecast.io Data Point.
* It contains all the available fields in a forecast.
*
* @author David Ervideira
*/
package com.github.dvdme.ForecastIOLib;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.TimeZone;
import com.eclipsesource.json.JsonObject;
public class FIODataPoint {
HashMap<String, Object> datapoint;
String timezone;
public FIODataPoint(){
datapoint = new HashMap<String, Object>();
timezone = "GMT";
}
public FIODataPoint(JsonObject dp){
datapoint = new HashMap<String, Object>();
timezone = "GMT";
update(dp);
}
/**
* Updates the data point data
* @param dp JsonObect with the data
*/
void update(JsonObject dp){
for(int i = 0; i < dp.names().size(); i++){
datapoint.put(dp.names().get(i), dp.get(dp.names().get(i)));
}
}
/**
* Returns a String with all the Forecast.io field's available
* in this data point.
*
* @return the String with the field's names.
* @see String
*/
public String getFields(){
return datapoint.keySet().toString();
}
/**
* Returns a String array with all the Forecast.io fields available
* in this data point. It can be usefull to iterate over all
* available fields in a data point.
*
* @return the String array with the field's names.
*/
public String [] getFieldsArray(){
Object [] obj = datapoint.keySet().toArray();
String [] out = new String[obj.length];
for(int i=0; i<obj.length; i++)
out[i] = String.valueOf(obj[i]);
return out;
}
/**
* Allows to set the timezone.
* If none is set, default is GMT.
* @param tz String with the timezone such as "GMT"
*/
public void setTimezone(String tz){
this.timezone = tz;
}
/**
* Allows to get the timezone in use
* @return String with the timezone
*/
public String getTimezone(){
return this.timezone;
}
/* Gets */
/**
* Return the data point field with the corresponding key
*
* @param key name of the field in the data point
* @return the field value
*/
public String getByKey(String key){
String out = "";
if(key.equals("time"))
return time();
if(key.contains("Time")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
out = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get(key))) * 1000 );
}
else
out = String.valueOf( datapoint.get(key) );
return out;
}
public String time(){
DateFormat dfm = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
Long t = Long.parseLong( String.valueOf(this.datapoint.get("time")) );
String time = dfm.format( t * 1000 );
return time;
}
/**
* Returns the UNIX timestamp at which this data point occurs (seconds since UNIX epoch).
* e.g. 1433361600 = Wed, 03 Jun 2015 20:00:00 GMT
* @return A machine-readable UNIX timestamp as a long.
*/
public long timestamp() {
return Long.parseLong( String.valueOf(this.datapoint.get("time")) );
}
public String summary(){
if(this.datapoint.containsKey("summary"))
return asString(this.datapoint.get("summary"));
else
return "no data";
}
public String icon(){
if(this.datapoint.containsKey("icon"))
return asString(this.datapoint.get("icon"));
else
return "no data";
}
public String sunriseTime(){
if(this.datapoint.containsKey("sunriseTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("sunriseTime"))) * 1000 );
return time;
}
else
return "no data";
}
public String sunsetTime(){
if(this.datapoint.containsKey("sunsetTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("sunsetTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double precipIntensity(){
if(this.datapoint.containsKey("precipIntensity"))
return asDouble(this.datapoint.get("precipIntensity"));
else
return -1d;
}
public Double precipIntensityMax(){
if(this.datapoint.containsKey("precipIntensityMax"))
return asDouble(this.datapoint.get("precipIntensityMax"));
else
return -1d;
}
public String precipIntensityMaxTime(){
if(this.datapoint.containsKey("precipIntensityMaxTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("precipIntensityMaxTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double precipProbability(){
if(this.datapoint.containsKey("precipProbability"))
return asDouble(this.datapoint.get("precipProbability"));
else
return -1d;
}
public String precipType(){
if(this.datapoint.containsKey("precipType"))
return asString(this.datapoint.get("precipType"));
else
return "no data";
}
public Double precipAccumulation(){
if(this.datapoint.containsKey("precipAccumulation"))
return asDouble(this.datapoint.get("precipAccumulation"));
else
return -1d;
}
public Double temperature(){
if(this.datapoint.containsKey("temperature"))
return asDouble(this.datapoint.get("temperature"));
else
return null;
}
public Double temperatureError(){
if(this.datapoint.containsKey("temperatureError"))
return asDouble(this.datapoint.get("temperatureError"));
else
return null;
}
public Double temperatureMin(){
if(this.datapoint.containsKey("temperatureMin"))
return asDouble(this.datapoint.get("temperatureMin"));
else
return null;
}
public Double temperatureMinError(){
if(this.datapoint.containsKey("temperatureMinError"))
return asDouble(this.datapoint.get("temperatureMinError"));
else
return null;
}
public String temperatureMinTime(){
if(this.datapoint.containsKey("temperatureMinTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("temperatureMinTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double temperatureMax(){
if(this.datapoint.containsKey("temperatureMax"))
return asDouble(this.datapoint.get("temperatureMax"));
else
return null;
}
public Double temperatureMaxError(){
if(this.datapoint.containsKey("temperatureMaxError"))
return asDouble(this.datapoint.get("temperatureMaxError"));
else
return null;
}
public String temperatureMaxTime(){
if(this.datapoint.containsKey("temperatureMaxTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("temperatureMaxTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double apparentTemperature(){
if(this.datapoint.containsKey("apparentTemperature"))
return asDouble(this.datapoint.get("apparentTemperature"));
else
return null;
}
public Double apparentTemperatureMin(){
if(this.datapoint.containsKey("apparentTemperatureMin"))
return asDouble(this.datapoint.get("apparentTemperatureMin"));
else
return null;
}
public String apparentTemperatureMinTime(){
if(this.datapoint.containsKey("temperatureMinTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("apparentTemperatureMinTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double apparentTemperatureMax(){
if(this.datapoint.containsKey("apparentTemperatureMax"))
return asDouble(this.datapoint.get("apparentTemperatureMax"));
else
return null;
}
public String apparentTemperatureMaxTime(){
if(this.datapoint.containsKey("apparentTemperatureMaxTime")){
DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone(timezone));
String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("apparentTemperatureMaxTime"))) * 1000 );
return time;
}
else
return "no data";
}
public Double dewPoint(){
if(this.datapoint.containsKey("dewPoint"))
return asDouble(this.datapoint.get("dewPoint"));
else
return -1d;
}
public Double dewPointError(){
if(this.datapoint.containsKey("dewPointError"))
return asDouble(this.datapoint.get("dewPointError"));
else
return -1d;
}
public Double windSpeed(){
if(this.datapoint.containsKey("windSpeed"))
return asDouble(this.datapoint.get("windSpeed"));
else
return -1d;
}
public Double windSpeedError(){
if(this.datapoint.containsKey("windSpeedError"))
return asDouble(this.datapoint.get("windSpeedError"));
else
return -1d;
}
public Double windBearing(){
if(this.datapoint.containsKey("windBearing"))
return asDouble(this.datapoint.get("windBearing"));
else
return -1d;
}
public Double windBearingError(){
if(this.datapoint.containsKey("windBearingError"))
return asDouble(this.datapoint.get("windBearingError"));
else
return -1d;
}
public Double cloudCover(){
if(this.datapoint.containsKey("cloudCover"))
return asDouble(this.datapoint.get("cloudCover"));
else
return -1d;
}
public Double cloudCoverError(){
if(this.datapoint.containsKey("cloudCoverError"))
return asDouble(this.datapoint.get("cloudCoverError"));
else
return -1d;
}
public Double humidity(){
if(this.datapoint.containsKey("humidity"))
return asDouble(this.datapoint.get("humidity"));
else
return -1d;
}
public Double humidityError(){
if(this.datapoint.containsKey("humidityError"))
return asDouble(this.datapoint.get("humidityError"));
else
return -1d;
}
public Double pressure(){
if(this.datapoint.containsKey("pressure"))
return asDouble(this.datapoint.get("pressure"));
else
return -1d;
}
public Double pressureError(){
if(this.datapoint.containsKey("pressureError"))
return asDouble(this.datapoint.get("pressureError"));
else
return -1d;
}
public Double visibility(){
if(this.datapoint.containsKey("visibility"))
return asDouble(this.datapoint.get("visibility"));
else
return null;
}
public Double visibilityError(){
if(this.datapoint.containsKey("visibilityError"))
return asDouble(this.datapoint.get("visibilityError"));
else
return null;
}
public Double ozone(){
if(this.datapoint.containsKey("ozone"))
return asDouble(this.datapoint.get("ozone"));
else
return -1d;
}
public Double nearestStormBearing(){
if(this.datapoint.containsKey("nearestStormBearing"))
return asDouble(this.datapoint.get("nearestStormBearing"));
else
return -1d;
}
public Double nearestStormDistance(){
if(this.datapoint.containsKey("nearestStormDistance"))
return asDouble(this.datapoint.get("nearestStormDistance"));
else
return -1d;
}
private Double asDouble(Object obj){
return Double.parseDouble( String.valueOf(obj) );
}
private String asString(Object obj){
return String.valueOf(obj);
}
}//public class - end
|
package com.vionto.vithesaurus.tools;
import java.io.*;
/**
* Some useful tools for dealing with Strings.
*/
public class StringTools {
private static final int BUFFER_SIZE = 4096;
private StringTools() {
// static methods only, no public constructor
}
public static String slashEscape(String str) {
return str.replace("/", "___");
}
public static String slashUnescape(String str) {
return str.replace("___", "/");
}
public static String normalize(String word) {
return word.replaceAll("\\(.*?\\)", "").replaceAll("\\s+", " ").trim();
}
public static String normalizeForSort(String s) {
return normalize(s.toLowerCase().replace('ä', 'a').replace('ü', 'u').replace('ö', 'o').replace("ß", "ss"));
}
/**
* Replaces all occurrences of<br>
* <code><, >, &</code> <br>
* with <br>
* <code>&lt;, &gt;, &amp;</code><br>
*
* @param string
* The input string
* @return The modified String, with replacements.
*/
public static String replaceHtmlMarkupChars(final String string) {
return string.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
}
/**
* Write the contents if {@code file} to {@code out}.
* @param file input file
* @param out stream to be written to
* @throws IOException
*/
public static void writeToStream(final File file, final OutputStream out) throws IOException {
final FileInputStream fis = new FileInputStream(file);
try {
final BufferedInputStream bis = new BufferedInputStream(fis);
try {
final byte[] chars = new byte[BUFFER_SIZE];
int readBytes = 0;
while (readBytes >= 0) {
readBytes = bis.read(chars, 0, BUFFER_SIZE);
if (readBytes <= 0) {
break;
}
out.write(chars, 0, readBytes);
}
} finally {
bis.close();
}
} finally {
fis.close();
}
}
}
|
package com.github.pkunk.pq.ui.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ProgressBar;
public class TextProgressBar extends ProgressBar {
private String text;
private Paint textPaint;
private Rect bounds = new Rect();
public TextProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
text = "";
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setAntiAlias(true);
textPaint.setTextSize(10 * getContext().getResources().getDisplayMetrics().scaledDensity);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
// First draw the regular progress bar, then custom draw our text
super.onDraw(canvas);
textPaint.getTextBounds(text, 0, text.length(), bounds);
int x = getWidth() / 2 - bounds.centerX();
int y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}
public synchronized void setText(String text) {
this.text = text;
drawableStateChanged();
}
public void setTextColor(int color) {
textPaint.setColor(color);
drawableStateChanged();
}
}
|
package org.deeplearning4j.models.embeddings.reader.impl;
import com.google.common.collect.Lists;
import lombok.NonNull;
import org.deeplearning4j.berkeley.Counter;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.reader.ModelUtils;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.util.MathUtils;
import org.deeplearning4j.util.SetUtils;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Basic implementation for ModelUtils interface, suited for standalone use.
*
* PLEASE NOTE: This reader applies normalization to underlying lookup table.
*
* @author Adam Gibson
*/
public class BasicModelUtils<T extends SequenceElement> implements ModelUtils<T> {
protected VocabCache<T> vocabCache;
protected WeightLookupTable<T> lookupTable;
protected boolean normalized = false;
private static final Logger log = LoggerFactory.getLogger(BasicModelUtils.class);
public BasicModelUtils() {
}
@Override
public void init(@NonNull WeightLookupTable<T> lookupTable) {
this.vocabCache = lookupTable.getVocabCache();
this.lookupTable = lookupTable;
}
/**
* Returns the similarity of 2 words. Result value will be in range [-1,1], where -1.0 is exact opposite similarity, i.e. NO similarity, and 1.0 is total match of two word vectors.
* However, most of time you'll see values in range [0,1], but that's something depends of training corpus.
*
* Returns NaN if any of labels not exists in vocab, or any label is null
*
* @param label1 the first word
* @param label2 the second word
* @return a normalized similarity (cosine similarity)
*/
@Override
public double similarity( String label1, String label2) {
if (label1 == null || label2 == null) return Double.NaN;
INDArray vec1 = lookupTable.vector(label1);
INDArray vec2 = lookupTable.vector(label2);
if (vec1 == null || vec2 == null) return Double.NaN;
if (label1.equals(label2)) return 1.0;
return Transforms.cosineSim(vec1, vec2);
}
@Override
public Collection<String> wordsNearest(String label, int n) {
Collection<String> collection = wordsNearest(Arrays.asList(label),new ArrayList<String>(),n + 1);
if (collection.contains(label)) collection.remove(label);
return collection;
}
/**
* Accuracy based on questions which are a space separated list of strings
* where the first word is the query word, the next 2 words are negative,
* and the last word is the predicted word to be nearest
* @param questions the questions to ask
* @return the accuracy based on these questions
*/
@Override
public Map<String, Double> accuracy(List<String> questions) {
Map<String,Double> accuracy = new HashMap<>();
Counter<String> right = new Counter<>();
String analogyType = "";
for(String s : questions) {
if(s.startsWith(":")) {
double correct = right.getCount("correct");
double wrong = right.getCount("wrong");
if(analogyType.isEmpty()){
analogyType=s;
continue;
}
double accuracyRet = 100.0 * correct / (correct + wrong);
accuracy.put(analogyType,accuracyRet);
analogyType = s;
right.clear();
}
else {
String[] split = s.split(" ");
String word = split[0];
List<String> positive = Arrays.asList(word);
List<String> negative = Arrays.asList(split[1],split[2]);
String predicted = split[3];
String w = wordsNearest(positive,negative,1).iterator().next();
if(predicted.equals(w))
right.incrementCount("right",1.0);
else
right.incrementCount("wrong",1.0);
}
}
if(!analogyType.isEmpty()){
double correct = right.getCount("correct");
double wrong = right.getCount("wrong");
double accuracyRet = 100.0 * correct / (correct + wrong);
accuracy.put(analogyType,accuracyRet);
}
return accuracy;
}
/**
* Find all words with a similar characters
* in the vocab
* @param word the word to compare
* @param accuracy the accuracy: 0 to 1
* @return the list of words that are similar in the vocab
*/
@Override
public List<String> similarWordsInVocabTo(String word, double accuracy) {
List<String> ret = new ArrayList<>();
for(String s : vocabCache.words()) {
if(MathUtils.stringSimilarity(word, s) >= accuracy)
ret.add(s);
}
return ret;
}
public Collection<String> wordsNearest(Collection<String> positive, Collection<String> negative, int top) {
// Check every word is in the model
for (String p : SetUtils.union(new HashSet<>(positive), new HashSet<>(negative))) {
if (!vocabCache.containsWord(p)) {
return new ArrayList<>();
}
}
INDArray words = Nd4j.create(positive.size() + negative.size(), lookupTable.layerSize());
int row = 0;
//Set<String> union = SetUtils.union(new HashSet<>(positive), new HashSet<>(negative));
for (String s : positive) {
words.putRow(row++, lookupTable.vector(s));
}
for (String s : negative) {
words.putRow(row++, lookupTable.vector(s).mul(-1));
}
INDArray mean = words.isMatrix() ? words.mean(0) : words;
return wordsNearest(mean, top);
}
/**
* Get the top n words most similar to the given word
* @param word the word to compare
* @param n the n to get
* @return the top n words
*/
@Override
public Collection<String> wordsNearestSum(String word, int n) {
//INDArray vec = Transforms.unitVec(this.lookupTable.vector(word));
INDArray vec = this.lookupTable.vector(word);
return wordsNearestSum(vec, n);
}
/**
* Words nearest based on positive and negative words
* * @param top the top n words
* @return the words nearest the mean of the words
*/
@Override
public Collection<String> wordsNearest(INDArray words, int top) {
if(lookupTable instanceof InMemoryLookupTable) {
InMemoryLookupTable l = (InMemoryLookupTable) lookupTable;
INDArray syn0 = l.getSyn0();
if (!normalized) {
syn0.diviColumnVector(syn0.norm2(1));
normalized = true;
}
INDArray similarity = Transforms.unitVec(words).mmul(syn0.transpose());
// We assume that syn0 is normalized.
// Hence, the following division is not needed anymore.
// distances.diviRowVector(distances.norm2(1));
//INDArray[] sorted = Nd4j.sortWithIndices(distances,0,false);
List<Double> highToLowSimList = getTopN(similarity, top + 20);
List<String> ret = new ArrayList<>();
for (int i = 0; i < highToLowSimList.size(); i++) {
String word = vocabCache.wordAtIndex(highToLowSimList.get(i).intValue());
if (word != null && !word.equals("UNK") && !word.equals("STOP") ) {
ret.add(word);
if (ret.size() >= top) {
break;
}
}
}
return ret;
}
Counter<String> distances = new Counter<>();
for(String s : vocabCache.words()) {
INDArray otherVec = lookupTable.vector(s);
double sim = Transforms.cosineSim(words, otherVec);
distances.incrementCount(s, sim);
}
distances.keepTopNKeys(top);
return distances.keySet();
}
/**
* Get top N elements
*
* @param vec the vec to extract the top elements from
* @param N the number of elements to extract
* @return the indices and the sorted top N elements
*/
private List<Double> getTopN(INDArray vec, int N) {
ArrayComparator comparator = new ArrayComparator();
PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(),comparator);
for (int j = 0; j < vec.length(); j++) {
final Double[] pair = new Double[]{vec.getDouble(j), (double) j};
if (queue.size() < N) {
queue.add(pair);
} else {
Double[] head = queue.peek();
if (comparator.compare(pair, head) > 0) {
queue.poll();
queue.add(pair);
}
}
}
List<Double> lowToHighSimLst = new ArrayList<>();
while (!queue.isEmpty()) {
double ind = queue.poll()[1];
lowToHighSimLst.add(ind);
}
return Lists.reverse(lowToHighSimLst);
}
/**
* Words nearest based on positive and negative words
* * @param top the top n words
* @return the words nearest the mean of the words
*/
@Override
public Collection<String> wordsNearestSum(INDArray words,int top) {
if(lookupTable instanceof InMemoryLookupTable) {
InMemoryLookupTable l = (InMemoryLookupTable) lookupTable;
INDArray syn0 = l.getSyn0();
INDArray weights = syn0.norm2(0).rdivi(1).muli(words);
INDArray distances = syn0.mulRowVector(weights).sum(1);
INDArray[] sorted = Nd4j.sortWithIndices(distances,0,false);
INDArray sort = sorted[0];
List<String> ret = new ArrayList<>();
if(top > sort.length())
top = sort.length();
//there will be a redundant word
int end = top;
for(int i = 0; i < end; i++) {
String add = vocabCache.wordAtIndex(sort.getInt(i));
if(add == null || add.equals("UNK") || add.equals("STOP")) {
end++;
if(end >= sort.length())
break;
continue;
}
ret.add(vocabCache.wordAtIndex(sort.getInt(i)));
}
return ret;
}
Counter<String> distances = new Counter<>();
for(String s : vocabCache.words()) {
INDArray otherVec = lookupTable.vector(s);
double sim = Transforms.cosineSim(words, otherVec);
distances.incrementCount(s, sim);
}
distances.keepTopNKeys(top);
return distances.keySet();
}
/**
* Words nearest based on positive and negative words
* @param positive the positive words
* @param negative the negative words
* @param top the top n words
* @return the words nearest the mean of the words
*/
@Override
public Collection<String> wordsNearestSum(Collection<String> positive, Collection<String> negative, int top) {
INDArray words = Nd4j.create(lookupTable.layerSize());
// Set<String> union = SetUtils.union(new HashSet<>(positive), new HashSet<>(negative));
for(String s : positive)
words.addi(lookupTable.vector(s));
for(String s : negative)
words.addi(lookupTable.vector(s).mul(-1));
return wordsNearestSum(words,top);
}
private static class ArrayComparator implements Comparator<Double[]> {
@Override
public int compare(Double[] o1, Double[] o2) {
return Double.compare(o1[0], o2[0]);
}
}
}
|
package io.compgen.ngsutils.cli.bam;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMProgramRecord;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractCommand;
import io.compgen.common.progress.FileChannelStats;
import io.compgen.common.progress.ProgressMessage;
import io.compgen.common.progress.ProgressUtils;
import io.compgen.ngsutils.NGSUtils;
import io.compgen.ngsutils.bam.Orientation;
import io.compgen.ngsutils.bam.filter.BamFilter;
import io.compgen.ngsutils.bam.filter.BedExclude;
import io.compgen.ngsutils.bam.filter.BedInclude;
import io.compgen.ngsutils.bam.filter.FilterFlags;
import io.compgen.ngsutils.bam.filter.JunctionWhitelist;
import io.compgen.ngsutils.bam.filter.NullFilter;
import io.compgen.ngsutils.bam.filter.PairedFilter;
import io.compgen.ngsutils.bam.filter.RefExclude;
import io.compgen.ngsutils.bam.filter.RefInclude;
import io.compgen.ngsutils.bam.filter.RequiredFlags;
import io.compgen.ngsutils.bam.filter.TagEq;
import io.compgen.ngsutils.bam.filter.TagEqStr;
import io.compgen.ngsutils.bam.filter.TagMax;
import io.compgen.ngsutils.bam.filter.TagMin;
import io.compgen.ngsutils.bam.filter.UniqueMapping;
import io.compgen.ngsutils.bam.filter.UniqueStart;
import io.compgen.ngsutils.bam.filter.Whitelist;
import io.compgen.ngsutils.bam.support.ReadUtils;
import io.compgen.ngsutils.support.CloseableFinalizer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Command(name="bam-filter", desc="Filters out reads based upon various criteria", category="bam")
public class BamFilterCli extends AbstractCommand {
private List<String> filenames=null;
private String tmpDir = null;
private String bedExclude = null;
private boolean bedExcludeRequireOne = false;
private boolean bedExcludeRequireBoth = false;
private boolean bedExcludeOnlyWithin = false;
private boolean bedExcludeReadStartPos = false;
private String bedIncludeFile = null;
private boolean bedIncludeRequireOne = false;
private boolean bedIncludeRequireBoth = false;
private boolean bedIncludeOnlyWithin = false;
private boolean bedIncludeReadStartPos = false;
private String junctionWhitelist = null;
private String whitelist = null;
private String failedFilename = null;
private String excludeRefs = null;
private String includeRefs = null;
private Map<String, Integer> minTagValues = null;
private Map<String, Integer> maxTagValues = null;
private Map<String, Integer> eqTagValues = null;
private Map<String, String> eqStrTagValues = null;
private boolean paired = false;
private boolean unique = false;
private boolean uniqueStart = false;
private boolean lenient = false;
private boolean silent = false;
private int filterFlags = 0;
private int requiredFlags = 0;
private Orientation orient = Orientation.UNSTRANDED;
@UnnamedArg(name = "INFILE OUTFILE")
public void setFilename(List<String> filenames) throws CommandArgumentException {
if (filenames.size() != 2) {
throw new CommandArgumentException("You must specify both an input and an output file.");
}
this.filenames = filenames;
}
@Option(desc="Write temporary files here", name="tmpdir", helpValue="dir")
public void setTmpDir(String tmpDir) {
this.tmpDir = tmpDir;
}
@Option(desc="Force sanity checking of read pairing (simple - same chromosome, reversed orientation)", name="paired")
public void setPaired(boolean val) {
this.paired = val;
}
@Option(desc="Require junction-spanning reads to span one of these junctions", name="junction-whitelist", helpValue="fname")
public void setJunctionWhitelist(String junctionWhitelist) {
this.junctionWhitelist = junctionWhitelist;
}
@Option(desc="Remove reads mapping to these references (comma-delimited)", name="ref-exclude", helpValue="ref")
public void excludeRefs(String excludeRefs) {
this.excludeRefs = excludeRefs;
}
@Option(desc="Keep only reads mapping to these references (comma-delimited)", name="ref-include", helpValue="ref")
public void includeRefs(String includeRefs) {
this.includeRefs = includeRefs;
}
@Option(desc="Keep only read names from this whitelist", name="whitelist", helpValue="fname")
public void setWhitelist(String whitelist) {
this.whitelist = whitelist;
}
@Option(desc="Write failed reads to this file (BAM)", name="failed", helpValue="fname")
public void setFailedFilename(String failedFilename) {
this.failedFilename = failedFilename;
}
@Option(desc="Exclude reads within BED regions", name="bed-exclude", helpValue="fname")
public void setBedExcludeFile(String bedExclude) {
this.bedExclude = bedExclude;
}
@Option(desc="BED Exclude option: only-within", name="bed-excl-only-within")
public void setBEDExcludeWithin(boolean val) {
this.bedExcludeOnlyWithin = val;
}
@Option(desc="BED Exclude option: require-one", name="bed-excl-require-one")
public void setBEDExcludeRequireOne(boolean val) {
this.bedExcludeRequireOne = val;
}
@Option(desc="BED Exclude option: start-pos", name="bed-excl-start-pos")
public void setBEDExcludeReadStartPos(boolean val) {
this.bedExcludeReadStartPos = val;
}
@Option(desc="BED Exclude option: require-both", name="bed-excl-require-both")
public void setBEDExcludeRequireBoth(boolean val) {
this.bedExcludeRequireBoth = val;
}
@Option(desc="Include reads within BED regions", name="bed-include", helpValue="fname")
public void setBedIncludeFile(String bedIncludeFile) {
this.bedIncludeFile = bedIncludeFile;
}
@Option(desc="BED Include option: only-within", name="bed-incl-only-within")
public void setBEDIncludeWithin(boolean val) {
this.bedIncludeOnlyWithin = val;
}
@Option(desc="BED Include option: require-one", name="bed-incl-require-one")
public void setBEDIncludeKeep(boolean val) {
this.bedIncludeRequireOne = val;
}
@Option(desc="BED Include option: require-both", name="bed-incl-require-both")
public void setBEDIncludeRemove(boolean val) {
this.bedIncludeRequireBoth = val;
}
@Option(desc="BED Include option: start-pos", name="bed-incl-start-pos")
public void setBEDIncludeReadStartPos(boolean val) {
this.bedIncludeReadStartPos = val;
}
@Option(desc="Use lenient validation strategy", name="lenient")
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
@Option(desc="Library is in FR orientation (only used for BED filters)", name="library-fr")
public void setLibraryFR(boolean val) {
if (val) {
orient = Orientation.FR;
}
}
@Option(desc="Library is in RF orientation (only used for BED filters)", name="library-rf")
public void setLibraryRF(boolean val) {
if (val) {
orient = Orientation.RF;
}
}
@Option(desc="Library is in unstranded orientation (only used for BED filters, default)", name="library-unstranded")
public void setLibraryUnstranded(boolean val) {
if (val) {
orient = Orientation.UNSTRANDED;
}
}
@Option(desc="Only keep properly paired reads", name="proper-pairs")
public void setProperPairs(boolean val) {
if (val) {
requiredFlags |= ReadUtils.PROPER_PAIR_FLAG;
}
}
@Option(desc="Only keep reads that have one unique mapping (NH==1|IH==1|MAPQ>0)", name="unique-mapping")
public void setUniqueMapping(boolean val) {
unique=val;
setMapped(true);
}
@Option(desc="Keep at most one read per position (strand-specific, only for single-read fragments)", name="unique-start")
public void setUniqueStart(boolean val) {
uniqueStart=val;
setMapped(true);
}
@Option(desc="Only keep mapped reads (both reads if paired)", name="mapped")
public void setMapped(boolean val) {
if (val) {
filterFlags |= ReadUtils.READ_UNMAPPED_FLAG | ReadUtils.MATE_UNMAPPED_FLAG;
}
}
@Option(desc="Only keep unmapped reads", name="unmapped")
public void setUnmapped(boolean val) {
if (val) {
requiredFlags |= ReadUtils.READ_UNMAPPED_FLAG;
}
}
@Option(desc="No secondary mappings", name="nosecondary")
public void setNoSecondary(boolean val) {
if (val) {
filterFlags |= ReadUtils.SUPPLEMENTARY_ALIGNMENT_FLAG;
}
}
@Option(desc="No PCR duplicates", name="nopcrdup")
public void setNoPCRDuplicates(boolean val) {
if (val) {
filterFlags |= ReadUtils.DUPLICATE_READ_FLAG;
}
}
@Option(desc="No QC failures", name="noqcfail")
public void setNoQCFail(boolean val) {
if (val) {
filterFlags |= ReadUtils.READ_FAILS_VENDOR_QUALITY_CHECK_FLAG;
}
}
@Option(desc="Filtering flags", name="filter-flags", defaultValue="0")
public void setFilterFlags(int flag) {
filterFlags |= flag;
}
@Option(desc="Required flags", name="required-flags", defaultValue="0")
public void setRequiredFlags(int flag) {
requiredFlags |= flag;
}
@Option(desc="Minimum tag value (tag:val, ex: AS:100,MAPQ:1)", name="tag-min")
public void setMinTagValue(String vals) {
if (minTagValues == null) {
minTagValues = new HashMap<String, Integer>();
}
for (String val:vals.split(",")) {
String key = val.split(":")[0];
Integer value = Integer.parseInt(val.split(":")[1]);
minTagValues.put(key, value);
}
}
@Option(desc="Maximum tag value (tag:val, ex: NH:0)", name="tag-max")
public void setMaxTagValue(String vals) {
if (maxTagValues == null) {
maxTagValues = new HashMap<String, Integer>();
}
for (String val:vals.split(",")) {
String key = val.split(":")[0];
Integer value = Integer.parseInt(val.split(":")[1]);
maxTagValues.put(key, value);
}
}
@Option(desc="Tag value equals (tag:val, ex: NH:0, int)", name="tag-eq")
public void setEqTagValue(String vals) {
if (eqTagValues == null) {
eqTagValues = new HashMap<String, Integer>();
}
for (String val:vals.split(",")) {
String key = val.split(":")[0];
Integer value = Integer.parseInt(val.split(":")[1]);
eqTagValues.put(key, value);
}
}
@Option(desc="Tag value equals (tag:val, ex: NH:0, string)", name="tag-eqstr")
public void setEqStringTagValue(String vals) {
if (eqStrTagValues == null) {
eqStrTagValues = new HashMap<String, String>();
}
for (String val:vals.split(",")) {
String[] kv = val.split(":");
eqStrTagValues.put(kv[0], kv[1]);
}
}
@Exec
public void exec() throws CommandArgumentException, IOException {
if (filenames == null || filenames.size()!=2) {
throw new CommandArgumentException("You must specify an input BAM filename and an output BAM filename!");
}
SamReaderFactory readerFactory = SamReaderFactory.makeDefault();
if (lenient) {
readerFactory.validationStringency(ValidationStringency.LENIENT);
} else if (silent) {
readerFactory.validationStringency(ValidationStringency.SILENT);
}
SamReader reader = null;
String name;
FileChannel channel = null;
if (filenames.get(0).equals("-")) {
reader = readerFactory.open(SamInputResource.of(System.in));
name = "<stdin>";
} else {
File f = new File(filenames.get(0));
FileInputStream fis = new FileInputStream(f);
channel = fis.getChannel();
reader = readerFactory.open(SamInputResource.of(fis));
name = f.getName();
}
SAMFileWriterFactory factory = new SAMFileWriterFactory();
String outFilename = filenames.get(1);
File outfile = null;
OutputStream outStream = null;
if (outFilename.equals("-")) {
outStream = new BufferedOutputStream(System.out);
} else {
outfile = new File(outFilename);
}
if (tmpDir != null) {
factory.setTempDirectory(new File(tmpDir));
} else if (outfile == null || outfile.getParent() == null) {
factory.setTempDirectory(new File(".").getCanonicalFile());
} else if (outfile!=null) {
factory.setTempDirectory(outfile.getParentFile());
}
SAMFileHeader header = reader.getFileHeader().clone();
SAMProgramRecord pg = NGSUtils.buildSAMProgramRecord("bam-filter", header);
List<SAMProgramRecord> pgRecords = new ArrayList<SAMProgramRecord>(header.getProgramRecords());
pgRecords.add(0, pg);
header.setProgramRecords(pgRecords);
SAMFileWriter out;
if (outfile != null) {
out = factory.makeBAMWriter(header, true, outfile);
} else {
out = factory.makeSAMWriter(header, true, outStream);
}
SAMFileWriter failedWriter = null;
if (failedFilename != null) {
failedWriter = factory.makeBAMWriter(header, true, new File(failedFilename));
}
BamFilter parent;
if (channel == null) {
parent = new NullFilter(reader.iterator(), failedWriter);
} else {
parent = new NullFilter(ProgressUtils.getIterator(name, reader.iterator(), new FileChannelStats(channel), new ProgressMessage<SAMRecord>(){
@Override
public String msg(SAMRecord current) {
if (current != null) {
return current.getReadName();
}
return null;
}}, new CloseableFinalizer<SAMRecord>()), failedWriter);
}
if (filterFlags > 0) {
parent = new FilterFlags(parent, false, filterFlags);
if (verbose) {
System.err.println("FilterFlags: "+filterFlags);
}
}
if (requiredFlags > 0) {
parent = new RequiredFlags(parent, false, requiredFlags);
if (verbose) {
System.err.println("RequiredFlags: "+requiredFlags);
}
}
if (unique) {
parent = new UniqueMapping(parent, false);
if (verbose) {
System.err.println("Unique-mapping");
}
}
if (uniqueStart) {
parent = new UniqueStart(parent, false);
if (verbose) {
System.err.println("Unique-start");
}
}
if (paired) {
parent = new PairedFilter(parent, false);
if (verbose) {
System.err.println("Paired");
}
}
if (bedIncludeFile!=null) {
parent = new BedInclude(parent, false, bedIncludeFile, orient);
((BedInclude)parent).setOnlyWithin(bedIncludeOnlyWithin);
((BedInclude)parent).setRequireOnePair(bedIncludeRequireOne);
((BedInclude)parent).setRequireBothPairs(bedIncludeRequireBoth);
((BedInclude)parent).setReadStartPos(bedIncludeReadStartPos);
if (verbose) {
System.err.println("BEDInclude: "+bedIncludeFile);
}
}
if (bedExclude!=null) {
parent = new BedExclude(parent, false, bedExclude, orient);
((BedExclude)parent).setOnlyWithin(bedExcludeOnlyWithin);
((BedExclude)parent).setRequireOnePair(bedExcludeRequireOne);
((BedExclude)parent).setRequireBothPairs(bedExcludeRequireBoth);
((BedExclude)parent).setReadStartPos(bedExcludeReadStartPos);
if (verbose) {
System.err.println("BEDExclude: "+bedExclude);
}
}
if (includeRefs!=null) {
parent = new RefInclude(parent, false, includeRefs);
if (verbose) {
System.err.println("RefInclude: "+includeRefs);
}
}
if (excludeRefs!=null) {
parent = new RefExclude(parent, false, excludeRefs);
if (verbose) {
System.err.println("RefExclude: "+excludeRefs);
}
}
if (junctionWhitelist != null) {
parent = new JunctionWhitelist(parent, false, junctionWhitelist);
if (verbose) {
System.err.println("JuntionWhitelist: "+junctionWhitelist);
}
}
if (whitelist != null) {
parent = new Whitelist(parent, false, whitelist);
if (verbose) {
System.err.println("Whitelist: "+whitelist);
}
}
if (minTagValues != null) {
parent = new TagMin(parent, false, minTagValues);
if (verbose) {
String outval = "";
for (String k:minTagValues.keySet()) {
if (!outval.equals("")) {
outval+=",";
}
outval += k+":"+minTagValues.get(k);
}
System.err.println("Tag min: "+outval);
}
}
if (maxTagValues != null) {
parent = new TagMax(parent, false, maxTagValues);
if (verbose) {
String outval = "";
for (String k:maxTagValues.keySet()) {
if (!outval.equals("")) {
outval+=",";
}
outval += k+":"+maxTagValues.get(k);
}
System.err.println("Tag max: "+outval);
}
}
if (eqTagValues != null) {
parent = new TagEq(parent, false, eqTagValues);
if (verbose) {
String outval = "";
for (String k:eqTagValues.keySet()) {
if (!outval.equals("")) {
outval+=",";
}
outval += k+":"+eqTagValues.get(k);
}
System.err.println("Tag eq (int): "+outval);
}
}
if (eqStrTagValues != null) {
parent = new TagEqStr(parent, false, eqStrTagValues);
if (verbose) {
String outval = "";
for (String k:eqStrTagValues.keySet()) {
if (!outval.equals("")) {
outval+=",";
}
outval += k+":"+eqStrTagValues.get(k);
}
System.err.println("Tag eq (string): "+outval);
}
}
for (SAMRecord read: parent) {
if (read != null) {
out.addAlignment(read);
}
}
if (verbose) {
dumpStats(parent);
}
reader.close();
out.close();
if (failedWriter != null) {
failedWriter.close();
}
}
private void dumpStats(BamFilter filter) {
if (filter.getParent()!=null) {
dumpStats(filter.getParent());
}
System.err.println(filter.getClass().getSimpleName());
System.err.println(" total: "+filter.getTotal());
System.err.println(" removed: "+filter.getRemoved());
}
}
|
package nl.b3p.viewer.stripes;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.NoResultException;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.After;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.app.ConfiguredAttribute;
import nl.b3p.viewer.config.services.AttributeDescriptor;
import nl.b3p.viewer.config.services.Layer;
import nl.b3p.viewer.config.services.SimpleFeatureType;
import nl.b3p.viewer.config.services.WFSFeatureSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/appLayer")
@StrictBinding
public class AppLayerActionBean implements ActionBean {
private static final Log log = LogFactory.getLog(AppLayerActionBean.class);
private static final int MAX_FEATURES = 50;
private ActionBeanContext context;
@Validate
private ApplicationLayer appLayer;
private Layer layer = null;
@Validate
private int limit;
@Validate
private int page;
@Validate
private int start;
@Validate
private String dir;
@Validate
private String sort;
@Validate
private boolean arrays;
@Validate
private boolean debug;
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ApplicationLayer getAppLayer() {
return appLayer;
}
public void setAppLayer(ApplicationLayer appLayer) {
this.appLayer = appLayer;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public boolean isArrays() {
return arrays;
}
public void setArrays(boolean arrays) {
this.arrays = arrays;
}
//</editor-fold>
@After(stages=LifecycleStage.BindingAndValidation)
public void loadLayer() {
// TODO check if user has rights to appLayer
try {
layer = (Layer)Stripersist.getEntityManager().createQuery("from Layer where service = :service and name = :n order by virtual desc")
.setParameter("service", appLayer.getService())
.setParameter("n", appLayer.getLayerName())
.setMaxResults(1)
.getSingleResult();
} catch(NoResultException nre) {
}
}
public Resolution attributes() throws JSONException {
JSONObject json = new JSONObject();
json.put("success", Boolean.FALSE);
String error = null;
if(appLayer == null) {
error = "Invalid parameters";
} else {
Map<String,AttributeDescriptor> featureTypeAttributes = new HashMap<String,AttributeDescriptor>();
if(layer != null) {
SimpleFeatureType ft = layer.getFeatureType();
if(ft != null) {
for(AttributeDescriptor ad: ft.getAttributes()) {
featureTypeAttributes.put(ad.getName(), ad);
}
}
}
JSONArray attributes = new JSONArray();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
JSONObject j = ca.toJSONObject();
AttributeDescriptor ad = featureTypeAttributes.get(ca.getAttributeName());
if(ad != null) {
j.put("alias", ad.getAlias());
j.put("type", ad.getType());
}
attributes.put(j);
}
json.put("attributes", attributes);
json.put("success", Boolean.TRUE);
}
if(error != null) {
json.put("error", error);
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
public Resolution store() throws JSONException, Exception {
JSONObject json = new JSONObject();
JSONArray features = new JSONArray();
json.put("features", features);
try {
int total = 0;
if(layer != null && layer.getFeatureType() != null) {
FeatureSource fs;
if(isDebug() && layer.getFeatureType().getFeatureSource() instanceof WFSFeatureSource) {
Map extraDataStoreParams = new HashMap();
extraDataStoreParams.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.FALSE);
fs = ((WFSFeatureSource)layer.getFeatureType().getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams);
} else {
fs = layer.getFeatureType().openGeoToolsFeatureSource();
}
boolean startIndexSupported = fs.getQueryCapabilities().isOffsetSupported();
Query q = new Query(fs.getName().toString());
FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
if(sort != null) {
String sortAttribute = sort;
if(arrays) {
int i = Integer.parseInt(sort.substring(1));
int j = 0;
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
if(j == i) {
sortAttribute = ca.getAttributeName();
}
j++;
}
}
}
q.setSortBy(new SortBy[] {
ff2.sort(sortAttribute, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING)
});
}
total = fs.getCount(q);
if(total == -1) {
total = MAX_FEATURES;
}
q.setStartIndex(start);
q.setMaxFeatures(Math.min(limit + (startIndexSupported ? 0 : start),MAX_FEATURES));
FeatureCollection fc = fs.getFeatures(q);
FeatureIterator<SimpleFeature> it = fc.features();
try {
while(it.hasNext()) {
SimpleFeature f = it.next();
if(!startIndexSupported && start > 0) {
start
continue;
}
if(arrays) {
JSONObject j = new JSONObject();
int idx = 0;
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
Object value = f.getAttribute(ca.getAttributeName());
j.put("c" + idx++, formatValue(value));
}
}
features.put(j);
} else {
JSONObject j = new JSONObject();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
String name = ca.getAttributeName();
j.put(name, f.getAttribute(name));
}
}
features.put(j);
}
}
} finally {
it.close();
fs.getDataStore().dispose();
}
}
json.put("total", total);
} catch(Exception e) {
log.error("Error loading features", e);
json.put("success", false);
String message = "Fout bij ophalen features: " + e.toString();
Throwable cause = e.getCause();
while(cause != null) {
message += "; " + cause.toString();
cause = cause.getCause();
}
json.put("message", message);
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private Object formatValue(Object value) {
if(value instanceof Date) {
// JSON has no date type so format the date as it is used for
// display, not calculation
return dateFormat.format((Date)value);
} else {
return value;
}
}
}
|
package io.quarkus.reactive.datasource.runtime;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.enterprise.inject.spi.Bean;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
import org.jboss.logging.Logger;
import io.quarkus.datasource.common.runtime.DataSourceUtil;
import io.quarkus.reactive.datasource.ReactiveDataSource;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
public abstract class ReactiveDatasourceHealthCheck implements HealthCheck {
private static final Logger log = Logger.getLogger(ReactiveDatasourceHealthCheck.class);
private final Map<String, Pool> pools = new ConcurrentHashMap<>();
private final String healthCheckResponseName;
private final String healthCheckSQL;
protected ReactiveDatasourceHealthCheck(String healthCheckResponseName, String healthCheckSQL) {
this.healthCheckResponseName = healthCheckResponseName;
this.healthCheckSQL = healthCheckSQL;
}
protected void addPool(String name, Pool p) {
final Pool previous = pools.put(name, p);
if (previous != null) {
throw new IllegalStateException("Duplicate pool name: " + name);
}
}
@Override
public HealthCheckResponse call() {
HealthCheckResponseBuilder builder = HealthCheckResponse.named(healthCheckResponseName);
builder.up();
for (Map.Entry<String, Pool> pgPoolEntry : pools.entrySet()) {
final String dataSourceName = pgPoolEntry.getKey();
final Pool pgPool = pgPoolEntry.getValue();
try {
CompletableFuture<Void> databaseConnectionAttempt = new CompletableFuture<>();
Context context = Vertx.currentContext();
if (context != null) {
log.debug("Run health check on the current Vert.x context");
context.runOnContext(v -> {
pgPool.query(healthCheckSQL)
.execute(ar -> {
checkFailure(ar, builder, dataSourceName);
databaseConnectionAttempt.complete(null);
});
});
} else {
log.warn("Vert.x context unavailable to perform healthcheck of reactive datasource `" + dataSourceName
+ "`. This is unlikely to work correctly.");
pgPool.query(healthCheckSQL)
.execute(ar -> {
checkFailure(ar, builder, dataSourceName);
databaseConnectionAttempt.complete(null);
});
}
//20 seconds is rather high, but using just 10 is often not enough on slow CI
//systems, especially if the connections have to be established for the first time.
databaseConnectionAttempt.get(20, TimeUnit.SECONDS);
builder.withData(dataSourceName, "UP");
} catch (RuntimeException | ExecutionException exception) {
operationsError(dataSourceName, exception);
builder.down();
builder.withData(dataSourceName, "down - connection failed: " + exception.getMessage());
} catch (InterruptedException e) {
log.warn("Interrupted while obtaining database connection for healthcheck of datasource " + dataSourceName);
Thread.currentThread().interrupt();
return builder.build();
} catch (TimeoutException e) {
log.warn("Timed out while waiting for an available connection to perform healthcheck of datasource "
+ dataSourceName);
builder.down();
builder.withData(dataSourceName, "timed out, unable to obtain connection to perform healthcheck of datasource");
}
}
return builder.build();
}
private void operationsError(final String datasourceName, final Throwable cause) {
log.warn("Error obtaining database connection for healthcheck of datasource '" + datasourceName + '\'', cause);
}
private void checkFailure(AsyncResult<RowSet<Row>> ar, HealthCheckResponseBuilder builder, String dataSourceName) {
if (ar.failed()) {
operationsError(dataSourceName, ar.cause());
builder.down();
builder.withData(dataSourceName, "down - connection failed: " + ar.cause().getMessage());
}
}
protected String getPoolName(Bean<?> bean) {
for (Object qualifier : bean.getQualifiers()) {
if (qualifier instanceof ReactiveDataSource) {
return ((ReactiveDataSource) qualifier).value();
}
}
return DataSourceUtil.DEFAULT_DATASOURCE_NAME;
}
}
|
package com.intellij.refactoring.extractMethod.preview;
import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffManager;
import com.intellij.diff.DiffRequestPanel;
import com.intellij.diff.comparison.ComparisonManagerImpl;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.fragments.LineFragment;
import com.intellij.diff.tools.fragmented.UnifiedDiffTool;
import com.intellij.diff.tools.util.text.LineOffsets;
import com.intellij.diff.tools.util.text.LineOffsetsUtil;
import com.intellij.diff.util.DiffUserDataKeys;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.diff.util.DiffUtil;
import com.intellij.diff.util.Range;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethod.ExtractMethodHandler;
import com.intellij.refactoring.extractMethod.ExtractMethodProcessor;
import com.intellij.refactoring.extractMethod.ExtractMethodSnapshot;
import com.intellij.refactoring.extractMethod.JavaDuplicatesExtractMethodProcessor;
import com.intellij.refactoring.introduceParameter.IntroduceParameterHandler;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.duplicates.Match;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.components.BorderLayoutPanel;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.refactoring.extractMethod.ExtractMethodHandler.REFACTORING_NAME;
/**
* @author Pavel.Dolgov
*/
class PreviewDiffPanel extends BorderLayoutPanel implements Disposable, PreviewTreeListener {
private final Project myProject;
private final PreviewTree myTree;
private final List<SmartPsiElementPointer<PsiElement>> myPattern;
private final ExtractMethodSnapshot mySnapshot;
private final SmartPsiElementPointer<PsiElement> myAnchor;
private final DiffRequestPanel myDiffPanel;
private PreviewDiffRequest myDiffRequest; // accessed in EDT
private Document myPatternDocument; // accessed in EDT
private long myInitialDocumentStamp; // accessed in EDT
public PreviewDiffPanel(@NotNull ExtractMethodProcessor processor, PreviewTree tree) {
myProject = processor.getProject();
myTree = tree;
SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject);
myPattern = ContainerUtil.map2List(processor.getElements(), smartPointerManager::createSmartPsiElementPointer);
mySnapshot = new ExtractMethodSnapshot(processor);
myAnchor = smartPointerManager.createSmartPsiElementPointer(processor.getAnchor());
myDiffPanel = DiffManager.getInstance().createRequestPanel(myProject, this, null);
myDiffPanel.putContextHints(DiffUserDataKeys.PLACE, "ExtractMethod");
myDiffPanel.putContextHints(DiffUserDataKeys.FORCE_READ_ONLY, true);
myDiffPanel.putContextHints(DiffUserDataKeysEx.FORCE_DIFF_TOOL, UnifiedDiffTool.INSTANCE);
addToCenter(myDiffPanel.getComponent());
Disposer.register(this, myDiffPanel);
}
@Override
public void dispose() {
}
public void doExtract() {
List<DuplicateNode> enabledNodes = myTree.getModel().getEnabledDuplicates();
PsiElement[] pattern = getPatternElements();
if (pattern.length == 0) {
// todo suggest re-running the refactoring
CommonRefactoringUtil.showErrorHint(myProject, null, RefactoringBundle.message("refactoring.extract.method.preview.failed"),
REFACTORING_NAME, HelpID.EXTRACT_METHOD);
return;
}
JavaDuplicatesExtractMethodProcessor processor = new JavaDuplicatesExtractMethodProcessor(pattern, REFACTORING_NAME);
if (!processor.prepareFromSnapshot(mySnapshot, true)) {
return;
}
WriteCommandAction.runWriteCommandAction(myProject, REFACTORING_NAME, null,
() -> doExtractImpl(processor, enabledNodes), pattern[0].getContainingFile());
}
public void initLater() {
ProgressManager.getInstance().run(new Task.Backgroundable(myProject,
RefactoringBundle.message("refactoring.extract.method.preview.preparing")) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
updateLaterImpl(indicator, false);
}
});
}
public void updateLater() {
ProgressManager.getInstance().run(new Task.Backgroundable(myProject,
RefactoringBundle.message("refactoring.extract.method.preview.updating")) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
updateLaterImpl(indicator, true);
}
});
}
private void updateLaterImpl(@NotNull ProgressIndicator indicator, boolean onlyEnabled) {
List<DuplicateNode> allNodes = myTree.getModel().getAllDuplicates();
List<? extends DuplicateNode> selectedNodes = onlyEnabled ? myTree.getModel().getEnabledDuplicates() : allNodes;
IncrementalProgress progress = new IncrementalProgress(indicator, selectedNodes.size() + 4);
PsiElement[] pattern = ReadAction.compute(() -> getPatternElements());
PsiElement[] patternCopy = ReadAction.compute(() -> {
PsiFile patternFile = pattern[0].getContainingFile();
return IntroduceParameterHandler.getElementsInCopy(myProject, patternFile, pattern, false);
});
progress.increment();
ExtractMethodSnapshot copySnapshot = ReadAction.compute(() -> new ExtractMethodSnapshot(mySnapshot, pattern, patternCopy));
ExtractMethodProcessor copyProcessor = ReadAction.compute(() -> {
JavaDuplicatesExtractMethodProcessor processor = new JavaDuplicatesExtractMethodProcessor(patternCopy, REFACTORING_NAME);
return processor.prepareFromSnapshot(copySnapshot, true) ? processor : null;
});
if (copyProcessor == null) return;
Map<DuplicateNode, Match> duplicateMatches = ReadAction.compute(() -> findSelectedDuplicates(copyProcessor, selectedNodes));
List<Duplicate> excludedDuplicates =
onlyEnabled && allNodes.size() != duplicateMatches.size()
? ReadAction.compute(() -> collectExcludedRanges(allNodes, duplicateMatches.keySet(), patternCopy[0].getContainingFile()))
: Collections.emptyList();
Bounds patternReplacementBounds = ReadAction.compute(() -> {
Bounds patternBounds = new Bounds(patternCopy[0], patternCopy[patternCopy.length - 1]);
copyProcessor.doExtract();
return patternBounds;
});
progress.increment();
ReadAction.run(() -> copyProcessor.initParametrizedDuplicates(false));
progress.increment();
List<Duplicate> duplicateReplacements = new ArrayList<>();
for (Map.Entry<DuplicateNode, Match> entry : duplicateMatches.entrySet()) {
DuplicateNode duplicateNode = entry.getKey();
Match duplicate = entry.getValue();
ReadAction.run(() -> {
Bounds bounds = new Bounds(duplicate.getMatchStart(), duplicate.getMatchEnd());
copyProcessor.processMatch(duplicate);
ElementsRange replacement = bounds.getElementsRange();
duplicateReplacements.add(new Duplicate(duplicateNode, replacement));
});
progress.increment(); // +size()
}
PsiMethod method = ReadAction.compute(() -> {
PsiMethod extractedMethod = copyProcessor.getExtractedMethod();
return (PsiMethod)CodeStyleManager.getInstance(myProject).reformat(extractedMethod);
});
ElementsRange patternReplacement = ReadAction.compute(() -> patternReplacementBounds.getElementsRange());
Document refactoredDocument = ReadAction.compute(() -> {
PsiFile refactoredFile = method.getContainingFile();
if (refactoredFile != null) {
VirtualFile vFile = refactoredFile.getViewProvider().getVirtualFile();
vFile.putUserData(DiffUtil.TEMP_FILE_KEY, Boolean.TRUE); // prevent Go To action to non-physical file
return FileDocumentManager.getInstance().getDocument(vFile);
}
return null;
});
progress.increment();
if (refactoredDocument != null) {
ApplicationManager.getApplication().invokeLater(() -> {
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
documentManager.doPostponedOperationsAndUnblockDocument(refactoredDocument);
MethodNode methodNode = myTree.getModel().updateMethod(method);
initDiff(pattern, patternReplacement, refactoredDocument,
methodNode, method.getTextRange(),
duplicateReplacements, excludedDuplicates);
myTree.onUpdateLater();
});
}
}
private void initDiff(@NotNull PsiElement[] pattern,
@NotNull ElementsRange patternReplacement,
@NotNull Document refactoredDocument,
@NotNull MethodNode methodNode,
@NotNull TextRange methodRange,
@NotNull List<Duplicate> duplicateReplacements,
@NotNull List<Duplicate> excludedDuplicates) {
PsiFile patternFile = pattern[0].getContainingFile();
myPatternDocument = FileDocumentManager.getInstance().getDocument(patternFile.getViewProvider().getVirtualFile());
if (myPatternDocument == null) {
return;
}
myInitialDocumentStamp = myPatternDocument.getModificationStamp();
List<Range> diffRanges = new ArrayList<>();
Map<FragmentNode, Couple<TextRange>> linesBounds = new HashMap<>();
collectDiffRanges(refactoredDocument, diffRanges, linesBounds, duplicateReplacements);
collectDiffRanges(refactoredDocument, diffRanges, linesBounds, excludedDuplicates);
PsiElement anchorElement = myAnchor.getElement();
if (anchorElement != null) {
int anchorOffset = anchorElement.getTextRange().getEndOffset();
int anchorLineNumber = myPatternDocument.getLineNumber(anchorOffset);
Range diffRange = new Range(anchorLineNumber,
anchorLineNumber,
getStartLineNumber(refactoredDocument, methodRange),
getLineNumberAfter(refactoredDocument, methodRange));
diffRanges.add(diffRange);
linesBounds.put(methodNode, Couple.of(new TextRange(anchorOffset, anchorOffset),
getLinesRange(methodRange, refactoredDocument)));
}
TextRange patternRange = new ElementsRange(pattern).getTextRange();
TextRange replacementRange = patternReplacement.getTextRange();
Range diffRange = getDiffRange(patternRange, myPatternDocument, replacementRange, refactoredDocument);
if (diffRange != null) {
diffRanges.add(diffRange);
linesBounds.put(myTree.getModel().getPatternNode(), Couple.of(getLinesRange(patternRange, myPatternDocument),
getLinesRange(replacementRange, refactoredDocument)));
}
diffRanges.sort(Comparator.comparing(r -> r.start1));
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DocumentContent oldContent = contentFactory.create(myProject, myPatternDocument);
DocumentContent newContent = contentFactory.create(myProject, refactoredDocument);
myDiffRequest = new PreviewDiffRequest(linesBounds, oldContent, newContent, node -> myTree.selectNode(node));
myDiffRequest.putUserData(DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER, getDiffComputer(diffRanges));
myDiffPanel.setRequest(myDiffRequest);
myDiffRequest.onInitialized();
}
private void collectDiffRanges(@NotNull Document refactoredDocument,
@NotNull List<Range> diffRanges,
@NotNull Map<FragmentNode, Couple<TextRange>> linesBounds,
@NotNull List<Duplicate> duplicates) {
for (Duplicate duplicate : duplicates) {
DuplicateNode duplicateNode = duplicate.myNode;
TextRange patternRange = duplicateNode.getTextRange();
TextRange copyRange = duplicate.myCopy.getTextRange();
Range diffRange = getDiffRange(patternRange, myPatternDocument, copyRange, refactoredDocument);
if (diffRange != null) {
diffRanges.add(diffRange);
linesBounds.put(duplicateNode, Couple.of(getLinesRange(patternRange, myPatternDocument),
getLinesRange(copyRange, refactoredDocument)));
}
}
}
private static int getStartLineNumber(Document document, TextRange textRange) {
return document.getLineNumber(textRange.getStartOffset());
}
private static int getLineNumberAfter(Document document, TextRange textRange) {
return Math.min(document.getLineNumber(textRange.getEndOffset()) + 1, document.getLineCount());
}
private static Range getDiffRange(@Nullable TextRange patternRange,
@NotNull Document patternDocument,
@Nullable TextRange refactoredRange,
@NotNull Document refactoredDocument) {
if (patternRange == null || refactoredRange == null) {
return null;
}
return new Range(getStartLineNumber(patternDocument, patternRange),
getLineNumberAfter(patternDocument, patternRange),
getStartLineNumber(refactoredDocument, refactoredRange),
getLineNumberAfter(refactoredDocument, refactoredRange));
}
@NotNull
private static TextRange getLinesRange(@NotNull TextRange textRange, @NotNull Document document) {
int startLine = document.getLineNumber(textRange.getStartOffset());
int endLine = document.getLineNumber(Math.min(textRange.getEndOffset(), document.getTextLength()));
return new TextRange(document.getLineStartOffset(startLine), document.getLineEndOffset(endLine));
}
private static List<Duplicate> collectExcludedRanges(@NotNull List<DuplicateNode> allNodes,
@NotNull Set<DuplicateNode> selectedNodes,
@NotNull PsiFile copyFile) {
List<Duplicate> excludedRanges = new ArrayList<>();
for (DuplicateNode node : allNodes) {
if (selectedNodes.contains(node)) {
continue;
}
ElementsRange elementsRange = node.getElementsRange();
if (elementsRange != null) {
ElementsRange copyRange = elementsRange.findCopyInFile(copyFile);
if (copyRange != null) {
excludedRanges.add(new Duplicate(node, copyRange));
}
}
}
return excludedRanges;
}
private static void doExtractImpl(@NotNull JavaDuplicatesExtractMethodProcessor processor,
@NotNull List<? extends DuplicateNode> selectedNodes) {
Map<DuplicateNode, Match> selectedDuplicates = findSelectedDuplicates(processor, selectedNodes);
processor.doExtract();
processor.initParametrizedDuplicates(false);
for (Match duplicate : selectedDuplicates.values()) {
processor.processMatch(duplicate);
}
PsiMethodCallExpression methodCall = processor.getMethodCall();
if (methodCall != null && methodCall.isValid()) {
Editor editor = getEditor(methodCall.getContainingFile(), false);
if (editor != null) {
editor.getSelectionModel().removeSelection();
editor.getCaretModel().moveToOffset(methodCall.getTextOffset());
}
}
}
@Override
public void onNodeSelected(@NotNull FragmentNode node) {
if (myDiffRequest != null) {
myDiffRequest.onNodeSelected(node);
}
}
@NotNull
private static Map<DuplicateNode, Match> findSelectedDuplicates(@NotNull ExtractMethodProcessor processor,
@NotNull List<? extends DuplicateNode> selectedNodes) {
Set<TextRange> textRanges = ContainerUtil.map2SetNotNull(selectedNodes, FragmentNode::getTextRange);
processor.previewRefactoring(textRanges);
List<Match> duplicates = processor.getAnyDuplicates();
return filterSelectedDuplicates(selectedNodes, duplicates);
}
@NotNull
private static Map<DuplicateNode, Match> filterSelectedDuplicates(@NotNull Collection<? extends DuplicateNode> selectedNodes,
@Nullable List<Match> allDuplicates) {
if (ContainerUtil.isEmpty(allDuplicates)) {
return Collections.emptyMap();
}
Map<DuplicateNode, Match> selectedDuplicates = new THashMap<>();
for (DuplicateNode duplicateNode : selectedNodes) {
TextRange selectedRange = duplicateNode.getTextRange();
if (selectedRange != null) {
for (Match duplicate : allDuplicates) {
PsiElement start = duplicate.getMatchStart();
PsiElement end = duplicate.getMatchEnd();
if (start != null && end != null &&
selectedRange.equalsToRange(start.getTextRange().getStartOffset(), end.getTextRange().getEndOffset())) {
selectedDuplicates.put(duplicateNode, duplicate);
break;
}
}
}
}
return selectedDuplicates;
}
@NotNull
private static DiffUserDataKeysEx.DiffComputer getDiffComputer(@NotNull Collection<? extends Range> ranges) {
return (text1, text2, policy, innerChanges, indicator) -> {
LineOffsets offsets1 = LineOffsetsUtil.create(text1);
LineOffsets offsets2 = LineOffsetsUtil.create(text2);
List<LineFragment> result = new ArrayList<>();
ComparisonManagerImpl comparisonManager = ComparisonManagerImpl.getInstanceImpl();
for (Range range : ranges) {
result.addAll(comparisonManager.compareLinesInner(range, text1, text2, offsets1, offsets2, policy, innerChanges, indicator));
}
return result;
};
}
public void tryExtractAgain() {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
PsiElement[] elements = getPatternElements();
if (elements.length != 0) {
PsiFile psiFile = elements[0].getContainingFile();
if (psiFile != null) {
ExtractMethodSnapshot.SNAPSHOT_KEY.set(psiFile, mySnapshot);
try {
Editor editor = getEditor(psiFile, true);
ExtractMethodHandler.invokeOnElements(myProject, editor, psiFile, elements);
return;
}
finally {
ExtractMethodSnapshot.SNAPSHOT_KEY.set(psiFile, null);
}
}
}
Messages.showErrorDialog(myProject, "Can't restore context for method extraction", "Failed to Re-Run Refactoring");
}
@NotNull
private PsiElement[] getPatternElements() {
PsiElement[] elements = ContainerUtil.map2Array(myPattern, PsiElement.EMPTY_ARRAY, SmartPsiElementPointer::getElement);
if (ArrayUtil.contains(null, elements)) {
return PsiElement.EMPTY_ARRAY;
}
return elements;
}
@Nullable
private static Editor getEditor(@NotNull PsiFile psiFile, boolean canCreate) {
VirtualFile vFile = psiFile.getViewProvider().getVirtualFile();
Document document = FileDocumentManager.getInstance().getDocument(vFile);
if (document == null) {
return null;
}
EditorFactory factory = EditorFactory.getInstance();
Project project = psiFile.getProject();
Editor[] editors = factory.getEditors(document, project);
if (editors.length != 0) {
return editors[0];
}
return canCreate ? EditorFactory.getInstance().createEditor(document, project) : null;
}
boolean isModified() {
return myPatternDocument == null || myPatternDocument.getModificationStamp() != myInitialDocumentStamp;
}
private static class Bounds {
private static final Class[] SKIP_TYPES = {PsiWhiteSpace.class, PsiComment.class, PsiEmptyStatement.class};
final PsiElement myParent;
final PsiElement myBefore;
final PsiElement myAfter;
public Bounds(@NotNull PsiElement start, @NotNull PsiElement end) {
myParent = start.getParent();
assert myParent != null : "bounds' parent is null";
myBefore = PsiTreeUtil.skipSiblingsBackward(start, SKIP_TYPES);
myAfter = PsiTreeUtil.skipSiblingsForward(end, SKIP_TYPES);
}
ElementsRange getElementsRange() {
PsiElement start = PsiTreeUtil.skipSiblingsForward(myBefore, SKIP_TYPES);
PsiElement end = PsiTreeUtil.skipSiblingsBackward(myAfter, SKIP_TYPES);
if (start == null) start = myParent.getFirstChild();
if (end == null) end = myParent.getLastChild();
if (start != null && end != null) {
return new ElementsRange(start, end);
}
return new ElementsRange(myParent, myParent);
}
}
private static class Duplicate {
final DuplicateNode myNode;
final ElementsRange myCopy;
Duplicate(DuplicateNode node, ElementsRange copy) {
myNode = node;
myCopy = copy;
}
}
static class IncrementalProgress {
private final ProgressIndicator myIndicator;
private final double myTotal;
private int myCount;
IncrementalProgress(@NotNull ProgressIndicator indicator, int total) {
myIndicator = indicator;
myTotal = total;
indicator.setIndeterminate(false);
}
void increment() {
myIndicator.setFraction(++myCount / myTotal);
}
}
}
|
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.picard.sam.SamPairUtil;
import net.sf.samtools.*;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.util.*;
/**
* A locally resorting, mate fixing sam file writer that supports an idiom where reads are only moved around if
* the ISIZE of the pair is < X and reads are not allowed to move any more than Y bp from their original positions.
*
* To understand this data structure, let's begin by asking -- when are we certain we know the position of read R added
* to the writer and its mate M given that R has been added to the writer (but M may not be), their ISIZE in R, at the
* moment that a read K is added to the writer, under the constraints X and Y? Complex I know. First, because
* reads cannot move more than Y bp in either direction, we know that R originated at most R.pos + Y bp from its
* current position. Also, we know that K is at most K.pos + Y bp from it's original position. If R is maximally
* shifted to the right, and K shifted to the left, then they could at most move 2Y together. So if the distance
* between R and K > 2Y, we know that there are no reads left in the original stream that could be moved before R.
*
* Now, we also need to be certain if we have a mate pair M, that won't emit R before we can incorporate any move of
* M into the mate pair info R. There are two cases to consider here:
*
* If ISIZE > X, we know that we won't move M when we see it, so we can safely emit R knowing that
* M is fixed in place.
*
* If ISIZE <= X, M might be moved, and it we have to wait until we see M in the stream to know it's position.
* So R must be buffered until either M arrives, or we see a read K that's more than 2Y units past the original position
* of M.
*
* So the worst-case memory consumption here is proportional to the number of reads
* occurring between R and M + 2 Y, and so is proportional to the depth of the data and X and Y.
*
* This leads to the following simple algorithm:
*
* addAlignment(newRead):
* addReadToListOfReads(newRead)
* update mate pair of newRead if present in list of reads
*
* for ( read in list of reads [in order of increasing read.pos] ):
* if read.pos < newRead.pos - 2Y && (read.isize >= X || read.matePos < newRead.pos - 2 * Y):
* emit read and remove from list of reads
* else:
* break
*
* @author depristo, ebanks
* @version 0.2
*/
public class ConstrainedMateFixingManager {
protected static final Logger logger = Logger.getLogger(ConstrainedMateFixingManager.class);
private static final boolean DEBUG = false;
/** How often do we check whether we want to emit reads? */
private final static int EMIT_FREQUENCY = 1000;
/**
* How much could a single read move in position from its original position?
*/
final int MAX_POS_MOVE_ALLOWED;
/**
* How many reads should we store in memory before flushing the queue?
*/
final int MAX_RECORDS_IN_MEMORY;
/** how we order our SAM records */
private final SAMRecordComparator comparer = new SAMRecordCoordinateComparator();
/** The place where we ultimately write out our records */
final SAMFileWriter writer;
/**
* what is the maximum isize of a pair of reads that can move? Reads with isize > this value
* are assumes to not be allowed to move in the incoming read stream.
*/
final int maxInsertSizeForMovingReadPairs;
final GenomeLocParser genomeLocParser;
private GenomeLoc lastLocFlushed = null;
int counter = 0;
/** read.name -> records */
HashMap<String, SAMRecordHashObject> forMateMatching = new HashMap<String, SAMRecordHashObject>();
TreeSet<SAMRecord> waitingReads = new TreeSet<SAMRecord>(comparer);
private <T> T remove(TreeSet<T> treeSet) {
final T first = treeSet.first();
treeSet.remove(first);
return first;
}
private class SAMRecordHashObject {
public SAMRecord record;
public boolean wasModified;
public SAMRecordHashObject(SAMRecord record, boolean wasModified) {
this.record = record;
this.wasModified = wasModified;
}
}
//private SimpleTimer timer = new SimpleTimer("ConstrainedWriter");
//private long PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds
//private long lastProgressPrintTime = -1; // When was the last time we printed progress log?
/**
*
* @param writer actual writer
* @param genomeLocParser the GenomeLocParser object
* @param maxInsertSizeForMovingReadPairs max insert size allowed for moving pairs
* @param maxMoveAllowed max positional move allowed for any read
* @param maxRecordsInMemory max records to keep in memory
*/
public ConstrainedMateFixingManager(final SAMFileWriter writer,
final GenomeLocParser genomeLocParser,
final int maxInsertSizeForMovingReadPairs,
final int maxMoveAllowed,
final int maxRecordsInMemory) {
this.writer = writer;
this.genomeLocParser = genomeLocParser;
this.maxInsertSizeForMovingReadPairs = maxInsertSizeForMovingReadPairs;
this.MAX_POS_MOVE_ALLOWED = maxMoveAllowed;
this.MAX_RECORDS_IN_MEMORY = maxRecordsInMemory;
//timer.start();
//lastProgressPrintTime = timer.currentTime();
}
public int getNReadsInQueue() { return waitingReads.size(); }
public boolean canMoveReads(GenomeLoc earliestPosition) {
if ( DEBUG ) logger.info("Refusing to realign? " + earliestPosition + " vs. " + lastLocFlushed);
return lastLocFlushed == null ||
lastLocFlushed.compareContigs(earliestPosition) != 0 ||
lastLocFlushed.distance(earliestPosition) > maxInsertSizeForMovingReadPairs;
}
private boolean noReadCanMoveBefore(int pos, SAMRecord addedRead) {
return pos + 2 * MAX_POS_MOVE_ALLOWED < addedRead.getAlignmentStart();
}
public void addRead(SAMRecord newRead, boolean readWasModified) {
addRead(newRead, readWasModified, true);
}
public void addReads(List<SAMRecord> newReads, Set<SAMRecord> modifiedReads) {
for ( SAMRecord newRead : newReads )
addRead(newRead, modifiedReads.contains(newRead), false);
}
private void addRead(SAMRecord newRead, boolean readWasModified, boolean canFlush) {
if ( DEBUG ) logger.info("New read pos " + newRead.getAlignmentStart() + " OP = " + newRead.getAttribute("OP") + " " + readWasModified);
//final long curTime = timer.currentTime();
//if ( curTime - lastProgressPrintTime > PROGRESS_PRINT_FREQUENCY ) {
// lastProgressPrintTime = curTime;
// System.out.println("WaitingReads.size = " + waitingReads.size() + ", forMateMatching.size = " + forMateMatching.size());
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
if ( canFlush && (tooManyReads || (getNReadsInQueue() > 0 && !waitingReads.first().getReferenceIndex().equals(newRead.getReferenceIndex()))) ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + newRead.getReferenceName() + " from " + waitingReads.first().getReferenceName())) + " at " + newRead.getAlignmentStart());
while ( getNReadsInQueue() > 1 ) {
// emit to disk
writeRead(remove(waitingReads));
}
SAMRecord lastRead = remove(waitingReads);
lastLocFlushed = (lastRead.getReferenceIndex() == -1) ? null : genomeLocParser.createGenomeLoc(lastRead);
writeRead(lastRead);
if ( !tooManyReads )
forMateMatching.clear();
else
purgeUnmodifiedMates();
}
// fix mates, as needed
// Since setMateInfo can move reads, we potentially need to remove the mate, and requeue
// it to ensure proper sorting
if ( newRead.getReadPairedFlag() ) {
SAMRecordHashObject mate = forMateMatching.get(newRead.getReadName());
if ( mate != null ) {
// 1. Frustratingly, Picard's setMateInfo() method unaligns (by setting the reference contig
// to '*') read pairs when both of their flags have the unmapped bit set. This is problematic
// when trying to emit reads in coordinate order because all of a sudden we have reads in the
// middle of the bam file that now belong at the end - and any mapped reads that get emitted
// after them trigger an exception in the writer. For our purposes, because we shouldn't be
// moving read pairs when they are both unmapped anyways, we'll just not run fix mates on them.
// 2. Furthermore, when reads get mapped to the junction of two chromosomes (e.g. MT since it
// is actually circular DNA), their unmapped bit is set, but they are given legitimate coordinates.
// The Picard code will come in and move the read all the way back to its mate (which can be
// arbitrarily far away). However, we do still want to move legitimately unmapped reads whose
// mates are mapped, so the compromise will be that if the mate is still in the queue then we'll
// move the read and otherwise we won't.
boolean doNotFixMates = newRead.getReadUnmappedFlag() && (mate.record.getReadUnmappedFlag() || !waitingReads.contains(mate.record));
if ( !doNotFixMates ) {
boolean reQueueMate = mate.record.getReadUnmappedFlag() && ! newRead.getReadUnmappedFlag();
if ( reQueueMate ) {
// the mate was unmapped, but newRead was mapped, so the mate may have been moved
// to be next-to newRead, so needs to be reinserted into the waitingReads queue
// note -- this must be called before the setMateInfo call below
if ( ! waitingReads.remove(mate.record) )
// we must have hit a region with too much depth and flushed the queue
reQueueMate = false;
}
// we've already seen our mate -- set the mate info and remove it from the map
SamPairUtil.setMateInfo(mate.record, newRead, null);
if ( reQueueMate ) waitingReads.add(mate.record);
}
forMateMatching.remove(newRead.getReadName());
} else if ( pairedReadIsMovable(newRead) ) {
forMateMatching.put(newRead.getReadName(), new SAMRecordHashObject(newRead, readWasModified));
}
}
waitingReads.add(newRead);
if ( ++counter % EMIT_FREQUENCY == 0 ) {
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
SAMRecord read = waitingReads.first();
if ( noReadCanMoveBefore(read.getAlignmentStart(), newRead) &&
(!pairedReadIsMovable(read) // we won't try to move such a read
|| noReadCanMoveBefore(read.getMateAlignmentStart(), newRead ) ) ) { // we're already past where the mate started
// remove reads from the map that we have emitted -- useful for case where the mate never showed up
forMateMatching.remove(read.getReadName());
if ( DEBUG )
logger.warn(String.format("EMIT! At %d: read %s at %d with isize %d, mate start %d, op = %s",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(),
read.getInferredInsertSize(), read.getMateAlignmentStart(), read.getAttribute("OP")));
// emit to disk
writeRead(remove(waitingReads));
} else {
if ( DEBUG )
logger.warn(String.format("At %d: read %s at %d with isize %d couldn't be emited, mate start %d",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(), read.getInferredInsertSize(), read.getMateAlignmentStart()));
break;
}
}
if ( DEBUG ) logger.warn(String.format("At %d: Done with emit cycle", newRead.getAlignmentStart()));
}
}
private void writeRead(SAMRecord read) {
try {
writer.addAlignment(read);
} catch (IllegalArgumentException e) {
throw new UserException("If the maximum allowable reads in memory is too small, it may cause reads to be written out of order when trying to write the BAM; please see the --maxReadsInMemory argument for details. " + e.getMessage(), e);
}
}
/**
* @param read the read
* @return true if the read shouldn't be moved given the constraints of this SAMFileWriter
*/
public boolean iSizeTooBigToMove(SAMRecord read) {
return iSizeTooBigToMove(read, maxInsertSizeForMovingReadPairs); // we won't try to move such a read
}
public static boolean iSizeTooBigToMove(SAMRecord read, int maxInsertSizeForMovingReadPairs) {
return ( read.getReadPairedFlag() && ! read.getMateUnmappedFlag() && read.getReferenceName() != read.getMateReferenceName() ) // maps to different chromosomes
|| Math.abs(read.getInferredInsertSize()) > maxInsertSizeForMovingReadPairs; // we won't try to move such a read
}
private void purgeUnmodifiedMates() {
HashMap<String, SAMRecordHashObject> forMateMatchingCleaned = new HashMap<String, SAMRecordHashObject>();
for ( Map.Entry<String, SAMRecordHashObject> entry : forMateMatching.entrySet() ) {
if ( entry.getValue().wasModified )
forMateMatchingCleaned.put(entry.getKey(), entry.getValue());
}
forMateMatching.clear(); // explicitly clear the memory
forMateMatching = forMateMatchingCleaned;
}
private boolean pairedReadIsMovable(SAMRecord read) {
return read.getReadPairedFlag() // we're a paired read
&& (!read.getReadUnmappedFlag() || !read.getMateUnmappedFlag()) // at least one read is mapped
&& !iSizeTooBigToMove(read); // insert size isn't too big
}
public void close() {
// write out all of the remaining reads
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
writeRead(remove(waitingReads));
}
}
}
|
package com.altamiracorp.lumify.securegraph.model.workspace;
import com.altamiracorp.lumify.core.exception.LumifyAccessDeniedException;
import com.altamiracorp.lumify.core.exception.LumifyResourceNotFoundException;
import com.altamiracorp.lumify.core.model.ontology.Concept;
import com.altamiracorp.lumify.core.model.ontology.OntologyLumifyProperties;
import com.altamiracorp.lumify.core.model.ontology.OntologyRepository;
import com.altamiracorp.lumify.core.model.ontology.Relationship;
import com.altamiracorp.lumify.core.model.user.AuthorizationRepository;
import com.altamiracorp.lumify.core.model.user.UserRepository;
import com.altamiracorp.lumify.core.model.workspace.*;
import com.altamiracorp.lumify.core.model.workspace.diff.DiffItem;
import com.altamiracorp.lumify.core.model.workspace.diff.WorkspaceDiff;
import com.altamiracorp.lumify.core.security.LumifyVisibility;
import com.altamiracorp.lumify.core.user.User;
import com.altamiracorp.lumify.core.util.LumifyLogger;
import com.altamiracorp.lumify.core.util.LumifyLoggerFactory;
import com.altamiracorp.lumify.securegraph.model.user.SecureGraphUserRepository;
import com.altamiracorp.securegraph.*;
import com.altamiracorp.securegraph.mutation.ElementMutation;
import com.altamiracorp.securegraph.util.ConvertingIterable;
import com.altamiracorp.securegraph.util.VerticesToEdgeIdsIterable;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.altamiracorp.securegraph.util.IterableUtils.toList;
import static com.altamiracorp.securegraph.util.IterableUtils.toSet;
import static com.google.common.base.Preconditions.checkNotNull;
@Singleton
public class SecureGraphWorkspaceRepository extends WorkspaceRepository {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(SecureGraphWorkspaceRepository.class);
private Graph graph;
private String workspaceConceptId;
private String workspaceToEntityRelationshipId;
private String workspaceToUserRelationshipId;
private UserRepository userRepository;
private AuthorizationRepository authorizationRepository;
private WorkspaceDiff workspaceDiff;
private Cache<String, Boolean> usersWithReadAccessCache = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.SECONDS)
.build();
private Cache<String, Boolean> usersWithWriteAccessCache = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.SECONDS)
.build();
@Inject
public SecureGraphWorkspaceRepository(
OntologyRepository ontologyRepository,
Graph graph,
UserRepository userRepository,
AuthorizationRepository authorizationRepository,
WorkspaceDiff workspaceDiff) {
this.graph = graph;
this.userRepository = userRepository;
this.authorizationRepository = authorizationRepository;
this.workspaceDiff = workspaceDiff;
authorizationRepository.addAuthorizationToGraph(VISIBILITY_STRING);
authorizationRepository.addAuthorizationToGraph(LumifyVisibility.SUPER_USER_VISIBILITY_STRING);
Concept rootConcept = ontologyRepository.getConceptByIRI(OntologyRepository.ROOT_CONCEPT_IRI);
Concept workspaceConcept = ontologyRepository.getOrCreateConcept(null, WORKSPACE_CONCEPT_NAME, "workspace");
workspaceConceptId = workspaceConcept.getTitle();
Relationship workspaceToEntityRelationship = ontologyRepository.getOrCreateRelationshipType(workspaceConcept, rootConcept, WORKSPACE_TO_ENTITY_RELATIONSHIP_NAME, "workspace to entity");
workspaceToEntityRelationshipId = workspaceToEntityRelationship.getIRI();
Relationship workspaceToUserRelationship = ontologyRepository.getOrCreateRelationshipType(workspaceConcept, rootConcept, WORKSPACE_TO_USER_RELATIONSHIP_NAME, "workspace to user");
workspaceToUserRelationshipId = workspaceToUserRelationship.getIRI();
}
@Override
public void delete(Workspace workspace, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, UserRepository.VISIBILITY_STRING, LumifyVisibility.SUPER_USER_VISIBILITY_STRING, workspace.getId());
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
graph.removeVertex(workspaceVertex, authorizations);
graph.flush();
authorizationRepository.removeAuthorizationFromGraph(workspace.getId());
}
private Vertex getVertexFromWorkspace(Workspace workspace, Authorizations authorizations) {
if (workspace instanceof SecureGraphWorkspace) {
return ((SecureGraphWorkspace) workspace).getVertex(graph, authorizations);
}
return graph.getVertex(workspace.getId(), authorizations);
}
@Override
public Workspace findById(String workspaceId, User user) {
LOGGER.debug("findById(workspaceId: %s, userId: %s)", workspaceId, user.getUserId());
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspaceId);
Vertex workspaceVertex = graph.getVertex(workspaceId, authorizations);
if (workspaceVertex == null) {
return null;
}
Workspace workspace = new SecureGraphWorkspace(workspaceVertex);
if (!doesUserHaveReadAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have read access to workspace " + workspace.getId(), user, workspace.getId());
}
return workspace;
}
@Override
public Workspace add(String title, User user) {
String workspaceId = WORKSPACE_ID_PREFIX + graph.getIdGenerator().nextId();
authorizationRepository.addAuthorizationToGraph(workspaceId);
Authorizations authorizations = userRepository.getAuthorizations(user, UserRepository.VISIBILITY_STRING, VISIBILITY_STRING, workspaceId);
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
checkNotNull(userVertex, "Could not find user: " + user.getUserId());
VertexBuilder workspaceVertexBuilder = graph.prepareVertex(workspaceId, VISIBILITY.getVisibility(), authorizations);
OntologyLumifyProperties.CONCEPT_TYPE.setProperty(workspaceVertexBuilder, workspaceConceptId, VISIBILITY.getVisibility());
WorkspaceLumifyProperties.TITLE.setProperty(workspaceVertexBuilder, title, VISIBILITY.getVisibility());
Vertex workspaceVertex = workspaceVertexBuilder.save();
EdgeBuilder edgeBuilder = graph.prepareEdge(workspaceVertex, userVertex, workspaceToUserRelationshipId, VISIBILITY.getVisibility(), authorizations);
WorkspaceLumifyProperties.WORKSPACE_TO_USER_IS_CREATOR.setProperty(edgeBuilder, true, VISIBILITY.getVisibility());
WorkspaceLumifyProperties.WORKSPACE_TO_USER_ACCESS.setProperty(edgeBuilder, WorkspaceAccess.WRITE.toString(), VISIBILITY.getVisibility());
edgeBuilder.save();
graph.flush();
return new SecureGraphWorkspace(workspaceVertex);
}
@Override
public Iterable<Workspace> findAll(User user) {
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, UserRepository.VISIBILITY_STRING);
Iterable<Vertex> vertices = graph.getVertex(user.getUserId(), authorizations).getVertices(Direction.IN, workspaceToUserRelationshipId, authorizations);
return toWorkspaceIterable(vertices, user);
}
@Override
public void setTitle(Workspace workspace, String title, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user);
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
WorkspaceLumifyProperties.TITLE.setProperty(workspaceVertex, title, VISIBILITY.getVisibility());
graph.flush();
}
@Override
public List<WorkspaceUser> findUsersWithAccess(final Workspace workspace, final User user) {
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
Iterable<Edge> userEdges = workspaceVertex.getEdges(Direction.BOTH, workspaceToUserRelationshipId, authorizations);
return toList(new ConvertingIterable<Edge, WorkspaceUser>(userEdges) {
@Override
protected WorkspaceUser convert(Edge edge) {
String userId = edge.getOtherVertexId(workspace.getId()).toString();
String accessString = WorkspaceLumifyProperties.WORKSPACE_TO_USER_ACCESS.getPropertyValue(edge);
WorkspaceAccess workspaceAccess = WorkspaceAccess.NONE;
if (accessString != null && accessString.length() > 0) {
workspaceAccess = WorkspaceAccess.valueOf(accessString);
}
boolean isCreator = WorkspaceLumifyProperties.WORKSPACE_TO_USER_IS_CREATOR.getPropertyValue(edge, false);
return new WorkspaceUser(userId, workspaceAccess, isCreator);
}
});
}
@Override
public List<WorkspaceEntity> findEntities(final Workspace workspace, User user) {
LOGGER.debug("findEntities(workspaceId: %s, userId: %s)", workspace.getId(), user.getUserId());
if (!doesUserHaveReadAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have read access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
Iterable<Edge> entityEdges = workspaceVertex.getEdges(Direction.BOTH, workspaceToEntityRelationshipId, authorizations);
return toList(new ConvertingIterable<Edge, WorkspaceEntity>(entityEdges) {
@Override
protected WorkspaceEntity convert(Edge edge) {
Object entityVertexId = edge.getOtherVertexId(workspace.getId());
int graphPositionX = WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_X.getPropertyValue(edge, 0);
int graphPositionY = WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_Y.getPropertyValue(edge, 0);
boolean visible = WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_VISIBLE.getPropertyValue(edge, false);
return new WorkspaceEntity(entityVertexId, visible, graphPositionX, graphPositionY);
}
});
}
private Iterable<Edge> findEdges(final Workspace workspace, List<WorkspaceEntity> workspaceEntities, User user) {
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Iterable<Vertex> vertices = WorkspaceEntity.toVertices(graph, workspaceEntities, authorizations);
Iterable<Object> edgeIds = toSet(new VerticesToEdgeIdsIterable(vertices, authorizations));
final Iterable<Edge> edges = graph.getEdges(edgeIds, authorizations);
return edges;
}
@Override
public Workspace copy(Workspace workspace, User user) {
Workspace newWorkspace = add("Copy of " + workspace.getDisplayTitle(), user);
List<WorkspaceEntity> entities = findEntities(workspace, user);
for (WorkspaceEntity entity : entities) {
updateEntityOnWorkspace(newWorkspace, entity.getEntityVertexId(), entity.isVisible(), entity.getGraphPositionX(), entity.getGraphPositionY(), user);
}
// TODO should we copy users?
graph.flush();
return newWorkspace;
}
@Override
public void softDeleteEntityFromWorkspace(Workspace workspace, Object vertexId, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Vertex otherVertex = graph.getVertex(vertexId, authorizations);
if (otherVertex == null) {
throw new LumifyResourceNotFoundException("Could not find vertex: " + vertexId, vertexId);
}
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
List<Edge> edges = toList(workspaceVertex.getEdges(otherVertex, Direction.BOTH, authorizations));
for (Edge edge : edges) {
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_VISIBLE.setProperty(edge, false, VISIBILITY.getVisibility());
}
graph.flush();
}
@Override
public void updateEntityOnWorkspace(Workspace workspace, Object vertexId, Boolean visible, Integer graphPositionX, Integer graphPositionY, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
if (workspaceVertex == null) {
throw new LumifyResourceNotFoundException("Could not find workspace vertex: " + workspace.getId(), workspace.getId());
}
Vertex otherVertex = graph.getVertex(vertexId, authorizations);
if (otherVertex == null) {
throw new LumifyResourceNotFoundException("Could not find vertex: " + vertexId, vertexId);
}
List<Edge> existingEdges = toList(workspaceVertex.getEdges(otherVertex, Direction.BOTH, authorizations));
if (existingEdges.size() > 0) {
for (Edge existingEdge : existingEdges) {
ElementMutation<Edge> m = existingEdge.prepareMutation();
if (graphPositionX != null && graphPositionY != null) {
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_X.setProperty(m, graphPositionX, VISIBILITY.getVisibility());
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_Y.setProperty(m, graphPositionY, VISIBILITY.getVisibility());
}
if (visible != null) {
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_VISIBLE.setProperty(m, visible, VISIBILITY.getVisibility());
}
m.save();
}
} else {
EdgeBuilder edgeBuilder = graph.prepareEdge(workspaceVertex, otherVertex, workspaceToEntityRelationshipId, VISIBILITY.getVisibility(), authorizations);
if (graphPositionX != null && graphPositionY != null) {
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_X.setProperty(edgeBuilder, graphPositionX, VISIBILITY.getVisibility());
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_GRAPH_POSITION_Y.setProperty(edgeBuilder, graphPositionY, VISIBILITY.getVisibility());
}
if (visible != null) {
WorkspaceLumifyProperties.WORKSPACE_TO_ENTITY_VISIBLE.setProperty(edgeBuilder, visible, VISIBILITY.getVisibility());
}
edgeBuilder.save();
}
graph.flush();
}
@Override
public void deleteUserFromWorkspace(Workspace workspace, String userId, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, UserRepository.VISIBILITY_STRING, VISIBILITY_STRING, workspace.getId());
Vertex userVertex = graph.getVertex(userId, authorizations);
if (userVertex == null) {
throw new LumifyResourceNotFoundException("Could not find user: " + userId, userId);
}
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
List<Edge> edges = toList(workspaceVertex.getEdges(userVertex, Direction.BOTH, workspaceToUserRelationshipId, authorizations));
for (Edge edge : edges) {
graph.removeEdge(edge, authorizations);
}
graph.flush();
}
private boolean doesUserHaveWriteAccess(Workspace workspace, User user) {
String cacheKey = workspace.getId() + user.getUserId();
Boolean hasWriteAccess = usersWithWriteAccessCache.getIfPresent(cacheKey);
if (hasWriteAccess != null && hasWriteAccess) {
return true;
}
List<WorkspaceUser> usersWithAccess = findUsersWithAccess(workspace, user);
for (WorkspaceUser userWithAccess : usersWithAccess) {
if (userWithAccess.getUserId().equals(user.getUserId()) && userWithAccess.getWorkspaceAccess() == WorkspaceAccess.WRITE) {
usersWithWriteAccessCache.put(cacheKey, true);
return true;
}
}
return false;
}
private boolean doesUserHaveReadAccess(Workspace workspace, User user) {
String cacheKey = workspace.getId() + user.getUserId();
Boolean hasReadAccess = usersWithReadAccessCache.getIfPresent(cacheKey);
if (hasReadAccess != null && hasReadAccess) {
return true;
}
List<WorkspaceUser> usersWithAccess = findUsersWithAccess(workspace, user);
for (WorkspaceUser userWithAccess : usersWithAccess) {
if (userWithAccess.getUserId().equals(user.getUserId())
&& (userWithAccess.getWorkspaceAccess() == WorkspaceAccess.WRITE || userWithAccess.getWorkspaceAccess() == WorkspaceAccess.READ)) {
return true;
}
}
return false;
}
@Override
public void updateUserOnWorkspace(Workspace workspace, String userId, WorkspaceAccess workspaceAccess, User user) {
if (!doesUserHaveWriteAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
Authorizations authorizations = userRepository.getAuthorizations(user, VISIBILITY_STRING, workspace.getId());
Vertex otherUserVertex;
if (userRepository instanceof SecureGraphUserRepository) {
otherUserVertex = ((SecureGraphUserRepository) userRepository).findByIdUserVertex(userId);
} else {
otherUserVertex = graph.getVertex(userId, authorizations);
}
if (otherUserVertex == null) {
throw new LumifyResourceNotFoundException("Could not find user: " + userId, userId);
}
Vertex workspaceVertex = getVertexFromWorkspace(workspace, authorizations);
if (workspaceVertex == null) {
throw new LumifyResourceNotFoundException("Could not find workspace vertex: " + workspace.getId(), workspace.getId());
}
List<Edge> existingEdges = toList(workspaceVertex.getEdges(otherUserVertex, Direction.OUT, workspaceToUserRelationshipId, authorizations));
if (existingEdges.size() > 0) {
for (Edge existingEdge : existingEdges) {
WorkspaceLumifyProperties.WORKSPACE_TO_USER_ACCESS.setProperty(existingEdge, workspaceAccess.toString(), VISIBILITY.getVisibility());
}
} else {
EdgeBuilder edgeBuilder = graph.prepareEdge(workspaceVertex, otherUserVertex, workspaceToUserRelationshipId, VISIBILITY.getVisibility(), authorizations);
WorkspaceLumifyProperties.WORKSPACE_TO_USER_ACCESS.setProperty(edgeBuilder, workspaceAccess.toString(), VISIBILITY.getVisibility());
edgeBuilder.save();
}
graph.flush();
}
@Override
public List<DiffItem> getDiff(Workspace workspace, User user) {
if (!doesUserHaveReadAccess(workspace, user)) {
throw new LumifyAccessDeniedException("user " + user.getUserId() + " does not have write access to workspace " + workspace.getId(), user, workspace.getId());
}
List<WorkspaceEntity> workspaceEntities = findEntities(workspace, user);
List<Edge> workspaceEdges = toList(findEdges(workspace, workspaceEntities, user));
return workspaceDiff.diff(workspace, workspaceEntities, workspaceEdges, user);
}
@Override
public String getCreatorUserId(Workspace workspace, User user) {
for (WorkspaceUser workspaceUser : findUsersWithAccess(workspace, user)) {
if (workspaceUser.isCreator()) {
return workspaceUser.getUserId();
}
}
return null;
}
@Override
public boolean hasWritePermissions(Workspace workspace, User user) {
for (WorkspaceUser workspaceUser : findUsersWithAccess(workspace, user)) {
if (workspaceUser.getUserId().equals(user.getUserId())) {
return workspaceUser.getWorkspaceAccess() == WorkspaceAccess.WRITE;
}
}
return false;
}
private Iterable<Workspace> toWorkspaceIterable(Iterable<Vertex> vertices, final User user) {
return new ConvertingIterable<Vertex, Workspace>(vertices) {
@Override
protected Workspace convert(Vertex workspaceVertex) {
return new SecureGraphWorkspace(workspaceVertex);
}
};
}
}
|
package de.factoryfx.javafx.editor.attribute;
import de.factoryfx.data.attribute.Attribute;
import de.factoryfx.data.attribute.AttributeChangeListener;
import de.factoryfx.javafx.widget.Widget;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Node;
public class AttributeEditor<T> implements Widget {
public final AttributeEditorVisualisation<T> attributeEditorVisualisation;
private SimpleObjectProperty<T> bound = new SimpleObjectProperty<>();
private Attribute<T> boundAttribute;
public AttributeEditor(Attribute<T> boundAttribute, AttributeEditorVisualisation<T> attributeEditorVisualisation) {
this.boundAttribute=boundAttribute;
this.attributeEditorVisualisation=attributeEditorVisualisation;
bound.addListener((observable, oldValue, newValue1) -> {
if (!setLoop){
boundAttribute.set(newValue1);
}
});
bound.set(boundAttribute.get());
boundAttribute.addListener(attributeChangeListener);
}
boolean setLoop=false;
private AttributeChangeListener<T> attributeChangeListener = (attribute, value) -> {
setLoop=true;
if (value==bound.get()){
//workaround to force changelistener to trigger
//same ref doesn't mean the content didn't chnage e.g List
bound.set(null);
bound.set(value);
}
bound.set(value);
setLoop=false;
};
Node content;
@Override
public Node createContent() {
if (content==null){
content = attributeEditorVisualisation.createContent(bound);
}
return content;
}
public void unbind() {
content=null;
boundAttribute.removeListener(attributeChangeListener);
}
}
|
package com.madphysicist.tools.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
/**
* Displays information about an exception. The exception stack trace is shown
* in a non-editable but selectable text area below the message. This area can
* be expanded or collapsed by pressing a button. This class can show a dialog
* as well.
*
* @author Joseph Fox-Rabinovitz
* @version 1.0.0 21 Nov 2013 - J. Fox-Rabinovitz - Created
* @since 1.0.0
*/
public class ExceptionPanel extends JPanel
{
/**
* The version ID for serialization.
*
* @serial Increment the least significant three digits when compatibility
* is not compromised by a structural change (e.g. adding a new field with
* a sensible default value), and the upper digits when the change makes
* serialized versions of of the class incompatible with previous releases.
* @since 1.0.0
*/
private static final long serialVersionUID = 1000L;
/**
* The text that appears on the button notifying the user that the panel can
* be expanded.
*
* @since 1.0.0
*/
private static final String EXPAND_TEXT = "Details >>";
/**
* The text that appears on the button notifying the user that the panel can
* be collapsed.
*
* @since 1.0.0
*/
private static final String COLLAPSE_TEXT = "Details <<";
/**
* The exception that is displayed by this panel. The stack trace of the
* exception is shown if the user expands the panel.
*
* @serial
* @since 1.0.0
*/
private Throwable exception;
/**
* The message that is displayed by the panel. The message appears in the
* part of the panel that is always visible. The default value for the
* message is just the exception message.
*
* @serial
* @since 1.0.0
*/
private String message;
/**
* The label that displays the message. The label is always in the visible
* part of the component.
*
* @serial
* @since 1.0.0
*/
private JLabel messageLabel;
/**
* The button that triggers the expansion or collapse of the detailed
* description of the exception. The text of the button is either {@link
* #EXPAND_TEXT} if the detail area is collapsed, or {@link #COLLAPSE_TEXT}
* if the area is expanded. The button is placed differently if this panel
* appears in a dialog.
*
* @serial
* @since 1.0.0
*/
private JButton expandButton;
/**
* The text area containing the detailed exception information. The stack
* trace of the exception is printed into this area.
*
* @serial
* @since 1.0.0
*/
private JTextArea details;
/**
* The scroll pane containing the text area. The visibility of this
* component is altered to collapse or expand the details pane.
*
* @serial
* @since 1.0.0
*/
private JScrollPane collapsePane;
public ExceptionPanel(Throwable exception)
{
this(exception, exception.getMessage());
}
public ExceptionPanel(Throwable exception, String message)
{
this.exception = exception;
this.message = message;
initComponents();
}
private void initComponents()
{
messageLabel = new JLabel(message);
messageLabel.setHorizontalAlignment(SwingConstants.LEADING);
expandButton = new JButton(new AbstractAction(EXPAND_TEXT) {
private static final long serialVersionUID = 1000L;
@Override public void actionPerformed(ActionEvent e) {
if(collapsePane.isVisible()) {
collapsePane.setVisible(false);
expandButton.setText(EXPAND_TEXT);
} else {
collapsePane.setVisible(true);
expandButton.setText(COLLAPSE_TEXT);
}
Window window = SwingUtilities.windowForComponent(ExceptionPanel.this);
if(window != null) {
window.pack();
}
}
});
details = new JTextArea(stackTraceToString());
details.setBorder(new BevelBorder(BevelBorder.LOWERED));
details.setEditable(false);
details.setEnabled(true);
details.setLineWrap(false);
details.setTabSize(4);
details.setRows(20);
details.setFont(Font.decode(Font.MONOSPACED));
collapsePane = new JScrollPane(details);
collapsePane.setVisible(false);
setLayout(new GridBagLayout());
add(messageLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
GridBagConstants.FILL_HORIZONTAL_NORTH, 0, 0));
addExpandComponent(expandButton);
add(collapsePane, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
GridBagConstants.FILL_BOTH, 0, 0));
}
public String getMessage()
{
return message;
}
public Throwable getException()
{
return exception;
}
public void displayDialog(Window parent, String title)
{
new ExceptionDialog(parent, title).setVisible(true);
}
public static void showDialog(Throwable exception, Window parent, String title)
{
new ExceptionPanel(exception).displayDialog(parent, title);
}
public static void showDialog(Throwable exception, Window parent, String title, String message)
{
new ExceptionPanel(exception, message).displayDialog(parent, title);
}
private void addExpandComponent(Component component)
{
add(component, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0,
GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE,
GridBagConstants.SOUTHEAST, 0, 0));
}
@SuppressWarnings("ConvertToTryWithResources")
private String stackTraceToString()
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
pw.close();
return sw.toString();
}
/**
* The dialog displayed by the {@code displayDialog()} and static {@code
* showDialog()} methods of the parent class. This dialog adds an extra "OK"
* button to the panel which is removed once the dialog is closed.
*
* @author Joseph Fox-Rabinovitz
* @version 1.0.0 19 Nov 2013 - J. Fox-Rabinovitz - Created
* @since 1.0.0
*/
private class ExceptionDialog extends JDialog
{
/**
* The version ID for serialization.
*
* @serial Increment the least significant three digits when
* compatibility is not compromised by a structural change (e.g. adding
* a new field with a sensible default value), and the upper digits when
* the change makes serialized versions of of the class incompatible
* with previous releases.
* @since 1.0.0
*/
private static final long serialVersionUID = 1000L;
/**
* The panel that replaces {@link ExceptionPanel#expandButton} in the
* parent panel's layout. This panel contains the original button as
* well as an additional "OK" button that closes that dialog. When the
* dialog is closed, this panel is removed from the parent and replaced
* with the original button.
*
* @serial
* @since 1.0.0
*/
private JPanel expandPanel;
public ExceptionDialog(Window parent, String title)
{
super(parent, title, ModalityType.APPLICATION_MODAL);
JButton okButton = new JButton(new AbstractAction("OK") {
private static final long serialVersionUID = 1000L;
@Override public void actionPerformed(ActionEvent e) { destroy(); }
});
ExceptionPanel.this.remove(expandButton);
expandPanel = new JPanel(new GridLayout(1, 2,
GridBagConstants.HORIZONTAL_INSET,
GridBagConstants.VERTICAL_INSET));
expandPanel.add(expandButton);
expandPanel.add(okButton);
addExpandComponent(expandPanel);
setLayout(new BorderLayout());
add(ExceptionPanel.this, BorderLayout.CENTER);
getRootPane().setDefaultButton(okButton);
pack();
setResizable(true);
setLocationRelativeTo(parent);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) { destroy(); }
});
}
/**
* Destroys the dialog GUI. The visibility is set to {@code false} so
* that any methods blocking until the dialog disappears can continue.
* The extra "OK" button is removed from the panel once it is no longer
* displayed. The {@code ExceptionPanel} is removed from the dialog and
* system resources are freed.
*
* @since 1.0.0
*/
private void destroy()
{
setVisible(false);
ExceptionPanel.this.remove(expandPanel);
ExceptionPanel.this.addExpandComponent(expandButton);
remove(ExceptionPanel.this);
dispose();
}
}
/**
* Shows a small demo of this class with a {@code NullPointerException}.
*
* @param args the command line arguments, which are always ignored.
*/
public static void main(String[] args)
{
try {
Double.parseDouble(null);
} catch(Exception ex) {
showDialog(ex, null, "Demo of ExceptionPanel v1.0.0", "There has been an accident.");
}
}
}
|
package org.jtrim.taskgraph.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jtrim.cancel.Cancellation;
import org.jtrim.cancel.CancellationSource;
import org.jtrim.cancel.CancellationToken;
import org.jtrim.cancel.OperationCanceledException;
import org.jtrim.collections.CollectionsEx;
import org.jtrim.concurrent.CancelableFunction;
import org.jtrim.taskgraph.TaskFactory;
import org.jtrim.taskgraph.TaskFactoryConfig;
import org.jtrim.taskgraph.TaskFactoryGroupConfigurer;
import org.jtrim.taskgraph.TaskFactoryKey;
import org.jtrim.taskgraph.TaskFactoryProperties;
import org.jtrim.taskgraph.TaskFactorySetup;
import org.jtrim.taskgraph.TaskGraphBuilder;
import org.jtrim.taskgraph.TaskGraphBuilderProperties;
import org.jtrim.taskgraph.TaskGraphExecutor;
import org.jtrim.taskgraph.TaskInputBinder;
import org.jtrim.taskgraph.TaskInputRef;
import org.jtrim.taskgraph.TaskNodeCreateArgs;
import org.jtrim.taskgraph.TaskNodeKey;
import org.jtrim.taskgraph.TaskNodeProperties;
import org.jtrim.utils.ExceptionHelper;
public final class CollectingTaskGraphBuilder implements TaskGraphBuilder {
private static final Logger LOGGER = Logger.getLogger(CollectingTaskGraphBuilder.class.getName());
private final TaskGraphBuilderProperties.Builder properties;
private final Map<TaskFactoryKey<?, ?>, TaskFactoryConfig<?, ?>> configs;
private final TaskGraphExecutorFactory executorFactory;
private final Set<TaskNodeKey<?, ?>> nodeKeys;
public CollectingTaskGraphBuilder(
Collection<? extends TaskFactoryConfig<?, ?>> configs,
TaskGraphExecutorFactory executorFactory) {
ExceptionHelper.checkNotNullArgument(configs, "configs");
ExceptionHelper.checkNotNullArgument(executorFactory, "executorFactory");
this.properties = new TaskGraphBuilderProperties.Builder();
this.executorFactory = executorFactory;
this.nodeKeys = Collections.newSetFromMap(new ConcurrentHashMap<>());
this.configs = CollectionsEx.newHashMap(configs.size());
configs.forEach((config) -> {
this.configs.put(config.getDefKey(), config);
});
ExceptionHelper.checkNotNullArgument(this.configs, "configs");
}
@Override
public void addNode(TaskNodeKey<?, ?> nodeKey) {
if (!nodeKeys.add(nodeKey)) {
throw new IllegalStateException("Duplicate node key: " + nodeKey);
}
}
@Override
public TaskGraphBuilderProperties.Builder properties() {
return properties;
}
@Override
public CompletionStage<TaskGraphExecutor> buildGraph(CancellationToken cancelToken) {
ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken");
TaskGraphBuilderImpl builder = new TaskGraphBuilderImpl(
cancelToken, properties.build(), configs, executorFactory);
return builder.build(nodeKeys);
}
private static boolean isError(boolean canceled, Throwable error) {
if (canceled && (error instanceof OperationCanceledException)) {
return false;
}
return error != null;
}
private static final class TaskGraphBuilderImpl {
private final Map<TaskFactoryKey<?, ?>, FactoryDef<?, ?>> factoryDefs;
private final TaskGraphBuilderProperties properties;
private final CancellationSource graphBuildCancel;
private final Lock taskGraphLock;
private final Map<TaskNodeKey<?, ?>, BuildableTaskNode<?, ?>> nodes;
private final DirectedGraph.Builder<TaskNodeKey<?, ?>> taskGraphBuilder;
private final AtomicInteger outstandingBuilds;
private final CompletableFuture<TaskGraphExecutor> graphBuildResult;
private final TaskGraphExecutorFactory executorFactory;
public TaskGraphBuilderImpl(
CancellationToken cancelToken,
TaskGraphBuilderProperties properties,
Map<TaskFactoryKey<?, ?>, TaskFactoryConfig<?, ?>> factoryDefs,
TaskGraphExecutorFactory executorFactory) {
this.properties = properties;
this.taskGraphLock = new ReentrantLock();
this.nodes = new ConcurrentHashMap<>();
this.taskGraphBuilder = new DirectedGraph.Builder<>();
this.graphBuildCancel = Cancellation.createChildCancellationSource(cancelToken);
this.outstandingBuilds = new AtomicInteger(0);
this.graphBuildResult = new CompletableFuture<>();
this.executorFactory = executorFactory;
this.factoryDefs = CollectionsEx.newHashMap(factoryDefs.size());
// We try to minimize the configuration if possible
Map<TaskFactoryGroupConfigurer, LazyFactoryConfigurer> configurers = new IdentityHashMap<>();
TaskFactoryProperties defaultFactoryProperties = properties.getDefaultFactoryProperties();
factoryDefs.forEach((key, config) -> {
LazyFactoryConfigurer lazyConfigurer;
lazyConfigurer = configurers.computeIfAbsent(config.getConfigurer(), (groupConfigurer) -> {
return new LazyFactoryConfigurer(defaultFactoryProperties, groupConfigurer);
});
this.factoryDefs.put(key, factoryDef(lazyConfigurer, config));
});
}
public CompletionStage<TaskGraphExecutor> build(Set<TaskNodeKey<?, ?>> nodeKeys) {
try {
incOutstandingBuilds();
nodeKeys.forEach(this::addNode);
decOutstandingBuilds();
} catch (Throwable ex) {
graphBuildCancel.getController().cancel();
throw ex;
}
return graphBuildResult;
}
private static <R, I> FactoryDef<R, I> factoryDef(
LazyFactoryConfigurer lazyConfigurer,
TaskFactoryConfig<R, I> config) {
return new FactoryDef<>(config.getDefKey(), lazyConfigurer, config.getSetup());
}
private void addNode(TaskNodeKey<?, ?> nodeKey) {
ExceptionHelper.checkNotNullArgument(nodeKey, "nodeKey");
BuildableTaskNode<?, ?> newNode = new BuildableTaskNode<>(nodeKey);
BuildableTaskNode<?, ?> prev = nodes.putIfAbsent(nodeKey, newNode);
if (prev != null) {
throw new IllegalStateException("Node was already added with key: " + nodeKey);
}
buildChildren(graphBuildCancel.getToken(), newNode);
}
public <R> NodeTaskRef<R> createNode(
CancellationToken cancelToken,
TaskNodeKey<R, ?> nodeKey,
TaskInputBinder inputBinder) throws Exception {
return createNodeBridge(cancelToken, nodeKey, inputBinder);
}
private <R, I> NodeTaskRef<R> createNodeBridge(
CancellationToken cancelToken,
TaskNodeKey<R, I> nodeKey,
TaskInputBinder inputBinder) throws Exception {
TaskFactoryKey<R, I> factoryKey = nodeKey.getFactoryKey();
FactoryDef<R, I> factoryDef = getFactoryDef(factoryKey);
if (factoryDef == null) {
throw new IllegalStateException("Missing node factory definition for key: " + factoryKey);
}
I factoryArg = nodeKey.getFactoryArg();
return factoryDef.createTaskNode(cancelToken, factoryArg, inputBinder);
}
public <R, I> BuildableTaskNode<R, I> addAndBuildNode(TaskNodeKey<R, I> nodeKey) {
BuildableTaskNode<R, I> newNode = new BuildableTaskNode<>(nodeKey);
BuildableTaskNode<?, ?> prev = nodes.putIfAbsent(nodeKey, newNode);
if (prev != null) {
@SuppressWarnings("unchecked")
BuildableTaskNode<R, I> result = (BuildableTaskNode<R, I>)prev;
assert result.getKey().equals(nodeKey);
return result;
}
buildChildren(graphBuildCancel.getToken(), newNode);
return newNode;
}
private void buildChildren(CancellationToken cancelToken, BuildableTaskNode<?, ?> newNode) {
TaskNodeKey<?, ?> key = newNode.getKey();
incOutstandingBuilds();
properties.getGraphBuilderExecutor().execute(cancelToken, (CancellationToken taskCancelToken) -> {
Set<TaskNodeKey<?, ?>> childrenKeys = newNode.buildChildren(taskCancelToken, this);
taskGraphLock.lock();
try {
taskGraphBuilder.addNodeWithChildren(key, childrenKeys);
} finally {
taskGraphLock.unlock();
}
}, (boolean canceled, Throwable error) -> {
// We intentionally do not decrease the oustandingBuilds to prevent
// success notification.
if (canceled) {
onCancel();
return;
}
if (isError(canceled, error)) {
onError(key, error);
return;
}
decOutstandingBuilds();
});
}
private void incOutstandingBuilds() {
outstandingBuilds.incrementAndGet();
}
private void decOutstandingBuilds() {
int outstandingBuildCount = outstandingBuilds.decrementAndGet();
if (outstandingBuildCount == 0) {
onSuccess();
}
}
private <R, I> FactoryDef<R, I> getFactoryDef(TaskFactoryKey<R, I> key) {
@SuppressWarnings("unchecked")
FactoryDef<R, I> result = (FactoryDef<R, I>)factoryDefs.get(key);
assert result == null || result.getDefKey().equals(key);
return result;
}
private void onError(TaskNodeKey<?, ?> nodeKey, Throwable error) {
try {
try {
graphBuildCancel.getController().cancel();
properties.getNodeCreateErrorHandler().onError(nodeKey, error);
} finally {
graphBuildResult.completeExceptionally(error);
}
} catch (Throwable subError) {
if (subError instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
subError.addSuppressed(error);
LOGGER.log(Level.SEVERE, "Error while handling error of a task node: " + nodeKey, subError);
}
}
private void onCancel() {
try {
// TODO: Do not save the callstack once OperationCanceledException allows us.
graphBuildResult.completeExceptionally(new OperationCanceledException());
} catch (Throwable ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LOGGER.log(Level.SEVERE, "Error while handling cancellation.", ex);
}
}
private void onSuccess() {
try {
// No synchronization is necessary because we already know that we have built the graph,
// so no more node will be added.
DependencyDag<TaskNodeKey<?, ?>> graph = new DependencyDag<>(taskGraphBuilder.build());
TaskGraphExecutor executor = executorFactory.createExecutor(graph, getBuiltNodes());
graphBuildResult.complete(executor);
} catch (Throwable ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LOGGER.log(Level.SEVERE, "Error while attempting to notify graph built handler.", ex);
graphBuildResult.completeExceptionally(ex);
}
}
private Iterable<TaskNode<?, ?>> getBuiltNodes() {
List<TaskNode<?, ?>> result = new ArrayList<>(nodes.size());
nodes.values().forEach((buildableNode) -> {
result.add(buildableNode.getBuiltNode());
});
return result;
}
}
private static final class FactoryDef<R, I> {
private final TaskFactoryKey<R, I> defKey;
private final LazyFactoryConfigurer groupConfigurer;
private final TaskFactorySetup<R, I> setup;
public FactoryDef(
TaskFactoryKey<R, I> defKey,
LazyFactoryConfigurer groupConfigurer,
TaskFactorySetup<R, I> setup) {
this.defKey = defKey;
this.groupConfigurer = groupConfigurer;
this.setup = setup;
}
public NodeTaskRef<R> createTaskNode(
CancellationToken cancelToken,
I factoryArg,
TaskInputBinder inputs) throws Exception {
TaskNodeProperties defaults = getProperties().getDefaultNodeProperties();
TaskNodeCreateArgs<I> createArgs = new TaskNodeCreateArgs<>(factoryArg, defaults, inputs);
CancelableFunction<R> nodeTask = createFactory().createTaskNode(cancelToken, createArgs);
return new NodeTaskRef<>(createArgs.properties().build(), nodeTask);
}
public TaskFactory<R, I> createFactory() throws Exception {
return setup.setup(getProperties());
}
public TaskFactoryKey<R, I> getDefKey() {
return defKey;
}
public TaskFactoryProperties getProperties() {
return groupConfigurer.getProperties();
}
}
private static final class LazyFactoryConfigurer {
private final TaskFactoryProperties defaults;
private final TaskFactoryGroupConfigurer groupConfigurer;
private final AtomicReference<TaskFactoryProperties> propertiesRef;
public LazyFactoryConfigurer(TaskFactoryProperties defaults, TaskFactoryGroupConfigurer groupConfigurer) {
this.defaults = defaults;
this.groupConfigurer = groupConfigurer;
this.propertiesRef = new AtomicReference<>(null);
}
public TaskFactoryProperties getProperties() {
TaskFactoryProperties result = propertiesRef.get();
if (result == null) {
TaskFactoryProperties.Builder resultBuilder = new TaskFactoryProperties.Builder(defaults);
groupConfigurer.setup(resultBuilder);
result = resultBuilder.build();
if (!propertiesRef.compareAndSet(null, result)) {
result = propertiesRef.get();
}
}
return result;
}
}
private static final class BuildableTaskNode<R, I> {
private final TaskNodeKey<R, I> key;
private final CompletableFuture<R> taskFuture;
private TaskNode<R, I> builtNode;
public BuildableTaskNode(TaskNodeKey<R, I> key) {
this.key = key;
this.taskFuture = new CompletableFuture<>();
}
public TaskNodeKey<R, I> getKey() {
return key;
}
public CompletableFuture<R> getTaskFuture() {
return taskFuture;
}
public Set<TaskNodeKey<?, ?>> buildChildren(
CancellationToken cancelToken,
TaskGraphBuilderImpl nodeBuilder) throws Exception {
ExceptionHelper.checkNotNullArgument(cancelToken, "cancelToken");
ExceptionHelper.checkNotNullArgument(nodeBuilder, "nodeBuilder");
TaskInputBinderImpl inputBinder = new TaskInputBinderImpl(cancelToken, nodeBuilder);
NodeTaskRef<R> nodeTask = nodeBuilder.createNode(cancelToken, key, inputBinder);
if (nodeTask == null) {
throw new NullPointerException("TaskNodeBuilder.createNode returned null for key " + key);
}
builtNode = new TaskNode<>(key, nodeTask, taskFuture);
return inputBinder.closeAndGetInputs();
}
public TaskNode<R, I> getBuiltNode() {
assert builtNode != null;
return builtNode;
}
}
private static final class TaskInputBinderImpl implements TaskInputBinder {
private final TaskGraphBuilderImpl nodeBuilder;
private Set<TaskNodeKey<?, ?>> inputKeys;
public TaskInputBinderImpl(CancellationToken cancelToken, TaskGraphBuilderImpl nodeBuilder) {
this.nodeBuilder = nodeBuilder;
this.inputKeys = new HashSet<>();
}
@Override
public <I, A> TaskInputRef<I> bindInput(TaskNodeKey<I, A> defKey) {
Set<TaskNodeKey<?, ?>> currentInputKeys = inputKeys;
if (currentInputKeys == null) {
throw new IllegalStateException("May only be called from the associated task node factory.");
}
BuildableTaskNode<I, A> child = nodeBuilder.addAndBuildNode(defKey);
inputKeys.add(child.getKey());
AtomicReference<CompletableFuture<I>> resultRef = new AtomicReference<>(child.getTaskFuture());
return () -> {
CompletableFuture<I> nodeFuture = resultRef.getAndSet(null);
if (nodeFuture == null) {
throw new IllegalStateException("Input already consumed for key: " + defKey);
}
return TaskNode.getExpectedResultNow(defKey, nodeFuture);
};
}
public Set<TaskNodeKey<?, ?>> closeAndGetInputs() {
Set<TaskNodeKey<?, ?>> result = inputKeys;
inputKeys = null;
return result;
}
}
}
|
package com.pcache.DO.timeseries;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import com.pcache.exceptions.PCacheException;
import com.pcache.utils.Commons;
/**
* The central class for storing timeseries
*/
public class VariableTimeseries {
/**
* The main treemap to represent the timeseries.
* A treemap is favourable here because of the inbuilt ordering that comes
* along with it. This allows the points that are inserted later on to
* find the right place. Also treemaps have a neat "submap" feature that
* allows to get a subset of a map
*/
private Map<Long, Object> _timeseries;
/**
* Get the size of the timeseries
* @return the size of the timeseries
*/
public int size() {
return this._timeseries.size();
}
/**
* Check if a given timestamp exists within the series
* @param timestamp the timestamp to check for
* @return true/false based on its existance
*/
public boolean contains(String timestamp) {
// Convert the timestamp to a UNIX time representation,
// getting the no. of miliseconds elapsed since EPOC
long milisSinceEpoc = Commons.ISO8601toMilis(timestamp);
return this._timeseries.containsKey(milisSinceEpoc);
}
/**
* A core procedure. This isn't called from the outside.
* Add or Update points inside the timeseries. The nature of the TreeMap
* allows us to do both of these things in the same call since the .put()
* function will replace an existsing value if it exists
* @param timestamps the set of timestamps to add/update
* @param dataPoints the associated set of data to the timestamps.
* Note: there should be a one to one correlation between the
* timestamps and the data points
* @throws PCacheException thrown if there is no one to one correlation
* between the timestamps and the data points
*/
private void addOrUpdatePoints(ArrayList<String> timestamps,
ArrayList<Object> dataPoints) throws PCacheException{
// Go through all the timestamps
for (int i=0; i<timestamps.size(); i++) {
// Pick up the timestamp and the data point
String timestampISO8601 = timestamps.get(i);
Object dataPoint = dataPoints.get(i);
// Convert the timestamp to a UNIX time representation,
// getting the no. of miliseconds elapsed since EPOC
long milisSinceEpoc = Commons.ISO8601toMilis(timestampISO8601);
// Add or update the timestamp, datapoint
// Put does updates also. so 2 birds, one stone!
_timeseries.put(milisSinceEpoc, dataPoint);
}
}
/**
* Add points to the timeseries
* @param timestamps the set of timestamps to add
* @param dataPoints the associated set of data points to add
* @throws PCacheException thrown if timeseries isn't associated to the
* datapoints or if the points already exist in the timeseries
*/
public void addPoints(ArrayList<String> timestamps,
ArrayList<Object> dataPoints) throws PCacheException {
// Sanity checks
exceptIfLengthUnequal(timestamps, dataPoints);
exceptIfPointsExist(timestamps);
// Call the core procedure to add points into the timeseries
addOrUpdatePoints(timestamps, dataPoints);
}
/**
* Update points in the timeseries
* @param timestamps the set of timestamps to update
* @param dataPoints the associated set of data points to update
* @throws PCacheException thrown if timeseries isn't associated to the
* datapoints or if the points don't exist in the timeseries
*/
public void updatePoints(ArrayList<String> timestamps,
ArrayList<Object> dataPoints) throws PCacheException {
// Sanity checks
exceptIfLengthUnequal(timestamps, dataPoints);
exceptIfNoPointsExist(timestamps);
// Call the core procedure to update points in the timeseries
addOrUpdatePoints(timestamps, dataPoints);
}
/**
* Remove a set of points from the timeseries
* @param timestamps the set of timestamps to remove
* @throws PCacheException thrown if one or more points specified to be
* deleted, doesn't exist
*/
public void removePoints(ArrayList<String> timestamps)
throws PCacheException {
// Sanity Checks
exceptIfNoPointsExist(timestamps);
List<Long> timestampsSinceEpoc = convertToUnixTimeMiliseconds(timestamps);
for (long timestamp : timestampsSinceEpoc) {
this._timeseries.remove(timestamp);
}
}
/**
* Get the set of points between 2 given timeseries'
* @param timestampFrom the ISO8601 timestamp representing the from
* @param timestampTo the ISO8601 timestamp representing the to
* @return a map of the timeseries - data representation for the given
* range
*/
public Map<Long, Object> getRangeBetween(String timestampFrom,
String timestampTo) {
// Convert from timestamp to miliseconds since EPOC
long milisSinceEpocFrom = Commons.ISO8601toMilis(timestampFrom);
// Convert from timestamp to miliseconds since EPOC
long milisSinceEpocTo = Commons.ISO8601toMilis(timestampTo);
// Return a map
return ((TreeMap<Long, Object>) this._timeseries)
.subMap(milisSinceEpocFrom, true, milisSinceEpocTo, true);
}
/**
* Get the set of points from a given timestamp till the last one
* @param timestampFrom the ISO8601 timestamp representing the from
* @return a map of the timeseries - data representation for the given
* range
*/
public Map<Long, Object> getRangeFrom(String timestampFrom) {
// Convert from timestamp to miliseconds since EPOC
long milisSinceEpocFrom = Commons.ISO8601toMilis(timestampFrom);
// Get the last key in the series of timestamps
long lastKey = ((TreeMap<Long, Object>) this._timeseries).lastKey();
// Return a map
return ((TreeMap<Long, Object>) this._timeseries)
.subMap(milisSinceEpocFrom, true, lastKey, true);
}
/**
* Get the set of points from the first one till a given timestamp
* @param timestampFrom the ISO8601 timestamp representing the from
* @return a map of the timeseries - data representation for the given
* range
*/
public Map<Long, Object> getRangeTo(String timestampTo) {
// Convert from timestamp to miliseconds since EPOC
long milisSinceEpocTo = Commons.ISO8601toMilis(timestampTo);
// Get the first key in the series of timestamps
long firstKey = ((TreeMap<Long, Object>) this._timeseries).firstKey();
// Return a map
return ((TreeMap<Long, Object>) this._timeseries)
.subMap(firstKey, true, milisSinceEpocTo, true);
}
/**
* Get the entire timeseries
* @return the entire timeseries map
*/
public Map<Long, Object> getAll() {
return this._timeseries;
}
/**
* Constructor. Initialize a time series.
* @param timestamps an array of ISO8601 timestamps. The timestamps are to
* be in ISO8601 format with miliseconds.
* i.e. YYYY-MM-DDTHH:MM:SS.SSS+Z (2014-03-30T20:13:00.000+05:30)
* @param dataPoints the data points associated with the timestamps. They
* SHOULD have a one to one correlation.
* @throws PCacheException thrown if the no. of timestamps do not match
* the no. of data points
*/
public VariableTimeseries (ArrayList<String> timestamps,
ArrayList<Object> dataPoints) throws PCacheException {
// Declare a new tree map
_timeseries = new TreeMap<Long, Object>();
addOrUpdatePoints(timestamps, dataPoints);
}
/**
* Check if the length of the timeseries is not equal to the length of the
* data points that it is associated with
* @param timestamps the set of timestamps
* @param dataPoints the associated set of data points
* @throws PCacheException thrown if the length of both are unequal
*/
private void exceptIfLengthUnequal(ArrayList<String> timestamps,
ArrayList<Object> dataPoints) throws PCacheException {
if (timestamps.size() != dataPoints.size()) {
throw new PCacheException("Sizes don't match. The number of data " +
"points should equal the number of timestamps");
}
}
/**
* Convert the given timestamps to UNIX time representation (in miliseconds)
* @param timestamps the set of timestamps to convert
* @return a list of timestamps in miliseconds since EPOC format
*/
private List<Long> convertToUnixTimeMiliseconds(
ArrayList<String> timestamps) {
ArrayList<Long> timestampsSinceEpoc = new ArrayList<>();
// Go through all the timestamps
for (int i=0; i<timestamps.size(); i++) {
// Pick up the timestamp
String timestampISO8601 = timestamps.get(i);
// Convert the timestamp to a UNIX time representation,
// getting the no. of miliseconds elapsed since EPOC
long milisSinceEpoc = Commons.ISO8601toMilis(timestampISO8601);
timestampsSinceEpoc.add(milisSinceEpoc);
}
return timestampsSinceEpoc;
}
/**
* Check if the set of points already exist in the cache
* @param timestamps the set of timestamps to check
* @throws PCacheException thrown if the set of points already exist in the
* cache
*/
private void exceptIfPointsExist(ArrayList<String> timestamps)
throws PCacheException {
// Get the EPOC representations
List<Long> timestampsInMilis =
convertToUnixTimeMiliseconds(timestamps);
// Go through the timestamps
for (long timestamp : timestampsInMilis) {
// If timeseries already contains it, except
if (this._timeseries.containsKey(timestamp)) {
throw new PCacheException("Some point(s) already exist in the "
+ "timeseries");
}
}
}
/**
* Check if the set of points don't exist in the cache
* @param timestamps the set of timestamps to check
* @throws PCacheException thrown if the set of points don't exist in the
* cache
*/
private void exceptIfNoPointsExist(ArrayList<String> timestamps)
throws PCacheException {
// Get the EPOC representations
List<Long> timestampsInMilis =
convertToUnixTimeMiliseconds(timestamps);
// Go through the timestamps
for (long timestamp : timestampsInMilis) {
// If the timeseries doesn't contain it, except
if (!this._timeseries.containsKey(timestamp)) {
throw new PCacheException("Some point(s) don't exist in the "
+ "timeseries");
}
}
}
}
|
package org.junit.jupiter.engine;
import java.util.List;
import org.junit.jupiter.engine.descriptor.ClassTestDescriptor;
import org.junit.jupiter.engine.descriptor.NestedClassTestDescriptor;
import org.junit.platform.engine.EngineDiscoveryRequest;
import org.junit.platform.engine.FilterResult;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.discovery.ClassNameFilter;
import org.junit.platform.engine.discovery.PackageNameFilter;
/**
* Class for applying all {@link org.junit.platform.engine.DiscoveryFilter}s to all
* children of a {@link TestDescriptor}.
*
* @since 5.0
*/
class DiscoveryFilterApplier {
/**
* Apply all filters. Currently only {@link ClassNameFilter} is considered.
*/
void applyAllFilters(EngineDiscoveryRequest discoveryRequest, TestDescriptor engineDescriptor) {
applyClassNameFilters(discoveryRequest.getFiltersByType(ClassNameFilter.class), engineDescriptor);
applyPackageNameFilters(discoveryRequest.getFiltersByType(PackageNameFilter.class), engineDescriptor);
}
private void applyPackageNameFilters(List<PackageNameFilter> packageNameFilters, TestDescriptor engineDescriptor) {
if (packageNameFilters.isEmpty()) {
return;
}
TestDescriptor.Visitor filteringVisitor = descriptor -> {
if (descriptor instanceof ClassTestDescriptor) {
if (!includePackage((ClassTestDescriptor) descriptor, packageNameFilters)) {
descriptor.removeFromHierarchy();
}
}
};
engineDescriptor.accept(filteringVisitor);
}
private boolean includePackage(ClassTestDescriptor classTestDescriptor,
List<PackageNameFilter> packageNameFilters) {
// Nested Tests are never filtered out
if (classTestDescriptor instanceof NestedClassTestDescriptor) {
return true;
}
Class<?> testClass = classTestDescriptor.getTestClass();
// @formatter:off
return (packageNameFilters.stream()
.map(filter -> filter.apply(testClass.getPackage().getName()))
.noneMatch(FilterResult::excluded));
// @formatter:on
}
private void applyClassNameFilters(List<ClassNameFilter> classNameFilters, TestDescriptor engineDescriptor) {
if (classNameFilters.isEmpty()) {
return;
}
TestDescriptor.Visitor filteringVisitor = descriptor -> {
if (descriptor instanceof ClassTestDescriptor
&& !includeClass((ClassTestDescriptor) descriptor, classNameFilters)) {
descriptor.removeFromHierarchy();
}
};
engineDescriptor.accept(filteringVisitor);
}
private boolean includeClass(ClassTestDescriptor classTestDescriptor, List<ClassNameFilter> classNameFilters) {
// Nested Tests are never filtered out
if (classTestDescriptor instanceof NestedClassTestDescriptor) {
return true;
}
Class<?> testClass = classTestDescriptor.getTestClass();
// @formatter:off
return classNameFilters.stream()
.map(filter -> filter.apply(testClass.getName()))
.noneMatch(FilterResult::excluded);
// @formatter:on
}
}
|
package com.pmc1.system;
import com.pmc1.entity.Floor;
public class FirstRequestProcessedSystem extends BaseElevatorSystem {
public void floorRequest(boolean goingUp) {
// first find an elevator that should pick up this request
// set that elevator's floorsOfInterest to be true for that specific floor
}
public void elevatorRequest(Floor floor) {
// process request in the order of request given because of naive implementation
}
}
|
package org.sakaiproject.component.app.messageforums.ui;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.LockMode;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.Area;
import org.sakaiproject.api.app.messageforums.AreaManager;
import org.sakaiproject.api.app.messageforums.Attachment;
import org.sakaiproject.api.app.messageforums.Message;
import org.sakaiproject.api.app.messageforums.MessageForumsForumManager;
import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager;
import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager;
import org.sakaiproject.api.app.messageforums.PrivateForum;
import org.sakaiproject.api.app.messageforums.PrivateMessage;
import org.sakaiproject.api.app.messageforums.PrivateMessageRecipient;
import org.sakaiproject.api.app.messageforums.PrivateTopic;
import org.sakaiproject.api.app.messageforums.Topic;
import org.sakaiproject.api.app.messageforums.UniqueArrayList;
import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager;
import org.sakaiproject.api.kernel.id.IdManager;
import org.sakaiproject.api.kernel.session.SessionManager;
import org.sakaiproject.api.kernel.tool.cover.ToolManager;
import org.sakaiproject.component.app.messageforums.TestUtil;
import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageImpl;
import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageRecipientImpl;
import org.sakaiproject.service.framework.email.EmailService;
import org.sakaiproject.service.legacy.content.ContentResource;
import org.sakaiproject.service.legacy.content.cover.ContentHostingService;
import org.sakaiproject.service.legacy.security.cover.SecurityService;
import org.sakaiproject.service.legacy.user.User;
import org.sakaiproject.service.legacy.user.cover.UserDirectoryService;
import org.springframework.orm.hibernate.HibernateCallback;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;
public class PrivateMessageManagerImpl extends HibernateDaoSupport implements
PrivateMessageManager
{
private static final Log LOG = LogFactory
.getLog(PrivateMessageManagerImpl.class);
private static final String QUERY_COUNT = "findPvtMsgCntByTopicTypeUser";
private static final String QUERY_COUNT_BY_UNREAD = "findUnreadPvtMsgCntByTopicTypeUser";
private static final String QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT = "findPrvtMsgsByUserTypeContext";
private static final String QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS = "findPrivateMessageByIdWithRecipients";
private AreaManager areaManager;
private MessageForumsMessageManager messageManager;
private MessageForumsForumManager forumManager;
private MessageForumsTypeManager typeManager;
private IdManager idManager;
private SessionManager sessionManager;
private EmailService emailService;
public void init()
{
;
}
public boolean getPrivateAreaEnabled()
{
if (LOG.isDebugEnabled())
{
LOG.debug("getPrivateAreaEnabled()");
}
return areaManager.isPrivateAreaEnabled();
}
public void setPrivateAreaEnabled(boolean value)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrivateAreaEnabled(value: " + value + ")");
}
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#isPrivateAreaEnabled()
*/
public boolean isPrivateAreaEnabled()
{
return areaManager.isPrivateAreaEnabled();
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#getPrivateMessageArea()
*/
public Area getPrivateMessageArea()
{
return areaManager.getPrivateArea();
}
public void savePrivateMessageArea(Area area)
{
areaManager.saveArea(area);
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#initializePrivateMessageArea(org.sakaiproject.api.app.messageforums.Area)
*/
public PrivateForum initializePrivateMessageArea(Area area)
{
String userId = getCurrentUser();
getHibernateTemplate().lock(area, LockMode.NONE);
PrivateForum pf;
/** create default user forum/topics if none exist */
if ((pf = forumManager.getPrivateForumByOwner(getCurrentUser())) == null)
{
/** initialize collections */
//getHibernateTemplate().initialize(area.getPrivateForumsSet());
pf = forumManager.createPrivateForum("Private Forum");
//area.addPrivateForum(pf);
//pf.setArea(area);
//areaManager.saveArea(area);
PrivateTopic receivedTopic = forumManager.createPrivateForumTopic("Received", true,
userId, pf.getId());
PrivateTopic sentTopic = forumManager.createPrivateForumTopic("Sent", true,
userId, pf.getId());
PrivateTopic deletedTopic = forumManager.createPrivateForumTopic("Deleted", true,
userId, pf.getId());
PrivateTopic draftTopic = forumManager.createPrivateForumTopic("Drafts", true,
userId, pf.getId());
/** save individual topics - required to add to forum's topic set */
forumManager.savePrivateForumTopic(receivedTopic);
forumManager.savePrivateForumTopic(sentTopic);
forumManager.savePrivateForumTopic(deletedTopic);
forumManager.savePrivateForumTopic(draftTopic);
pf.addTopic(receivedTopic);
pf.addTopic(sentTopic);
pf.addTopic(deletedTopic);
pf.addTopic(draftTopic);
forumManager.savePrivateForum(pf);
}
else{
getHibernateTemplate().initialize(pf.getTopicsSet());
}
return pf;
}
public PrivateForum initializationHelper(PrivateForum forum){
/** reget to load topic foreign keys */
PrivateForum pf = forumManager.getPrivateForumByOwner(getCurrentUser());
getHibernateTemplate().initialize(pf.getTopicsSet());
return pf;
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#savePrivateMessage(org.sakaiproject.api.app.messageforums.Message)
*/
public void savePrivateMessage(Message message)
{
messageManager.saveMessage(message);
}
public Message getMessageById(Long id)
{
return messageManager.getMessageById(id);
}
//Attachment
public Attachment createPvtMsgAttachment(String attachId, String name)
{
try
{
Attachment attach = messageManager.createAttachment();
attach.setAttachmentId(attachId);
attach.setAttachmentName(name);
ContentResource cr = ContentHostingService.getResource(attachId);
attach.setAttachmentSize((new Integer(cr.getContentLength())).toString());
attach.setCreatedBy(cr.getProperties().getProperty(
cr.getProperties().getNamePropCreator()));
attach.setModifiedBy(cr.getProperties().getProperty(
cr.getProperties().getNamePropModifiedBy()));
attach.setAttachmentType(cr.getContentType());
String tempString = cr.getUrl();
String newString = new String();
char[] oneChar = new char[1];
for (int i = 0; i < tempString.length(); i++)
{
if (tempString.charAt(i) != ' ')
{
oneChar[0] = tempString.charAt(i);
String concatString = new String(oneChar);
newString = newString.concat(concatString);
}
else
{
newString = newString.concat("%20");
}
}
//tempString.replaceAll(" ", "%20");
attach.setAttachmentUrl(newString);
return attach;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
// Himansu: I am not quite sure this is what you want... let me know.
// Before saving a message, we need to add all the attachmnets to a perticular message
public void addAttachToPvtMsg(PrivateMessage pvtMsgData,
Attachment pvtMsgAttach)
{
pvtMsgData.addAttachment(pvtMsgAttach);
}
// Required for editing multiple attachments to a message.
// When you reply to a message, you do have option to edit attachments to a message
public void removePvtMsgAttachment(Attachment o)
{
o.getMessage().removeAttachment(o);
}
public Attachment getPvtMsgAttachment(Long pvtMsgAttachId)
{
return messageManager.getAttachmentById(pvtMsgAttachId);
}
public int getTotalNoMessages(Topic topic)
{
return messageManager.findMessageCountByTopicId(topic.getId());
}
public int getUnreadNoMessages(Topic topic)
{
return messageManager.findUnreadMessageCountByTopicId(topic.getId());
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#saveAreaAndForumSettings(org.sakaiproject.api.app.messageforums.Area, org.sakaiproject.api.app.messageforums.PrivateForum)
*/
public void saveAreaAndForumSettings(Area area, PrivateForum forum)
{
/** method calls placed in this function to participate in same transaction */
saveForumSettings(forum);
/** need to evict forum b/c area saves fk on forum (which places two objects w/same id in session */
//getHibernateTemplate().evict(forum);
if (isInstructor()){
savePrivateMessageArea(area);
}
}
public void saveForumSettings(PrivateForum forum)
{
if (LOG.isDebugEnabled())
{
LOG.debug("saveForumSettings(forum: " + forum + ")");
}
if (forum == null)
{
throw new IllegalArgumentException("Null Argument");
}
forumManager.savePrivateForum(forum);
}
/**
* Topic Folder Setting
*/
public boolean isMutableTopicFolder(String parentTopicId)
{
return false;
}
public String createTopicFolderInForum(String parentForumId, String userId,
String name)
{
return null;
}
public String createTopicFolderInTopic(String parentTopicId, String userId,
String name)
{
return null;
}
public String renameTopicFolder(String parentTopicId, String userId,
String newName)
{
return null;
}
public void deleteTopicFolder(String topicId)
{
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#createPrivateMessage(java.lang.String)
*/
public PrivateMessage createPrivateMessage(String typeUuid)
{
PrivateMessage message = new PrivateMessageImpl();
message.setUuid(idManager.createUuid());
message.setTypeUuid(typeUuid);
message.setCreated(new Date());
message.setCreatedBy(getCurrentUser());
LOG.info("message " + message.getUuid() + " created successfully");
return message;
}
public boolean hasNextMessage(PrivateMessage message)
{
// TODO: Needs optimized
boolean next = false;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (next)
{
return true;
}
if (m.getId().equals(message.getId()))
{
next = true;
}
}
}
// if we get here, there is no next message
return false;
}
public boolean hasPreviousMessage(PrivateMessage message)
{
// TODO: Needs optimized
PrivateMessage prev = null;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (m.getId().equals(message.getId()))
{
// need to check null because we might be on the first message
// which means there is no previous one
return prev != null;
}
prev = (PrivateMessage) m;
}
}
// if we get here, there is no previous message
return false;
}
public PrivateMessage getNextMessage(PrivateMessage message)
{
// TODO: Needs optimized
boolean next = false;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (next)
{
return (PrivateMessage) m;
}
if (m.getId().equals(message.getId()))
{
next = true;
}
}
}
// if we get here, there is no next message
return null;
}
public PrivateMessage getPreviousMessage(PrivateMessage message)
{
// TODO: Needs optimized
PrivateMessage prev = null;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (m.getId().equals(message.getId()))
{
return prev;
}
prev = (PrivateMessage) m;
}
}
// if we get here, there is no previous message
return null;
}
public List getMessagesByTopic(String userId, Long topicId)
{
// TODO Auto-generated method stub
return null;
}
public List getReceivedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getReceivedPrivateMessageType(),
orderField, order);
}
public List getSentMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getSentPrivateMessageType(),
orderField, order);
}
public List getDeletedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getDeletedPrivateMessageType(),
orderField, order);
}
public List getDraftedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getDraftPrivateMessageType(),
orderField, order);
}
public PrivateMessage initMessageWithAttachmentsAndRecipients(PrivateMessage msg){
PrivateMessage pmReturn = (PrivateMessage) messageManager.getMessageByIdWithAttachments(msg.getId());
getHibernateTemplate().initialize(pmReturn.getRecipients());
return pmReturn;
}
/**
* helper method to get messages by type
* @param typeUuid
* @return message list
*/
public List getMessagesByType(final String typeUuid, final String orderField,
final String order)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getMessagesByType(typeUuid:" + typeUuid + ", orderField: "
+ orderField + ", order:" + order + ")");
}
// HibernateCallback hcb = new HibernateCallback() {
// public Object doInHibernate(Session session) throws HibernateException, SQLException {
// Criteria messageCriteria = session.createCriteria(PrivateMessageImpl.class);
// Criteria recipientCriteria = messageCriteria.createCriteria("recipients");
// Conjunction conjunction = Expression.conjunction();
// conjunction.add(Expression.eq("userId", getCurrentUser()));
// conjunction.add(Expression.eq("typeUuid", typeUuid));
// recipientCriteria.add(conjunction);
// if ("asc".equalsIgnoreCase(order)){
// messageCriteria.addOrder(Order.asc(orderField));
// else if ("desc".equalsIgnoreCase(order)){
// messageCriteria.addOrder(Order.desc(orderField));
// else{
// LOG.debug("getMessagesByType failed with (typeUuid:" + typeUuid + ", orderField: " + orderField +
// ", order:" + order + ")");
// //todo: parameterize fetch mode
// messageCriteria.setFetchMode("recipients", FetchMode.EAGER);
// messageCriteria.setFetchMode("attachments", FetchMode.EAGER);
// return messageCriteria.list();
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
Query qOrdered = session.createQuery(q.getQueryString() + " order by "
+ orderField + " " + order);
qOrdered.setParameter("userId", getCurrentUser(), Hibernate.STRING);
qOrdered.setParameter("typeUuid", typeUuid, Hibernate.STRING);
qOrdered.setParameter("contextId", getContextId(), Hibernate.STRING);
return qOrdered.list();
}
};
return (List) getHibernateTemplate().execute(hcb);
// fix to return count of attachments collection
// for (Iterator i = list.iterator(); i.hasNext();)
// PrivateMessage element = (PrivateMessage) i.next();
// getHibernateTemplate().initialize(element.getAttachmentsSet());
// return list;
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findMessageCount(java.lang.Long, java.lang.String)
*/
public int findMessageCount(final Long topicId, final String typeUuid)
{
String userId = getCurrentUser();
if (LOG.isDebugEnabled())
{
LOG.debug("findMessageCount executing with topicId: " + topicId
+ ", userId: " + userId + ", typeUuid: " + typeUuid);
}
if (topicId == null || userId == null || typeUuid == null)
{
LOG.error("findMessageCount failed with topicId: " + topicId
+ ", uerId: " + userId + ", typeUuid: " + typeUuid);
throw new IllegalArgumentException("Null Argument");
}
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_COUNT);
q.setParameter("typeUuid", typeUuid, Hibernate.STRING);
q.setParameter("contextId", getContextId(), Hibernate.STRING);
q.setParameter("userId", getCurrentUser(), Hibernate.STRING);
return q.uniqueResult();
}
};
return ((Integer) getHibernateTemplate().execute(hcb)).intValue();
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findUnreadMessageCount(java.lang.Long, java.lang.String)
*/
public int findUnreadMessageCount(final Long topicId, final String typeUuid)
{
String userId = getCurrentUser();
if (topicId == null || userId == null || typeUuid == null)
{
LOG.error("findUnreadMessageCount failed with topicId: " + topicId
+ ", userId: " + userId + ", typeUuid: " + typeUuid);
throw new IllegalArgumentException("Null Argument");
}
LOG.debug("findUnreadMessageCount executing with topicId: " + topicId
+ ", userId: " + userId + ", typeUuid: " + typeUuid);
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_COUNT_BY_UNREAD);
q.setParameter("typeUuid", typeUuid, Hibernate.STRING);
q.setParameter("contextId", getContextId(), Hibernate.STRING);
q.setParameter("userId", getCurrentUser(), Hibernate.STRING);
return q.uniqueResult();
}
};
return ((Integer) getHibernateTemplate().execute(hcb)).intValue();
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#deletePrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.lang.String)
*/
public void deletePrivateMessage(PrivateMessage message, String typeUuid)
{
String userId = getCurrentUser();
if (LOG.isDebugEnabled())
{
LOG.debug("deletePrivateMessage(message:" + message + ", typeUuid:"
+ typeUuid + ")");
}
/** fetch recipients for message */
PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
/**
* create PrivateMessageRecipient to search
*/
PrivateMessageRecipient pmrReadSearch = new PrivateMessageRecipientImpl(
userId, typeUuid, getContextId(), Boolean.TRUE);
PrivateMessageRecipient pmrNonReadSearch = new PrivateMessageRecipientImpl(
userId, typeUuid, getContextId(), Boolean.FALSE);
int indexDelete = -1;
int indexRead = pvtMessage.getRecipients().indexOf(pmrReadSearch);
if (indexRead != -1)
{
indexDelete = indexRead;
}
else
{
int indexNonRead = pvtMessage.getRecipients().indexOf(pmrNonReadSearch);
if (indexNonRead != -1)
{
indexDelete = indexNonRead;
}
else
{
LOG
.error("deletePrivateMessage -- cannot find private message for user: "
+ userId + ", typeUuid: " + typeUuid);
}
}
if (indexDelete != -1)
{
PrivateMessageRecipient pmrReturned = (PrivateMessageRecipient) pvtMessage
.getRecipients().get(indexDelete);
if (pmrReturned != null)
{
/** check for existing deleted message from user */
PrivateMessageRecipient pmrDeletedSearch = new PrivateMessageRecipientImpl(
userId, typeManager.getDeletedPrivateMessageType(), getContextId(),
Boolean.TRUE);
int indexDeleted = pvtMessage.getRecipients().indexOf(pmrDeletedSearch);
if (indexDeleted == -1)
{
pmrReturned.setRead(Boolean.TRUE);
pmrReturned.setTypeUuid(typeManager.getDeletedPrivateMessageType());
}
else
{
pvtMessage.getRecipients().remove(indexDelete);
}
}
}
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#sendPrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.util.Set, boolean)
*/
public void sendPrivateMessage(PrivateMessage message, Set recipients, boolean asEmail)
{
if (LOG.isDebugEnabled())
{
LOG.debug("sendPrivateMessage(message: " + message + ", recipients: "
+ recipients + ")");
}
if (message == null || recipients == null)
{
throw new IllegalArgumentException("Null Argument");
}
if (recipients.size() == 0)
{
return;
}
List recipientList = new UniqueArrayList();
/** test for draft message */
if (message.getDraft().booleanValue())
{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
getCurrentUser(), typeManager.getDraftPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(receiver);
message.setRecipients(recipientList);
savePrivateMessage(message);
return;
}
for (Iterator i = recipients.iterator(); i.hasNext();)
{
User u = (User) i.next();
String userId = u.getId();
/** determine if recipient has forwarding enabled */
PrivateForum pf = forumManager.getPrivateForumByOwner(userId);
boolean forwardingEnabled = false;
if (pf != null && pf.getAutoForward().booleanValue()){
forwardingEnabled = true;
}
List additionalHeaders = new ArrayList(1);
additionalHeaders.add("Content-Type: text/html");
if (!asEmail && forwardingEnabled){
emailService.send(UserDirectoryService.getCurrentUser().getEmail(), pf.getAutoForwardEmail(), message.getTitle(),
message.getBody(), pf.getAutoForwardEmail(), null, additionalHeaders);
}
if (asEmail){
emailService.send(UserDirectoryService.getCurrentUser().getEmail(), u.getEmail(), message.getTitle(),
message.getBody(), u.getEmail(), null, additionalHeaders);
}
else{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
Boolean.FALSE);
recipientList.add(receiver);
}
}
/** add sender as a saved recipient */
PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(
getCurrentUser(), typeManager.getSentPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(sender);
message.setRecipients(recipientList);
savePrivateMessage(message);
/** enable if users are stored in message forums user table
Iterator i = recipients.iterator();
while (i.hasNext()){
String userId = (String) i.next();
//getForumUser will create user if forums user does not exist
message.addRecipient(userManager.getForumUser(userId.trim()));
}
**/
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#markMessageAsReadForUser(org.sakaiproject.api.app.messageforums.PrivateMessage)
*/
public void markMessageAsReadForUser(final PrivateMessage message)
{
if (LOG.isDebugEnabled())
{
LOG.debug("markMessageAsReadForUser(message: " + message + ")");
}
if (message == null)
{
throw new IllegalArgumentException("Null Argument");
}
final String userId = getCurrentUser();
/** fetch recipients for message */
PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
/** create PrivateMessageRecipientImpl to search for recipient to update */
PrivateMessageRecipientImpl searchRecipient = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
Boolean.FALSE);
List recipientList = pvtMessage.getRecipients();
if (recipientList == null || recipientList.size() == 0)
{
LOG.error("markMessageAsReadForUser(message: " + message
+ ") has empty recipient list");
throw new Error("markMessageAsReadForUser(message: " + message
+ ") has empty recipient list");
}
int recordIndex = pvtMessage.getRecipients().indexOf(searchRecipient);
if (recordIndex != -1)
{
((PrivateMessageRecipientImpl) recipientList.get(recordIndex))
.setRead(Boolean.TRUE);
}
}
private PrivateMessage getPrivateMessageWithRecipients(
final PrivateMessage message)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getPrivateMessageWithRecipients(message: " + message + ")");
}
if (message == null)
{
throw new IllegalArgumentException("Null Argument");
}
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS);
q.setParameter("id", message.getId(), Hibernate.LONG);
return q.uniqueResult();
}
};
PrivateMessage pvtMessage = (PrivateMessage) getHibernateTemplate()
.execute(hcb);
if (pvtMessage == null)
{
LOG.error("getPrivateMessageWithRecipients(message: " + message
+ ") could not find message");
throw new Error("getPrivateMessageWithRecipients(message: " + message
+ ") could not find message");
}
return pvtMessage;
}
private String getCurrentUser()
{
if (TestUtil.isRunningTests())
{
return "test-user";
}
return sessionManager.getCurrentSessionUserId();
}
public AreaManager getAreaManager()
{
return areaManager;
}
public void setAreaManager(AreaManager areaManager)
{
this.areaManager = areaManager;
}
public MessageForumsMessageManager getMessageManager()
{
return messageManager;
}
public void setMessageManager(MessageForumsMessageManager messageManager)
{
this.messageManager = messageManager;
}
public void setTypeManager(MessageForumsTypeManager typeManager)
{
this.typeManager = typeManager;
}
public void setSessionManager(SessionManager sessionManager)
{
this.sessionManager = sessionManager;
}
public void setIdManager(IdManager idManager)
{
this.idManager = idManager;
}
public void setForumManager(MessageForumsForumManager forumManager)
{
this.forumManager = forumManager;
}
public void setEmailService(EmailService emailService)
{
this.emailService = emailService;
}
public boolean isInstructor()
{
LOG.debug("isInstructor()");
return isInstructor(UserDirectoryService.getCurrentUser());
}
/**
* Check if the given user has site.upd access
*
* @param user
* @return
*/
private boolean isInstructor(User user)
{
if (LOG.isDebugEnabled())
{
LOG.debug("isInstructor(User " + user + ")");
}
if (user != null)
return SecurityService.unlock(user, "site.upd", getContextSiteId());
else
return false;
}
/**
* @return siteId
*/
private String getContextSiteId()
{
LOG.debug("getContextSiteId()");
return ("/site/" + ToolManager.getCurrentPlacement().getContext());
}
private String getContextId()
{
LOG.debug("getContextId()");
if (TestUtil.isRunningTests())
{
return "01001010";
}
else
{
return ToolManager.getCurrentPlacement().getContext();
}
}
}
|
package com.techjar.ledcm.hardware;
import com.techjar.ledcm.LEDCubeManager;
import com.techjar.ledcm.hardware.animation.Animation;
import com.techjar.ledcm.hardware.animation.AnimationSpectrumAnalyzer;
import com.techjar.ledcm.hardware.tcp.packet.Packet;
import com.techjar.ledcm.hardware.tcp.packet.PacketAudioData;
import com.techjar.ledcm.hardware.tcp.packet.PacketAudioInit;
import com.techjar.ledcm.util.BufferHelper;
import com.techjar.ledcm.util.MathHelper;
import com.techjar.ledcm.util.PrintStreamRelayer;
import com.techjar.ledcm.util.Timer;
import com.techjar.ledcm.util.logging.LogHelper;
import ddf.minim.AudioListener;
import ddf.minim.AudioPlayer;
import ddf.minim.Minim;
import ddf.minim.analysis.BeatDetect;
import ddf.minim.analysis.FFT;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.lwjgl.util.Color;
/**
*
* @author Techjar
*/
public class SpectrumAnalyzer {
private final int bufferSize = 2048;
private final int sampleRate = 48000;
private final Minim minim;
private FFT fft;
private BeatDetect beatDetect;
private int beatDetectMode = BeatDetect.FREQ_ENERGY;
private AudioPlayer player;
@Getter private String currentTrack = "";
@Getter private Map<String, Mixer> mixers = new LinkedHashMap<>();
@Getter private Mixer currentMixer;
@Getter private String currentMixerName;
@Getter @Setter private float mixerGain = 1;
private TargetDataLine dataLine;
private Thread inputThread;
private Timer audioInputRestartTimer = new Timer();
public SpectrumAnalyzer() {
super();
this.minim = new Minim(this);
//this.minim.debugOn();
for (Mixer.Info info : AudioSystem.getMixerInfo()) {
Mixer mixer = AudioSystem.getMixer(info);
for (Line.Info lineInfo : mixer.getTargetLineInfo()) {
if (lineInfo instanceof TargetDataLine.Info) {
mixers.put(info.getName(), mixer);
if (currentMixer == null || info.getName().equals(LEDCubeManager.getConfig().getString("sound.inputdevice"))) {
currentMixer = mixer;
currentMixerName = info.getName();
}
LogHelper.config("Input device: %s", info.getName());
break;
}
}
}
mixers = Collections.unmodifiableMap(mixers);
LEDCubeManager.getConfig().setProperty("sound.inputdevice", currentMixerName);
}
public String sketchPath(String fileName) {
return new File(fileName).getAbsolutePath();
}
@SneakyThrows(IOException.class)
public InputStream createInput(String fileName) {
return new FileInputStream(fileName);
}
public boolean isPlaying() {
if (player != null) return player.isPlaying();
return false;
}
public boolean playerExists() {
return player != null;
}
public void play() {
if (player != null) {
if (player.isPlaying()) {
player.rewind();
} else {
if (player.position() >= player.length() - 1) {
player.rewind();
}
player.play();
}
}
}
public void pause() {
if (player != null) player.pause();
}
public void stop() {
if (player != null) {
player.pause();
player.rewind();
}
}
public void close() {
if (player != null) {
player.close();
player = null;
}
}
public void setVolume(float volume) {
if (player != null) player.setGain(volume > 0 ? (float)(MathHelper.log(volume, 4) * 20) : -200);
}
public float getPosition() {
if (player != null) {
return (float)player.position() / (float)player.length();
}
return 0;
}
public int getPositionMillis() {
if (player != null) {
return player.position();
}
return 0;
}
public int getLengthMillis() {
if (player != null) {
return player.length();
}
return 0;
}
public void setPosition(float position) {
if (player != null) {
player.rewind();
player.skip(Math.round(player.length() * position));
}
}
public AudioFormat getAudioFormat() {
if (player != null) {
return player.getFormat();
}
return null;
}
public void setMixer(String name) {
Mixer mixer = mixers.get(name);
if (mixer != null) {
currentMixer = mixer;
currentMixerName = name;
if (dataLine != null) {
stopAudioInput();
while (dataLine != null);
startAudioInput();
}
LEDCubeManager.getConfig().setProperty("sound.inputdevice", currentMixerName);
}
}
public boolean isRunningAudioInput() {
return dataLine != null;
}
public void startAudioInput() {
if (player != null) {
player.close();
player = null;
currentTrack = "";
}
try {
TargetDataLine.Info lineInfo = (TargetDataLine.Info)currentMixer.getTargetLineInfo()[0];
AudioFormat supportedFormat = null;
for (AudioFormat fmt : lineInfo.getFormats()) {
if (fmt.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED) && fmt.getSampleSizeInBits() == 16 && fmt.getChannels() == 1) {
supportedFormat = fmt;
break;
}
}
if (supportedFormat == null) {
LogHelper.severe("Couldn't find desired AudioFormat!");
return;
}
final AudioFormat format = new AudioFormat(supportedFormat.getEncoding(), sampleRate, supportedFormat.getSampleSizeInBits(), supportedFormat.getChannels(), supportedFormat.getFrameSize(), sampleRate, false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!currentMixer.isLineSupported(info)) {
LogHelper.severe("Mixer doesn't support requested line!");
return;
}
dataLine = (TargetDataLine)currentMixer.getLine(info);
dataLine.open(format, bufferSize * 8);
dataLine.start();
fft = new FFT(bufferSize / 2, sampleRate);
beatDetect = new BeatDetect(bufferSize / 2, sampleRate);
beatDetect.detectMode(beatDetectMode);
final AudioListener listener = new AnalyzerAudioListener(fft, beatDetect);
inputThread = new Thread("Audio Input") {
@Override
public void run() {
audioInputRestartTimer.restart();
byte[] buffer = new byte[bufferSize];
float[] floats = new float[bufferSize / 2];
while (dataLine.isOpen()) {
dataLine.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferSize; i += 2) {
int val = (short)((buffer[i] & 0xFF) | ((buffer[i + 1] & 0xFF) << 8));
floats[i / 2] = MathHelper.clamp((val / 32768F) * mixerGain, -1, 1);
}
listener.samples(floats);
// Really dumb fix for weird latency build-up issue
if (audioInputRestartTimer.getMinutes() >= 30) {
audioInputRestartTimer.restart();
try {
dataLine.close();
dataLine.open(format, bufferSize * 8);
dataLine.start();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
LEDCubeManager.getInstance().getScreenMainControl().audioInputBtnBg.setBackgroundColor(new Color(255, 127, 0));
}
}
}
dataLine = null;
}
};
inputThread.start();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
}
}
public void stopAudioInput() {
if (dataLine != null) {
dataLine.close();
inputThread = null;
}
}
public void loadFile(File file) {
try {
File file2 = new File("resampled/" + file.getName().substring(0, file.getName().lastIndexOf('.')) + ".wav");
String path = file2.getAbsolutePath();
if (!file2.exists()) {
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(System.getProperty("user.dir")));
pb.redirectErrorStream(true);
pb.command("ffmpeg", "-i", file.getAbsolutePath(), "-af", "aresample=resampler=soxr", "-sample_fmt", "s16", "-ar", Integer.toString(sampleRate), file2.getAbsolutePath());
Process proc = pb.start();
LEDCubeManager.setConvertingAudio(true);
Thread psrThread = new PrintStreamRelayer(proc.getInputStream(), System.out);
psrThread.setDaemon(true); psrThread.start();
proc.waitFor();
LEDCubeManager.setConvertingAudio(false);
}
stopAudioInput();
LEDCubeManager.getInstance().getScreenMainControl().audioInputBtnBg.setBackgroundColor(new Color(255, 0, 0));
if (player != null) {
player.close();
}
AudioPlayer oldPlayer = player;
player = minim.loadFile(path);
LEDCubeManager.getLEDCube().getCommThread().getTcpServer().sendPacket(new PacketAudioInit(player.getFormat()));
String path2 = path.replaceAll("\\\\", "/");
currentTrack = path2.contains("/") ? path2.substring(path2.lastIndexOf('/') + 1) : path2;
currentTrack = currentTrack.substring(0, currentTrack.lastIndexOf('.'));
setVolume(LEDCubeManager.getInstance().getScreenMainControl().volumeSlider.getValue());
fft = new FFT(player.bufferSize(), player.sampleRate());
beatDetect = new BeatDetect(player.bufferSize(), player.sampleRate());
beatDetect.detectMode(beatDetectMode);
player.addListener(new AnalyzerAudioListener(fft, beatDetect));
player.addListener(new StreamingAudioListener(true));
player.play();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void loadFile(String file) {
loadFile(new File(file));
}
private class AnalyzerAudioListener implements AudioListener {
private final FFT fft;
private final BeatDetect beatDetect;
public AnalyzerAudioListener(FFT fft, BeatDetect beatDetect) {
this.fft = fft;
this.beatDetect = beatDetect;
}
@Override
public void samples(float[] floats) {
Animation animation = LEDCubeManager.getLEDCube().getCommThread().getCurrentAnimation();
if (animation instanceof AnimationSpectrumAnalyzer) {
AnimationSpectrumAnalyzer anim = (AnimationSpectrumAnalyzer)animation;
if (anim.isFFT()) {
fft.forward(floats);
anim.processFFT(fft);
}
if (anim.isBeatDetect()) {
if (anim.getBeatDetectMode() != beatDetectMode) {
beatDetectMode = anim.getBeatDetectMode();
beatDetect.detectMode(beatDetectMode);
}
beatDetect.detect(floats);
anim.processBeatDetect(beatDetect);
}
}
}
@Override
public void samples(float[] floatsL, float[] floatsR) {
Animation animation = LEDCubeManager.getLEDCube().getCommThread().getCurrentAnimation();
if (animation instanceof AnimationSpectrumAnalyzer) {
AnimationSpectrumAnalyzer anim = (AnimationSpectrumAnalyzer)animation;
if (anim.isFFT()) {
fft.forward(floatsL, floatsR);
anim.processFFT(fft);
}
if (anim.isBeatDetect()) {
if (anim.getBeatDetectMode() != beatDetectMode) {
beatDetectMode = anim.getBeatDetectMode();
beatDetect.detectMode(beatDetectMode);
}
float[] floats = new float[floatsL.length];
for (int i = 0; i < floatsL.length; i++) {
floats[i] = MathHelper.clamp(floatsL[i] / 2 + floatsR[i] / 2, -1, 1);
}
beatDetect.detect(floats);
anim.processBeatDetect(beatDetect);
}
}
}
}
private class StreamingAudioListener implements AudioListener {
private final boolean useStereo;
public StreamingAudioListener(boolean useStereo) {
this.useStereo = useStereo;
}
@Override
public void samples(float[] floats) {
//if (!player.isPlaying()) return;
short[] resampled = new short[floats.length];
for (int i = 0; i < floats.length; i++) {
resampled[i] = (short)MathHelper.clamp(Math.round(32768 * floats[i]), -32768, 32767);
}
send(resampled);
}
@Override
public void samples(float[] floatsL, float[] floatsR) {
//if (!player.isPlaying()) return;
short[] resampledL = new short[floatsL.length];
short[] resampledR = new short[floatsR.length];
for (int i = 0; i < floatsL.length; i++) {
resampledL[i] = (short)MathHelper.clamp(Math.round(32768 * floatsL[i]), -32768, 32767);
}
for (int i = 0; i < floatsR.length; i++) {
resampledR[i] = (short)MathHelper.clamp(Math.round(32768 * floatsR[i]), -32768, 32767);
}
if (useStereo) {
short[] stereo = new short[resampledL.length * 2];
for (int i = 0; i < resampledL.length; i++) {
stereo[i * 2] = resampledL[i];
stereo[i * 2 + 1] = resampledR[i];
}
send(stereo);
} else {
short[] mono = new short[resampledL.length];
for (int i = 0; i < resampledL.length; i++) {
mono[i] = (short)MathHelper.clamp(Math.round(resampledL[i] / 2 + resampledR[i] / 2), -32768, 32767);
}
send(mono);
}
}
private void send(short[] samples) {
ByteBuffer buf = ByteBuffer.allocate(samples.length * 2 + 2);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short)samples.length);
for (int i = 0; i < samples.length; i++) {
buf.putShort(samples[i]);
}
LEDCubeManager.getLEDCube().getCommThread().getTcpServer().sendPacket(new PacketAudioData(buf.array()));
}
}
}
|
package org.opencb.opencga.storage.core.search;
import org.apache.commons.lang3.StringUtils;
import org.opencb.biodata.models.variant.StudyEntry;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.annotation.ConsequenceTypeMappings;
import org.opencb.biodata.models.variant.avro.*;
import org.opencb.biodata.models.variant.stats.VariantStats;
import org.opencb.commons.datastore.core.ComplexTypeConverter;
import java.util.*;
public class VariantSearchToVariantConverter implements ComplexTypeConverter<Variant, VariantSearchModel> {
@Override
public Variant convertToDataModelType(VariantSearchModel variantSearchModel) {
// set chromosome, start, end, ref, alt from ID
Variant variant = new Variant(variantSearchModel.getId());
// set ID, chromosome, start, end, ref, alt, type
variant.setId(variantSearchModel.getVariantId());
// set variant type
variant.setType(VariantType.valueOf(variantSearchModel.getType()));
// set studies and stats
Map<String, StudyEntry> studyEntryMap = new HashMap<>();
if (variantSearchModel.getStudies() != null && variantSearchModel.getStudies().size() > 0) {
List<StudyEntry> studies = new ArrayList<>();
variantSearchModel.getStudies().forEach(s -> {
StudyEntry entry = new StudyEntry();
entry.setStudyId(s);
studies.add(entry);
studyEntryMap.put(s, entry);
});
variant.setStudies(studies);
}
if (variantSearchModel.getStats() != null && variantSearchModel.getStats().size() > 0) {
for (String key: variantSearchModel.getStats().keySet()) {
// key consists of 'stats' + "__" + studyId + "__" + cohort
String[] fields = key.split("__");
if (fields[1].contains("_")) {
String[] split = fields[1].split("_");
fields[1] = split[split.length - 1];
}
if (studyEntryMap.containsKey(fields[1])) {
VariantStats variantStats = new VariantStats();
variantStats.setMaf(variantSearchModel.getStats().get(key));
studyEntryMap.get(fields[1]).setStats(fields[2], variantStats);
} else {
System.out.println("Something wrong happened: stats " + key + ", but there is no study for that stats.");
}
}
}
// process annotation
VariantAnnotation variantAnnotation = new VariantAnnotation();
// consequence types
String gene = null;
String ensGene = null;
Map<String, ConsequenceType> consequenceTypeMap = new HashMap<>();
for (int i = 0; i < variantSearchModel.getGenes().size(); i++) {
if (!variantSearchModel.getGenes().get(i).startsWith("ENS")) {
gene = variantSearchModel.getGenes().get(i);
}
if (variantSearchModel.getGenes().get(i).startsWith("ENSG")) {
ensGene = variantSearchModel.getGenes().get(i);
}
if (variantSearchModel.getGenes().get(i).startsWith("ENST")) {
ConsequenceType consequenceType = new ConsequenceType();
consequenceType.setGeneName(gene);
consequenceType.setEnsemblGeneId(ensGene);
consequenceType.setEnsemblTranscriptId(variantSearchModel.getGenes().get(i));
// setProteinVariantAnnotation is postponed, since it will only be set if SO accession is 1583
// The key is the ENST id
consequenceTypeMap.put(variantSearchModel.getGenes().get(i), consequenceType);
}
}
// prepare protein substitution scores: sift and polyphen
List<Score> scores;
ProteinVariantAnnotation proteinAnnotation = null;
if (variantSearchModel.getSift() != -1.0 || variantSearchModel.getPolyphen() != -1.0) {
proteinAnnotation = new ProteinVariantAnnotation();
scores = new ArrayList<>();
scores.add(new Score(variantSearchModel.getSift(), "sift", variantSearchModel.getSiftDesc()));
scores.add(new Score(variantSearchModel.getPolyphen(), "polyphen", variantSearchModel.getPolyphenDesc()));
proteinAnnotation.setSubstitutionScores(scores);
}
// and finally, update the SO accession for each consequence type
// and setProteinVariantAnnotation if SO accession is 1583
for (String geneToSoAcc: variantSearchModel.getGeneToSoAcc()) {
String[] fields = geneToSoAcc.split("_");
if (consequenceTypeMap.containsKey(fields[0])) {
int soAcc = Integer.parseInt(fields[1]);
SequenceOntologyTerm sequenceOntologyTerm = new SequenceOntologyTerm();
sequenceOntologyTerm.setAccession("SO:" + String.format("%07d", soAcc));
sequenceOntologyTerm.setName(ConsequenceTypeMappings.accessionToTerm.get(soAcc));
if (consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms() == null) {
consequenceTypeMap.get(fields[0]).setSequenceOntologyTerms(new ArrayList<>());
}
consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms().add(sequenceOntologyTerm);
// only set protein for that consequence type
// if annotated protein and SO accession is 1583 (missense_variant)
if (proteinAnnotation != null && soAcc == 1583) {
consequenceTypeMap.get(fields[0]).setProteinVariantAnnotation(proteinAnnotation);
}
}
}
// and update the variant annotation with the consequence types
variantAnnotation.setConsequenceTypes(new ArrayList<>(consequenceTypeMap.values()));
// set populations
if (variantSearchModel.getPopFreq() != null && variantSearchModel.getPopFreq().size() > 0) {
List<PopulationFrequency> populationFrequencies = new ArrayList<>();
for (String key : variantSearchModel.getPopFreq().keySet()) {
PopulationFrequency populationFrequency = new PopulationFrequency();
String[] fields = key.split("__");
populationFrequency.setStudy(fields[1]);
populationFrequency.setPopulation(fields[2]);
populationFrequency.setAltAlleleFreq(variantSearchModel.getPopFreq().get(key));
populationFrequencies.add(populationFrequency);
}
variantAnnotation.setPopulationFrequencies(populationFrequencies);
}
// set conservations
scores = new ArrayList<>();
scores.add(new Score(variantSearchModel.getGerp(), "gerp", ""));
scores.add(new Score(variantSearchModel.getPhastCons(), "phastCons", ""));
scores.add(new Score(variantSearchModel.getPhylop(), "phylop", ""));
variantAnnotation.setConservation(scores);
// set cadd
scores = new ArrayList<>();
scores.add(new Score(variantSearchModel.getCaddRaw(), "cadd_raw", ""));
scores.add(new Score(variantSearchModel.getCaddScaled(), "cadd_scaled", ""));
variantAnnotation.setFunctionalScore(scores);
// set clinvar, cosmic, hpo
Map<String, List<String>> clinVarMap = new HashMap<>();
List<Cosmic> cosmicList = new ArrayList<>();
List<GeneTraitAssociation> geneTraitAssociationList = new ArrayList<>();
if (variantSearchModel.getTraits() != null) {
for (String trait : variantSearchModel.getTraits()) {
String[] fields = trait.split("
switch (fields[0]) {
case "ClinVar": {
// variant trait
// ClinVar -- accession -- trait
if (!clinVarMap.containsKey(fields[1])) {
clinVarMap.put(fields[1], new ArrayList<>());
}
clinVarMap.get(fields[1]).add(fields[2]);
break;
}
case "COSMIC": {
// variant trait
// COSMIC -- mutation id -- primary histology -- histology subtype
Cosmic cosmic = new Cosmic();
cosmic.setMutationId(fields[1]);
cosmic.setPrimaryHistology(fields[2]);
cosmic.setHistologySubtype(fields[3]);
cosmicList.add(cosmic);
break;
}
case "HPO": {
// gene trait
// HPO -- hpo -- name
GeneTraitAssociation geneTraitAssociation = new GeneTraitAssociation();
geneTraitAssociation.setHpo(fields[1]);
geneTraitAssociation.setName(fields[2]);
geneTraitAssociationList.add(geneTraitAssociation);
break;
}
default: {
System.out.println("Unknown trait type: " + fields[0] + ", it should be ClinVar, COSMIC or HPO");
break;
}
}
}
}
VariantTraitAssociation variantTraitAssociation = new VariantTraitAssociation();
List<ClinVar> clinVarList = new ArrayList<>();
for (String key: clinVarMap.keySet()) {
ClinVar clinVar = new ClinVar();
clinVar.setAccession(key);
clinVar.setTraits(clinVarMap.get(key));
clinVarList.add(clinVar);
}
if (clinVarList.size() > 0 || cosmicList.size() > 0) {
if (clinVarList.size() > 0) {
variantTraitAssociation.setClinvar(clinVarList);
}
if (cosmicList.size() > 0) {
variantTraitAssociation.setCosmic(cosmicList);
}
variantAnnotation.setVariantTraitAssociation(variantTraitAssociation);
}
if (geneTraitAssociationList.size() > 0) {
variantAnnotation.setGeneTraitAssociation(geneTraitAssociationList);
}
// set variant annotation
variant.setAnnotation(variantAnnotation);
return variant;
}
@Override
public VariantSearchModel convertToStorageType(Variant variant) {
VariantSearchModel variantSearchModel = new VariantSearchModel();
// Set general Variant attributes: id, dbSNP, chromosome, start, end, type
variantSearchModel.setId(variant.getChromosome() + ":" + variant.getStart() + ":"
+ variant.getReference() + ":" + variant.getAlternate());
variantSearchModel.setChromosome(variant.getChromosome());
variantSearchModel.setStart(variant.getStart());
variantSearchModel.setEnd(variant.getEnd());
variantSearchModel.setVariantId(variant.getId());
variantSearchModel.setType(variant.getType().toString());
// This field contains all possible IDs: id, dbSNP, genes, transcripts, protein, clinvar, hpo, ...
// This will help when searching by variant id. This is added at the end of the method after collecting all IDs
Set<String> xrefs = new HashSet<>();
xrefs.add(variant.getChromosome() + ":" + variant.getStart() + ":" + variant.getReference() + ":" + variant.getAlternate());
xrefs.add(variantSearchModel.getVariantId());
// Set Studies Alias
if (variant.getStudies() != null && variant.getStudies().size() > 0) {
List<String> studies = new ArrayList<>();
Map<String, Float> stats = new HashMap<>();
// variant.getStudies().forEach(s -> studies.add(s.getStudyId()));
for (StudyEntry studyEntry : variant.getStudies()) {
String studyId = studyEntry.getStudyId();
if (studyId.contains(":")) {
String[] split = studyId.split(":");
studyId = split[split.length - 1];
}
studies.add(studyId);
// We store the cohort stats with the format stats_STUDY_COHORT = value, e.g. stats_1kg_phase3_ALL=0.02
if (studyEntry.getStats() != null && studyEntry.getStats().size() > 0) {
Map<String, VariantStats> studyStats = studyEntry.getStats();
for (String key: studyStats.keySet()) {
stats.put("stats__" + studyId + "__" + key, studyStats.get(key).getMaf());
}
}
}
variantSearchModel.setStudies(studies);
variantSearchModel.setStats(stats);
}
// Check for annotation
VariantAnnotation variantAnnotation = variant.getAnnotation();
if (variantAnnotation != null) {
// Set Genes and Consequence Types
List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes();
if (consequenceTypes != null) {
Map<String, Set<String>> genes = new LinkedHashMap<>();
Set<Integer> soAccessions = new LinkedHashSet<>();
Set<String> geneToSOAccessions = new LinkedHashSet<>();
for (ConsequenceType consequenceType : consequenceTypes) {
// Set genes if exists
if (StringUtils.isNotEmpty(consequenceType.getGeneName())) {
if (!genes.containsKey(consequenceType.getGeneName())) {
genes.put(consequenceType.getGeneName(), new LinkedHashSet<>());
}
genes.get(consequenceType.getGeneName()).add(consequenceType.getGeneName());
genes.get(consequenceType.getGeneName()).add(consequenceType.getEnsemblGeneId());
genes.get(consequenceType.getGeneName()).add(consequenceType.getEnsemblTranscriptId());
xrefs.add(consequenceType.getGeneName());
xrefs.add(consequenceType.getEnsemblGeneId());
xrefs.add(consequenceType.getEnsemblTranscriptId());
}
// Remove 'SO:' prefix to Store SO Accessions as integers and also store the relation
// between genes and SO accessions
for (SequenceOntologyTerm sequenceOntologyTerm : consequenceType.getSequenceOntologyTerms()) {
int soNumber = Integer.parseInt(sequenceOntologyTerm.getAccession().substring(3));
soAccessions.add(soNumber);
if (StringUtils.isNotEmpty(consequenceType.getGeneName())) {
geneToSOAccessions.add(consequenceType.getGeneName() + "_" + soNumber);
geneToSOAccessions.add(consequenceType.getEnsemblGeneId() + "_" + soNumber);
geneToSOAccessions.add(consequenceType.getEnsemblTranscriptId() + "_" + soNumber);
}
}
// Set uniprot accession protein id in xrefs
if (consequenceType.getProteinVariantAnnotation() != null) {
xrefs.add(consequenceType.getProteinVariantAnnotation().getUniprotAccession());
}
}
// Set sift and polyphen
setProteinScores(consequenceTypes, variantSearchModel);
// We store the accumulated data
genes.forEach((s, strings) -> variantSearchModel.getGenes().addAll(strings));
// for (String gene: genes.keySet()) {
//// variantSearchModel.getGenes().add(gene);
// variantSearchModel.getGenes().addAll(genes.get(gene));
variantSearchModel.setSoAcc(new ArrayList<>(soAccessions));
variantSearchModel.setGeneToSoAcc(new ArrayList<>(geneToSOAccessions));
}
// Set Populations frequencies
if (variantAnnotation.getPopulationFrequencies() != null) {
Map<String, Float> populationFrequencies = new HashMap<>();
for (PopulationFrequency populationFrequency : variantAnnotation.getPopulationFrequencies()) {
populationFrequencies.put("popFreq__" + populationFrequency.getStudy() + "__"
+ populationFrequency.getPopulation(), populationFrequency.getAltAlleleFreq());
}
if (!populationFrequencies.isEmpty()) {
variantSearchModel.setPopFreq(populationFrequencies);
}
}
// Set Conservation scores
if (variantAnnotation.getConservation() != null) {
for (Score score : variantAnnotation.getConservation()) {
switch (score.getSource()) {
case "phastCons":
variantSearchModel.setPhastCons(score.getScore());
break;
case "phylop":
variantSearchModel.setPhylop(score.getScore());
break;
case "gerp":
variantSearchModel.setGerp(score.getScore());
break;
default:
System.out.println("Unknown 'conservation' source: score.getSource() = " + score.getSource());
break;
}
}
}
// Set CADD
if (variantAnnotation.getFunctionalScore() != null) {
for (Score score : variantAnnotation.getFunctionalScore()) {
switch (score.getSource()) {
case "cadd_raw":
case "caddRaw":
variantSearchModel.setCaddRaw(score.getScore());
break;
case "cadd_scaled":
case "caddScaled":
variantSearchModel.setCaddScaled(score.getScore());
break;
default:
System.out.println("Unknown 'functional score' source: score.getSource() = " + score.getSource());
break;
}
}
}
// Set variant traits: ClinVar, Cosmic, HPO, ...
Set<String> traits = new HashSet<>();
if (variantAnnotation.getVariantTraitAssociation() != null) {
if (variantAnnotation.getVariantTraitAssociation().getClinvar() != null) {
variantAnnotation.getVariantTraitAssociation().getClinvar()
.forEach(cv -> {
xrefs.add(cv.getAccession());
cv.getTraits().forEach(cvt -> traits.add("ClinVar" + " -- " + cv.getAccession() + " -- " + cvt));
});
}
if (variantAnnotation.getVariantTraitAssociation().getCosmic() != null) {
variantAnnotation.getVariantTraitAssociation().getCosmic()
.forEach(cosm -> {
xrefs.add(cosm.getMutationId());
traits.add("COSMIC -- " + cosm.getMutationId() + " -- "
+ cosm.getPrimaryHistology() + " -- " + cosm.getHistologySubtype());
});
}
}
if (variantAnnotation.getGeneTraitAssociation() != null && variantAnnotation.getGeneTraitAssociation().size() > 0) {
for (GeneTraitAssociation geneTraitAssociation : variantAnnotation.getGeneTraitAssociation()) {
if (geneTraitAssociation.getSource().equalsIgnoreCase("hpo")) {
traits.add("HPO -- " + geneTraitAssociation.getHpo() + " -- " + geneTraitAssociation.getName());
}
}
}
variantSearchModel.setTraits(new ArrayList<>(traits));
}
variantSearchModel.setXrefs(new ArrayList<>(xrefs));
return variantSearchModel;
}
public List<VariantSearchModel> convertListToStorageType(List<Variant> variants) {
List<VariantSearchModel> variantSearchModelList = new ArrayList<>(variants.size());
for (Variant variant: variants) {
VariantSearchModel variantSearchModel = convertToStorageType(variant);
if (variantSearchModel.getId() != null) {
variantSearchModelList.add(variantSearchModel);
}
}
return variantSearchModelList;
}
/**
* Retrieve the protein substitution scores and descriptions from a consequence
* type annotation: sift or polyphen, and update the variant search model.
*
* @param consequenceTypes List of consequence type target
* @param variantSearchModel Variant search model to update
*/
private void setProteinScores(List<ConsequenceType> consequenceTypes, VariantSearchModel variantSearchModel) {
double sift = 10;
String siftDesc = "";
double polyphen = -1.0;
String polyphenDesc = "";
if (consequenceTypes != null) {
for (ConsequenceType consequenceType : consequenceTypes) {
if (consequenceType.getProteinVariantAnnotation() != null
&& consequenceType.getProteinVariantAnnotation().getSubstitutionScores() != null) {
for (Score score : consequenceType.getProteinVariantAnnotation().getSubstitutionScores()) {
String source = score.getSource();
if (source.equals("sift")) {
if (score.getScore() < sift) {
sift = score.getScore();
siftDesc = score.getDescription();
}
} else if (source.equals("polyphen")) {
if (score.getScore() > polyphen) {
polyphen = score.getScore();
polyphenDesc = score.getDescription();
}
}
}
}
}
}
// If sift not exist we set it to -1.0
if (sift == 10) {
sift = -1.0;
}
// set scores
variantSearchModel.setSift(sift);
variantSearchModel.setPolyphen(polyphen);
// set descriptions
variantSearchModel.setSiftDesc(siftDesc);
variantSearchModel.setPolyphenDesc(polyphenDesc);
}
}
|
package com.bbn.kbp.events2014.scorer.bin;
import com.bbn.bue.common.files.FileUtils;
import com.bbn.bue.common.parameters.Parameters;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.io.AnnotationStore;
import com.bbn.kbp.events2014.io.AssessmentSpecFormats;
import com.bbn.kbp.events2014.io.SystemOutputStore;
import com.bbn.kbp.events2014.scorer.KBPScorer;
import com.bbn.kbp.events2014.TypeRoleFillerRealis;
import com.bbn.kbp.events2014.scorer.observers.*;
import com.bbn.kbp.events2014.scorer.observers.errorloggers.HTMLErrorRecorder;
import com.bbn.kbp.events2014.scorer.observers.errorloggers.NullHTMLErrorRecorder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Sets.union;
public final class KBPScorerBin {
private static Logger log = LoggerFactory.getLogger(KBPScorerBin.class);
private KBPScorerBin() {
throw new UnsupportedOperationException();
}
private static void usage() {
log.warn("usage: kbpScorer param_file\n" +
"parameters are:\n" +
"\tanswerKey: annotation store to score against\n" +
"If running on a single output store:\n" +
"\tscoringOutput: directory to write scoring observer logs to\n"+
"\tsystemOutput: system output store to score\n"+
"\tdocumentsToScore: (optional) file listing which documents to score. If not present, scores all in either store."+
"If running on multiple stores:\n" +
"\tscoringOutputRoot: directory to write scoring observer logs to. A subdirectory will be created for each input store.\n"+
"\tsystemOutputsDir: each subdirectory of this is expected to be a system output store to score\n"+
"\tdocumentsToScore: file listing which documents to score."
);
System.exit(1);
}
private static List<KBPScoringObserver<TypeRoleFillerRealis>> getCorpusObservers(Parameters params) {
final List<KBPScoringObserver<TypeRoleFillerRealis>> corpusObservers = Lists.newArrayList();
if (params.getBoolean("annotationComplete")) {
corpusObservers.add(ExitOnUnannotatedAnswerKey.<TypeRoleFillerRealis>create());
}
final HTMLErrorRecorder dummyRecorder = NullHTMLErrorRecorder.getInstance();
// Lax scorer
corpusObservers.add(BuildConfusionMatrix.<TypeRoleFillerRealis>forAnswerFunctions(
"Lax", KBPScorer.IsPresent, KBPScorer.AnyAnswerSemanticallyCorrect));
corpusObservers.add(StrictStandardScoringObserver.strictScorer(dummyRecorder));
corpusObservers.add(StrictStandardScoringObserver.standardScorer(dummyRecorder));
corpusObservers.add(SkipIncompleteAnnotations.wrap(StrictStandardScoringObserver.strictScorer(dummyRecorder)));
corpusObservers.add(SkipIncompleteAnnotations.wrap(StrictStandardScoringObserver.standardScorer(dummyRecorder)));
return corpusObservers;
}
public static void main(final String[] argv) throws IOException {
if (argv.length != 1) {
usage();
}
final Parameters params = Parameters.loadSerifStyle(new File(argv[0]));
log.info(params.dump());
final KBPScorer scorer = KBPScorer.create();
final AnnotationStore goldAnswerStore = AssessmentSpecFormats.openAnnotationStore(params
.getExistingDirectory("answerKey"));
checkArgument(params.isPresent("systemOutput") != params.isPresent("systemOutputsDir"),
"Exactly one of systemOutput and systemOutputsDir must be specified");
if (params.isPresent("systemOutput")) {
scoreSingleSystemOutputStore(goldAnswerStore, scorer, params);
} else if (params.isPresent("systemOutputsDir")) {
scoreMultipleSystemOutputStores(goldAnswerStore, scorer, params);
} else {
throw new RuntimeException("Can't happen");
}
}
// this and the single output store version can't be easily refactored together because
// of their differing behavior wrt the list of documents to score
private static void scoreMultipleSystemOutputStores(AnnotationStore goldAnswerStore, KBPScorer scorer, Parameters params) throws IOException {
final File systemOutputsDir = params.getExistingDirectory("systemOutputsDir");
final File scoringOutputRoot = params.getCreatableDirectory("scoringOutputRoot");
log.info("Scoring all subdirectories of {}", systemOutputsDir);
final Set<Symbol> documentsToScore = loadDocumentsToScore(params);
for (File subDir : systemOutputsDir.listFiles()) {
if (subDir.isDirectory()) {
final SystemOutputStore systemOutputStore = AssessmentSpecFormats.openSystemOutputStore(subDir);
final File outputDir = new File(scoringOutputRoot, subDir.getName());
// we need new observers for each system output to avoid keeping stats from
// one system to another
final List<KBPScoringObserver<TypeRoleFillerRealis>> corpusObservers = getCorpusObservers(params);
outputDir.mkdirs();
scorer.run(systemOutputStore, goldAnswerStore, documentsToScore,
corpusObservers, outputDir);
}
}
}
private static void scoreSingleSystemOutputStore(AnnotationStore goldAnswerStore, KBPScorer scorer, Parameters params) throws IOException {
final File systemOutputDir = params.getExistingDirectory("systemOutput");
log.info("Scoring single system output {}", systemOutputDir);
final SystemOutputStore systemOutputStore = AssessmentSpecFormats.openSystemOutputStore(systemOutputDir);
final Set<Symbol> documentsToScore;
if (params.isPresent("documentsToScore")) {
documentsToScore = loadDocumentsToScore(params);
} else {
documentsToScore = union(systemOutputStore.docIDs(), goldAnswerStore.docIDs());
}
final List<KBPScoringObserver<TypeRoleFillerRealis>> corpusObservers = getCorpusObservers(params);
scorer.run(systemOutputStore, goldAnswerStore, documentsToScore,
corpusObservers, params.getCreatableDirectory("scoringOutput"));
}
private static ImmutableSet<Symbol> loadDocumentsToScore(Parameters params) throws IOException {
final File docsToScoreList = params.getExistingFile("documentsToScore");
final ImmutableSet<Symbol> ret = ImmutableSet.copyOf(FileUtils.loadSymbolList(docsToScoreList));
log.info("Scoring over {} documents specified in {}", ret.size(), docsToScoreList);
return ret;
}
}
|
package com.tranek.chivalryserverbrowser;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;
/**
*
* Represents a Chivalry: Medieval Warfare server.
*
*/
public class ChivServer {
/** The server's name. */
protected String mName;
/** The server's IP address. */
protected String mIP;
/** The server's queryport. */
protected String mQueryPort;
/** The server's gameport. */
protected String mGamePort;
/** The server's map. */
protected String mMap;
/** The server's game mode. */
protected String mGameMode;
/** The user's ping to the server. */
protected String mPing;
/** The server's maximum players. */
protected String mMaxPlayers;
/** The server's current players. */
protected String mCurrentPlayers;
/** Whether or not the server has a password. */
protected String mHasPassword;
/** The server's minimum rank. */
protected String mMinRank;
/** The server's maximum rank. */
protected String mMaxRank;
/** The server's location. */
protected String mLocation;
/** The server's allowed player perspective. */
protected String mPerspective;
/** The server's latitude. */
protected String mLatitude;
/** The server's longitude. */
protected String mLongitude;
/**
* Creates a new {@link ChivServer} by directly specifying all of the member fields.
*
* @param name the server's name
* @param ip the server's IP address
* @param queryport the server's queryport
* @param gameport the server's gameport
* @param map the server's map
* @param gamemode the server's game mode
* @param ping the user's ping to the server
* @param maxplayers the server's max ping
* @param currentplayers the server's current players
* @param haspassword whether or not the server has a password
* @param minrank the server's minimum rank
* @param maxrank the server's maximum rank
* @param location the server's location
* @param perspective the server's allowed player perspective
* @param lat the server's latitude
* @param lon the server's longitude
*/
public ChivServer(String name, String ip, String queryport, String gameport, String map,
String gamemode, String ping, String maxplayers, String currentplayers,
String haspassword, String minrank, String maxrank, String location, String perspective,
String lat, String lon) {
mName = name;
mIP = ip;
mQueryPort = queryport;
mGamePort = gameport;
mMap = map;
mGameMode = gamemode;
mPing = ping;
mMaxPlayers = maxplayers;
mCurrentPlayers = currentplayers;
mHasPassword = haspassword;
mMinRank = minrank;
mMaxRank = maxrank;
mLocation = location;
mPerspective = perspective;
mLatitude = lat;
mLongitude = lon;
}
/**
* Creates a new {@link ChivServer} with only a name, ip address, and queryport.
*
* @param name the server's name
* @param ip the server's ip address
* @param queryport the server's queryport
*/
public ChivServer(String name, String ip, String queryport) {
mName = name;
mIP = ip;
mQueryPort = queryport;
}
/**
* Creates a new {@link ChivServer} with only a name, ip address, queryport, and map.
*
* @param name the server's name
* @param ip the server's ip address
* @param queryport the server's queryport
* @param map the server's map
*/
public ChivServer(String name, String ip, String queryport, String map) {
mName = name;
mIP = ip;
mQueryPort = queryport;
mMap = map;
}
/**
* Static method to create a new {@link ChivServer} by querying the server directly
* from its IP address and queryport.
*
* @param mw reference to the MainWindow to have access to queried servers
* @param ip the server's IP address
* @param queryport the server's queryport
* @return a new {@link ChivServer}
* @see QueryServerCondenser#getInfo()
* @see LocationRIPE#getLocation(String)
* @see #getLocFromOtherServer(String, Vector)
*/
public static ChivServer createChivServer(MainWindow mw, String ip, int queryport) {
QueryServerCondenser qsc = new QueryServerCondenser(ip, queryport);
HashMap<String, String> info = qsc.getInfo();
String location = "";
String lat = "";
String lon = "";
HashMap<String, String> loc = getLocation(mw, ip);
location = loc.get("location");
lat = loc.get("latitude");
lon = loc.get("longitude");
String gamemode = getGameMode(info.get("map"));
return new ChivServer(info.get("name"), ip, "" + queryport, info.get("gameport"),
info.get("map"), gamemode, info.get("ping"), info.get("maxplayers"),
info.get("currentplayers"), info.get("haspassword"), info.get("minrank"),
info.get("maxrank"), location, info.get("perspective"), lat, lon);
}
/**
* Creates a new clone of this {@link ChivServer}.
*/
@Override
public ChivServer clone() {
return new ChivServer(mName, mIP, mQueryPort, mGamePort, mMap, mGameMode, mPing,
mMaxPlayers, mCurrentPlayers, mHasPassword, mMinRank, mMaxRank, mLocation,
mPerspective, mLatitude, mLongitude);
}
/**
* Gets the location for an IP address. It also adds a slight bit of randomness to its
* latitude and longitude so that multiple servers in a single data center don't overlap
* their markers on the map.
*
* @param ip the IP address for the server
* @return a HashMap of the location, latitude, and longitude
*/
public static HashMap<String, String> getLocation(MainWindow mw, String ip) {
HashMap<String, String> result = new HashMap<String, String>();
String location = "";
String lat = "";
String lon = "";
LocationRIPE l = new LocationRIPE();
HashMap<String, String> loc = l.getLocation(ip);
if (loc != null) {
String city = loc.get("city");
String state = loc.get("state");
String country = loc.get("country");
if ( !country.equals("USA") ) {
if ( !city.equals("") ) {
city += ", ";
}
} else if ( !city.equals("") ) {
city += " ";
}
if ( !state.equals("") ) {
state += ", ";
}
location = city + state + country;
lat = loc.get("latitude");
lon = loc.get("longitude");
}
if ( location.equals("") ) {
LocationARIN l2 = new LocationARIN();
loc = l2.getLocation(ip);
String city = loc.get("city");
String state = loc.get("state");
String country = loc.get("country");
if ( !country.equals("USA") ) {
if ( !city.equals("") ) {
city += ", ";
}
} else if ( !city.equals("") ) {
city += " ";
}
if ( !state.equals("") ) {
state += ", ";
}
location = city + state + country;
}
if ( lat.equals("") || lon.equals("") ) {
HashMap<String, String> lfos = getLocFromOtherServer(location, mw.servers);
if ( lfos != null ) {
lat = lfos.get("latitude");
lon = lfos.get("longitude");
}
}
if ( lat.equals("") || lon.equals("") ) {
//TODO check db
}
if ( lat.equals("") || lon.equals("") ) {
//TODO geolocate from google and store in db
// "DE country"
}
if ( !lat.equals("") && !lon.equals("") ) {
double latd = Double.parseDouble(lat);
double lond = Double.parseDouble(lon);
Random generator = new Random(System.currentTimeMillis());
int signlat = generator.nextInt(1);
int signlon = generator.nextInt(1);
double latran = (generator.nextDouble() * 999 + 1) / 10000;
double lonran = (generator.nextDouble() * 999 + 1) / 10000;
if ( signlat == 1 ) {
latd += latran;
} else {
latd -= latran;
}
if ( signlon == 1 ) {
lond += lonran;
} else {
lond -= lonran;
}
lat = "" + latd;
lon = "" + lond;
}
result.put("location", location);
result.put("latitude", lat);
result.put("longitude", lon);
return result;
}
/**
* Checks if another server with the same location has values for latitude and longitude.
* If another such server exists, it copies those values from it for itself. This is
* needed because the RIPE geolocation service sometimes doesn't return a latitude and
* longitude for some addresses.
*
* @param location the {@link ChivServer} location
* @param servers the list of {@link ChivServer} to check
* @return a {@link HashMap} of the latitude and longitude; or null if no other server
* with the same location exists with latitude and longitude data
*/
public synchronized static HashMap<String, String> getLocFromOtherServer(String location, Vector<ChivServer> servers) {
for ( ChivServer c : servers ) {
if ( !c.mLatitude.equals("") && !c.mLongitude.equals("") && c.mLocation.equals(location)) {
HashMap<String, String> result = new HashMap<String, String>();
result.put("latitude", c.mLatitude);
result.put("longitude", c.mLongitude);
return result;
}
}
return null;
}
/**
* Gets the game mode for a map based on its prefix.
*
* @param mapname the map name
* @return the game mode as a string
*/
public static String getGameMode(String mapname) {
String gamemode = "";
String prefix = mapname.split("-")[0];
prefix = prefix.toLowerCase();
if ( prefix.equals("aocffa") ) {
gamemode = "FFA";
} else if( prefix.equals("aocduel") ) {
gamemode = "DUEL";
} else if( prefix.equals("aockoth") ) {
gamemode = "KOTH";
} else if( prefix.equals("aocctf") ) {
gamemode = "CTF";
} else if( prefix.equals("aoclts") ) {
gamemode = "LTS";
} else if ( prefix.equals("aocto") ) {
gamemode = "TO";
} else if ( prefix.equals("aoctd") ) {
gamemode = "TDM";
}
return gamemode;
}
}
|
package org.eclipse.mylyn.internal.tasks.core.externalization;
import java.io.File;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.commons.net.Policy;
import org.eclipse.mylyn.internal.tasks.core.ITasksCoreConstants;
/**
* File based externalization participant
*
* @author Rob Elves
*/
public abstract class AbstractExternalizationParticipant implements IExternalizationParticipant {
public static final String SNAPSHOT_PREFIX = ".";
public abstract void load(File sourceFile, IProgressMonitor monitor) throws CoreException;
public abstract void save(File targetFile, IProgressMonitor monitor) throws CoreException;
public abstract String getDescription();
public abstract ISchedulingRule getSchedulingRule();
public abstract boolean isDirty();
public abstract String getFileName();
public AbstractExternalizationParticipant() {
super();
}
protected boolean takeSnapshot(File file) {
if (file.length() > 0) {
File originalFile = file.getAbsoluteFile();
File backup = new File(file.getParentFile(), SNAPSHOT_PREFIX + file.getName());
backup.delete();
return originalFile.renameTo(backup);
}
return false;
}
public void execute(IExternalizationContext context, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(context);
monitor = Policy.monitorFor(monitor);
final File dataFile = getFile(context.getRootPath());
switch (context.getKind()) {
case SAVE:
if (dataFile != null) {
takeSnapshot(dataFile);
}
save(dataFile, monitor);
break;
case LOAD:
performLoad(dataFile, monitor);
break;
case SNAPSHOT:
break;
}
}
protected boolean performLoad(final File dataFile, IProgressMonitor monitor) throws CoreException {
try {
load(dataFile, monitor);
return true;
} catch (CoreException e) {
if (dataFile != null) {
File backup = new File(dataFile.getParentFile(), SNAPSHOT_PREFIX + dataFile.getName());
if (backup.exists()) {
StatusHandler.log(new Status(IStatus.WARNING, ITasksCoreConstants.ID_PLUGIN, "Failed to load "
+ dataFile.getName() + ", restoring from snapshot", e));
load(backup, monitor);
return true;
}
}
}
return false;
}
public File getFile(String rootPath) throws CoreException {
String fileName = getFileName();
if (fileName != null) {
String filePath = rootPath + File.separator + getFileName();
return new File(filePath);
}
return null;
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.builder.component.LoadingBarBuilder;
import com.valkryst.VTerminal.misc.IntRange;
import lombok.Getter;
import java.awt.Color;
import java.util.Objects;
public class LoadingBar extends Component {
/** The percent complete. */
@Getter private int percentComplete = 0;
/** The character that represents an incomplete cell. */
@Getter private char incompleteCharacter;
/** The character that represents a complete cell. */
@Getter private char completeCharacter;
/** The background color for incomplete cells. */
@Getter private Color backgroundColor_incomplete;
/** The foreground color for incomplete cells. */
@Getter private Color foregroundColor_incomplete;
/** The background color for complete cells. */
@Getter private Color backgroundColor_complete;
/** The foreground color for complete cells. */
@Getter private Color foregroundColor_complete;
/**
* Constructs a new LoadingBar.
*
* @param builder
* The builder to use.
*/
public LoadingBar(final LoadingBarBuilder builder) {
super(builder.getColumnIndex(), builder.getRowIndex(), builder.getWidth(), builder.getHeight());
super.setRadio(builder.getRadio());
incompleteCharacter = builder.getIncompleteCharacter();
completeCharacter = builder.getCompleteCharacter();
backgroundColor_incomplete = builder.getBackgroundColor_incomplete();
foregroundColor_incomplete = builder.getForegroundColor_incomplete();
backgroundColor_complete = builder.getBackgroundColor_complete();
foregroundColor_complete = builder.getForegroundColor_complete();
// Set all chars to incomplete state:
for (final AsciiString string : super.getStrings()) {
string.setAllCharacters(incompleteCharacter);
string.setBackgroundAndForegroundColor(backgroundColor_incomplete, foregroundColor_incomplete);
}
}
@Override
public boolean equals(final Object otherObj) {
if (otherObj instanceof LoadingBar == false) {
return false;
}
if (otherObj == this) {
return true;
}
final LoadingBar otherBar = (LoadingBar) otherObj;
boolean isEqual = super.equals(otherObj);
isEqual &= Objects.equals(percentComplete, otherBar.getPercentComplete());
isEqual &= Objects.equals(incompleteCharacter, otherBar.getIncompleteCharacter());
isEqual &= Objects.equals(completeCharacter, otherBar.getCompleteCharacter());
isEqual &= Objects.equals(backgroundColor_incomplete, otherBar.getBackgroundColor_incomplete());
isEqual &= Objects.equals(foregroundColor_incomplete, otherBar.getForegroundColor_incomplete());
isEqual &= Objects.equals(backgroundColor_complete, otherBar.getBackgroundColor_complete());
isEqual &= Objects.equals(foregroundColor_complete, otherBar.getForegroundColor_complete());
return isEqual;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), percentComplete, incompleteCharacter, completeCharacter,
backgroundColor_incomplete, foregroundColor_incomplete, backgroundColor_complete,
foregroundColor_complete);
}
/**
* Sets the new percent complete and redraws the loading bar
* to reflect the changes.
*
* @param percentComplete
* The new percent complete.
*/
public void setPercentComplete(int percentComplete) {
if (percentComplete < 0) {
percentComplete = 0;
}
if (percentComplete > 100) {
percentComplete = 100;
}
final int numberOfCompleteChars = (int) (super.getWidth() * (percentComplete / 100f));
final IntRange range = new IntRange(0, numberOfCompleteChars);
for (final AsciiString string : super.getStrings()) {
string.setBackgroundAndForegroundColor(backgroundColor_incomplete, foregroundColor_incomplete);
string.setAllCharacters(incompleteCharacter);
string.setBackgroundAndForegroundColor(backgroundColor_complete, foregroundColor_complete, range);
string.setCharacters(completeCharacter, range);
}
this.percentComplete = percentComplete;
super.transmitDraw();
}
}
|
package cgeo.geocaching.utils;
import cgeo.geocaching.R;
import cgeo.geocaching.databinding.DialogTitleButtonButtonBinding;
import cgeo.geocaching.databinding.EmojiselectorBinding;
import cgeo.geocaching.maps.CacheMarker;
import cgeo.geocaching.storage.extension.EmojiLRU;
import cgeo.geocaching.storage.extension.OneTimeDialogs;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.functions.Action1;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Pair;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class EmojiUtils {
public static final int NO_EMOJI = 0;
// internal consts for calculated circles
private static final int COLOR_VALUES = 3; // supported # of different values per RGB
private static final int COLOR_SPREAD = 127;
private static final int COLOR_OFFSET = 0;
private static final int OPACITY_VALUES = 5;
private static final int OPACITY_SPREAD = 51;
private static final int CUSTOM_SET_SIZE_PER_OPACITY = COLOR_VALUES * COLOR_VALUES * COLOR_VALUES;
private static final int CUSTOM_SET_SIZE = CUSTOM_SET_SIZE_PER_OPACITY * OPACITY_VALUES;
// Unicode custom glyph area needed/supported by this class
private static final int CUSTOM_ICONS_START = 0xe000;
private static final int CUSTOM_ICONS_END = CUSTOM_ICONS_START + CUSTOM_SET_SIZE - 1; // max. possible value by Unicode definition: 0xf8ff;
private static final int CUSTOM_ICONS_START_CIRCLES = CUSTOM_ICONS_START;
private static final int VariationSelectorEmoji = 0xfe0f;
// list of emojis supported by the EmojiPopup
// should ideally be supported by the Android API level we have set as minimum (currently API 21 = Android 5),
// but starting with API 23 (Android 6) the app automatically filters out characters not supported by their fonts
private static final EmojiSet[] symbols = {
// category symbols
new EmojiSet(0x2764, new int[]{
/* hearts */ 0x2764, 0x1f9e1, 0x1f49b, 0x1f49a, 0x1f499, 0x1f49c, 0x1f90e, 0x1f5a4, 0x1f90d,
/* geometric */ 0x1f7e5, 0x1f7e7, 0x1f7e8, 0x1f7e9, 0x1f7e6, 0x1f7ea, 0x1f7eb, 0x2b1b, 0x2b1c,
/* geometric */ 0x1f536, 0x1f537,
/* events */ 0x1f383, 0x1f380, 0x1f384, 0x1f389,
/* award-medal */ 0x1f947, 0x1f948, 0x1f949, 0x1f3c6,
/* office */ 0x1f4c6,
/* warning */ 0x26a0, 0x26d4, 0x1f6ab, 0x1f6b3, 0x1f6d1, 0x2622,
/* av-symbol */ 0x1f505, 0x1f506,
/* other-symbol */ 0x2b55, 0x2705, 0x2611, 0x2714, 0x2716, 0x2795, 0x2796, 0x274c, 0x274e, 0x2733, 0x2734, 0x2747, 0x203c, 0x2049, 0x2753, 0x2757,
/* flags */ 0x1f3c1, 0x1f6a9, 0x1f3f4, 0x1f3f3
}),
// category custom symbols - will be filled dynamically below; has to be at position CUSTOM_GLYPHS_ID within EmojiSet[]
new EmojiSet(CUSTOM_ICONS_START_CIRCLES + 18 + CUSTOM_SET_SIZE_PER_OPACITY, new int[CUSTOM_SET_SIZE_PER_OPACITY]), // "18" to pick red circle instead of black
// category places
new EmojiSet(0x1f30d, new int[]{
/* globe */ 0x1f30d, 0x1f30e, 0x1f30f, 0x1f5fa,
/* geographic */ 0x26f0, 0x1f3d4, 0x1f3d6, 0x1f3dc, 0x1f3dd, 0x1f3de,
/* buildings */ 0x1f3e0, 0x1f3e1, 0x1f3e2, 0x1f3d9, 0x1f3eb, 0x1f3ea, 0x1F3ed, 0x1f3e5, 0x1f3da, 0x1f3f0,
/* other */ 0x1f5fd, 0x26f2, 0x2668, 0x1f6d2, 0x1f3ad, 0x1f3a8,
/* plants */ 0x1f332, 0x1f333, 0x1f334, 0x1f335, 0x1f340,
/* transport */ 0x1f682, 0x1f683, 0x1f686, 0x1f687, 0x1f68d, 0x1f695, 0x1f6b2, 0x1f697, 0x1f699, 0x2693, 0x26f5, 0x2708, 0x1f680,
/* transp.-sign */ 0x267f, 0x1f6bb,
/* time */ 0x23f3, 0x231a, 0x23f1, 0x1f324, 0x2600, 0x1f319, 0x1f318, 0x2728
}),
// category food
new EmojiSet(0x2615, new int[]{
/* fruits */ 0x1f34a, 0x1f34b, 0x1f34d, 0x1f34e, 0x1f34f, 0x1f95d, 0x1f336, 0x1f344,
/* other */ 0x1f968, 0x1f354, 0x1f355,
/* food-sweet */ 0x1f366, 0x1f370, 0x1f36d,
/* drink */ 0x1f964, 0x2615, 0x1f37a
}),
// category activity
new EmojiSet(0x1f3c3, new int[]{
/* person-sport */ 0x26f7, 0x1f3c4, 0x1f6a3, 0x1f3ca, 0x1f6b4,
/* p.-activity */ 0x1f6b5, 0x1f9d7,
/* person-role */ 0x1f575,
/* sport */ 0x26bd, 0x1f94e, 0x1f3c0, 0x1f3c8, 0x1f93f, 0x1f3bf, 0x1f3af, 0x1f9ff,
/* tool */ 0x1fa9c,
/* science */ 0x2697, 0x1f9ea, 0x1f52c,
/* other things */ 0x1f50e, 0x1f526, 0x1f4a1, 0x1f4d4, 0x1f4dc, 0x1f4ec, 0x1f3f7
}),
// category people
new EmojiSet(0x1f600, new int[]{
/* smileys */ 0x1f600, 0x1f60d, 0x1f641, 0x1f621, 0x1f9d0,
/* silhouettes */ 0x1f47b, 0x1f464, 0x1f465, 0x1f5e3,
/* people */ 0x1f466, 0x1f467, 0x1f468, 0x1f469, 0x1f474, 0x1f475, 0x1f46a,
/* hands */ 0x1f44d, 0x1f44e, 0x1f4aa, 0x270d
}),
};
private static final int CUSTOM_GLYPHS_ID = 1;
private static boolean fontIsChecked = false;
private static final Boolean lockGuard = false;
private static final SparseArray<CacheMarker> emojiCache = new SparseArray<>();
private static class EmojiSet {
public int tabSymbol;
public int remaining;
public int[] symbols;
EmojiSet(final int tabSymbol, final int[] symbols) {
this.tabSymbol = tabSymbol;
this.remaining = symbols.length;
this.symbols = symbols;
}
}
private EmojiUtils() {
// utility class
}
public static void selectEmojiPopup(final Context context, final int currentValue, @DrawableRes final int defaultRes, final Action1<Integer> setNewCacheIcon) {
// calc sizes for markers
final Pair<Integer, Integer> markerDimensionsTemp = DisplayUtils.getDrawableDimensions(context.getResources(), R.drawable.ic_menu_filter);
final int markerAvailable = (int) (markerDimensionsTemp.first * 0.5);
final Pair<Integer, Integer> markerDimensions = new Pair<>(markerAvailable, markerAvailable);
final EmojiPaint paint = new EmojiPaint(context.getResources(), markerDimensions, markerAvailable, 0, DisplayUtils.calculateMaxFontsize(35, 10, 150, markerAvailable));
// fill dynamic EmojiSet
prefillCustomCircles(0);
// check EmojiSet for characters not supported on this device
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
synchronized (lockGuard) {
if (!fontIsChecked) {
final Paint checker = new TextPaint();
checker.setTypeface(Typeface.DEFAULT);
for (EmojiSet symbol : symbols) {
int iPosNeu = 0;
for (int i = 0; i < symbol.symbols.length; i++) {
if (i != iPosNeu) {
symbol.symbols[iPosNeu] = symbol.symbols[i];
}
if ((symbol.symbols[i] >= CUSTOM_ICONS_START && symbol.symbols[i] <= CUSTOM_ICONS_END) || checker.hasGlyph(new String(Character.toChars(symbol.symbols[i])))) {
iPosNeu++;
}
}
symbol.remaining = iPosNeu;
}
fontIsChecked = true;
}
}
}
// create dialog
final EmojiselectorBinding dialogView = EmojiselectorBinding.inflate(LayoutInflater.from(context));
final DialogTitleButtonButtonBinding customTitle = DialogTitleButtonButtonBinding.inflate(LayoutInflater.from(context));
final AlertDialog dialog = Dialogs.newBuilder(context)
.setView(dialogView.getRoot())
.setCustomTitle(customTitle.getRoot())
.create();
final int maxCols = DisplayUtils.calculateNoOfColumns(context, 60);
dialogView.emojiGrid.setLayoutManager(new GridLayoutManager(context, maxCols));
final EmojiViewAdapter gridAdapter = new EmojiViewAdapter(context, paint, symbols[0].symbols, symbols[0].remaining, currentValue, false, newCacheIcon -> onItemSelected(dialog, setNewCacheIcon, newCacheIcon));
dialogView.emojiGrid.setAdapter(gridAdapter);
dialogView.emojiOpacity.setLayoutManager(new GridLayoutManager(context, OPACITY_VALUES));
final int[] emojiOpacities = new int[OPACITY_VALUES];
emojiOpacities[0] = CUSTOM_ICONS_START_CIRCLES + 18;
for (int i = 1; i < OPACITY_VALUES; i++) {
emojiOpacities[i] = emojiOpacities[i - 1] + CUSTOM_SET_SIZE_PER_OPACITY;
}
final EmojiViewAdapter opacityAdapter = new EmojiViewAdapter(context, paint, emojiOpacities, emojiOpacities.length, emojiOpacities[0], true, newgroup -> {
final int newOpacity = (newgroup - CUSTOM_ICONS_START_CIRCLES) / CUSTOM_SET_SIZE_PER_OPACITY;
prefillCustomCircles(newOpacity);
gridAdapter.notifyDataSetChanged();
});
dialogView.emojiOpacity.setAdapter(opacityAdapter);
dialogView.emojiGroups.setLayoutManager(new GridLayoutManager(context, symbols.length));
final int[] emojiGroups = new int[symbols.length];
for (int i = 0; i < symbols.length; i++) {
emojiGroups[i] = symbols[i].tabSymbol;
}
final EmojiViewAdapter groupsAdapter = new EmojiViewAdapter(context, paint, emojiGroups, emojiGroups.length, symbols[0].tabSymbol, true, newgroup -> {
int newGroupId = 0;
for (int i = 0; i < symbols.length; i++) {
if (symbols[i].tabSymbol == newgroup) {
gridAdapter.setData(symbols[i].symbols, symbols[i].remaining);
newGroupId = i;
}
dialogView.emojiOpacity.setVisibility(newGroupId == CUSTOM_GLYPHS_ID ? View.VISIBLE : View.GONE);
}
});
dialogView.emojiGroups.setAdapter(groupsAdapter);
dialogView.emojiLru.setLayoutManager(new GridLayoutManager(context, maxCols));
final int[] lru = EmojiLRU.getLRU();
final EmojiViewAdapter lruAdapter = new EmojiViewAdapter(context, paint, lru, lru.length, 0, false, newCacheIcon -> onItemSelected(dialog, setNewCacheIcon, newCacheIcon));
dialogView.emojiLru.setAdapter(lruAdapter);
customTitle.dialogTitleTitle.setText(R.string.select_icon);
// right button displays current value; clicking simply closes the dialog
customTitle.dialogButton2.setVisibility(View.VISIBLE);
if (currentValue == -1) {
customTitle.dialogButton2.setImageResource(R.drawable.ic_menu_mark);
} else if (currentValue != 0) {
customTitle.dialogButton2.setImageDrawable(getEmojiDrawable(paint, currentValue));
} else if (defaultRes != 0) {
customTitle.dialogButton2.setImageResource(defaultRes);
}
customTitle.dialogButton2.setOnClickListener(v -> dialog.dismiss());
// left button displays default value (if different from current value)
if (currentValue != 0 && defaultRes != currentValue) {
customTitle.dialogButton1.setVisibility(View.VISIBLE);
customTitle.dialogButton1.setImageResource(defaultRes == 0 ? R.drawable.ic_menu_reset : defaultRes);
customTitle.dialogButton1.setOnClickListener(v -> {
setNewCacheIcon.call(0);
dialog.dismiss();
});
}
dialog.show();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Dialogs.basicOneTimeMessage(context, OneTimeDialogs.DialogType.MISSING_UNICODE_CHARACTERS);
}
}
private static void onItemSelected(final AlertDialog dialog, final Action1<Integer> callback, final int selectedValue) {
dialog.dismiss();
EmojiLRU.add(selectedValue);
callback.call(selectedValue);
}
private static void prefillCustomCircles(final int opacity) {
for (int i = 0; i < CUSTOM_SET_SIZE_PER_OPACITY; i++) {
symbols[CUSTOM_GLYPHS_ID].symbols[i] = CUSTOM_ICONS_START_CIRCLES + i + opacity * CUSTOM_SET_SIZE_PER_OPACITY;
}
}
private static class EmojiViewAdapter extends RecyclerView.Adapter<EmojiViewAdapter.ViewHolder> {
private int[] data;
private int remaining;
private final LayoutInflater inflater;
private final Action1<Integer> callback;
private final EmojiPaint paint;
private int currentValue = 0;
private final boolean highlightCurrent;
EmojiViewAdapter(final Context context, final EmojiPaint paint, final int[] data, final int remaining, final int currentValue, final boolean hightlightCurrent, final Action1<Integer> callback) {
this.inflater = LayoutInflater.from(context);
this.paint = paint;
this.setData(data, remaining);
this.currentValue = currentValue;
this.highlightCurrent = hightlightCurrent;
this.callback = callback;
}
public void setData(final int[] data, final int remaining) {
this.data = data;
this.remaining = remaining;
notifyDataSetChanged();
}
@Override
@NonNull
public EmojiViewAdapter.ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
final View view = inflater.inflate(R.layout.emojiselector_item, parent, false);
return new EmojiViewAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final EmojiViewAdapter.ViewHolder holder, final int position) {
if (data[position] >= CUSTOM_ICONS_START && data[position] <= CUSTOM_ICONS_END) {
holder.iv.setImageDrawable(EmojiUtils.getEmojiDrawable(paint, data[position]));
holder.iv.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.GONE);
} else {
holder.tv.setText(getEmojiAsString(data[position]));
holder.iv.setVisibility(View.GONE);
holder.tv.setVisibility(View.VISIBLE);
}
if (highlightCurrent) {
holder.sep.setVisibility(currentValue == data[position] ? View.VISIBLE : View.INVISIBLE);
}
holder.itemView.setOnClickListener(v -> {
currentValue = data[position];
callback.call(currentValue);
if (highlightCurrent) {
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return remaining;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView tv;
protected ImageView iv;
protected View sep;
ViewHolder(final View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.info_text);
iv = itemView.findViewById(R.id.info_drawable);
sep = itemView.findViewById(R.id.separator);
}
}
}
/**
* get emoji string from codepoint
* @param emoji codepoint of the emoji to display
* @return string emoji with protection from rendering as black-and-white glyphs
*/
private static String getEmojiAsString(final int emoji) {
return new String(Character.toChars(emoji)) + new String(Character.toChars(VariationSelectorEmoji));
}
/**
* builds a drawable the size of a marker with a given text
* @param paint - paint data structure for Emojis
* @param emoji codepoint of the emoji to display
* @return drawable bitmap with text on it
*/
@NonNull
private static BitmapDrawable getEmojiDrawableHelper(final EmojiPaint paint, final int emoji) {
final Bitmap bm = Bitmap.createBitmap(paint.bitmapDimensions.first, paint.bitmapDimensions.second, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bm);
if (emoji >= CUSTOM_ICONS_START && emoji <= CUSTOM_ICONS_END) {
final int radius = paint.availableSize / 2;
final Paint cPaint = new Paint();
// calculate circle details
final int v = emoji - CUSTOM_ICONS_START_CIRCLES;
final int aIndex = v / (COLOR_VALUES * COLOR_VALUES * COLOR_VALUES);
final int rIndex = (v / (COLOR_VALUES * COLOR_VALUES)) % COLOR_VALUES;
final int gIndex = (v / COLOR_VALUES) % COLOR_VALUES;
final int bIndex = v % COLOR_VALUES;
final int color = Color.argb(
255 - (aIndex * OPACITY_SPREAD),
COLOR_OFFSET + rIndex * COLOR_SPREAD,
COLOR_OFFSET + gIndex * COLOR_SPREAD,
COLOR_OFFSET + bIndex * COLOR_SPREAD);
cPaint.setColor(color);
cPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle((int) (paint.bitmapDimensions.first / 2), (int) (paint.bitmapDimensions.second / 2) - paint.offsetTop, radius, cPaint);
} else {
final String text = getEmojiAsString(emoji);
final TextPaint tPaint = new TextPaint();
tPaint.setTextSize(paint.fontsize);
final StaticLayout lsLayout = new StaticLayout(text, tPaint, paint.availableSize, Layout.Alignment.ALIGN_CENTER, 1, 0, false);
canvas.translate((int) ((paint.bitmapDimensions.first - lsLayout.getWidth()) / 2), (int) ((paint.bitmapDimensions.second - lsLayout.getHeight()) / 2) - paint.offsetTop);
lsLayout.draw(canvas);
canvas.save();
canvas.restore();
}
return new BitmapDrawable(paint.res, bm);
}
/**
* get a drawable the size of a marker with a given text (either from cache or freshly built)
* @param paint - paint data structure for Emojis
* @param emoji codepoint of the emoji to display
* @return drawable bitmap with text on it
*/
@NonNull
public static BitmapDrawable getEmojiDrawable(final EmojiPaint paint, final int emoji) {
final int hashcode = new HashCodeBuilder()
.append(paint.bitmapDimensions.first)
.append(paint.availableSize)
.append(paint.fontsize)
.append(emoji)
.toHashCode();
synchronized (emojiCache) {
CacheMarker marker = emojiCache.get(hashcode);
if (marker == null) {
marker = new CacheMarker(hashcode, getEmojiDrawableHelper(paint, emoji));
emojiCache.put(hashcode, marker);
}
return (BitmapDrawable) marker.getDrawable();
}
}
/**
* configuration for getEmojiDrawable
*/
public static class EmojiPaint {
public final Resources res;
public final Pair<Integer, Integer> bitmapDimensions;
public final int availableSize;
public final int offsetTop;
public final int fontsize;
EmojiPaint(final Resources res, final Pair<Integer, Integer> bitmapDimensions, final int availableSize, final int offsetTop, final int fontsize) {
this.res = res;
this.bitmapDimensions = bitmapDimensions;
this.availableSize = availableSize;
this.offsetTop = offsetTop;
this.fontsize = fontsize;
}
}
}
|
package org.languagetool.dev.bigdata;
import org.languagetool.AnalyzedSentence;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.chunking.Chunker;
import org.languagetool.dev.dumpcheck.*;
import org.languagetool.dev.eval.FMeasure;
import org.languagetool.language.English;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.languagemodel.LuceneLanguageModel;
import org.languagetool.rules.ConfusionProbabilityRule;
import org.languagetool.rules.ConfusionSet;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.en.EnglishConfusionProbabilityRule;
import org.languagetool.tagging.Tagger;
import org.languagetool.tagging.xx.DemoTagger;
import org.languagetool.tools.StringTools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Locale.ENGLISH;
/**
* Loads sentences with a homophone (e.g. there/their) from Wikipedia or confusion set files
* and evaluates EnglishConfusionProbabilityRule with them.
*
* @since 3.0
* @author Daniel Naber
*/
class ConfusionRuleEvaluator {
private static final String TOKEN = "there";
private static final String TOKEN_HOMOPHONE = "their";
private static final int FACTOR = 100;
private static final int NGRAM_LEVEL = 3;
private static final int MAX_SENTENCES = 1000;
private final Language language;
private final ConfusionProbabilityRule rule;
private final int grams;
private int truePositives = 0;
private int trueNegatives = 0;
private int falsePositives = 0;
private int falseNegatives = 0;
private boolean verbose = true;
ConfusionRuleEvaluator(Language language, LanguageModel languageModel, int grams) {
this.language = language;
this.rule = new EnglishConfusionProbabilityRule(JLanguageTool.getMessageBundle(), languageModel, language, grams);
this.grams = grams;
}
void setVerboseMode(boolean verbose) {
this.verbose = verbose;
}
String run(List<String> inputsOrDir, String token, String homophoneToken, long factor, int maxSentences) throws IOException {
truePositives = 0;
trueNegatives = 0;
falsePositives = 0;
falseNegatives = 0;
rule.setConfusionSet(new ConfusionSet(factor, homophoneToken, token));
List<Sentence> allTokenSentences = getRelevantSentences(inputsOrDir, token, maxSentences);
// Load the sentences with a homophone and later replace it so we get error sentences:
List<Sentence> allHomophoneSentences = getRelevantSentences(inputsOrDir, homophoneToken, maxSentences);
evaluate(allTokenSentences, true, token, homophoneToken);
evaluate(allTokenSentences, false, homophoneToken, token);
evaluate(allHomophoneSentences, false, token, homophoneToken);
evaluate(allHomophoneSentences, true, homophoneToken, token);
return printEvalResult(allTokenSentences, allHomophoneSentences, inputsOrDir);
}
@SuppressWarnings("ConstantConditions")
private void evaluate(List<Sentence> sentences, boolean isCorrect, String token, String homophoneToken) throws IOException {
println("======================");
printf("Starting evaluation on " + sentences.size() + " sentences with %s/%s:\n", token, homophoneToken);
JLanguageTool lt = new JLanguageTool(language);
for (Sentence sentence : sentences) {
String textToken = isCorrect ? token : homophoneToken;
String plainText = sentence.getText();
String replacement = plainText.indexOf(textToken) == 0 ? StringTools.uppercaseFirstChar(token) : token;
String replacedTokenSentence = isCorrect ? plainText : plainText.replaceFirst("(?i)\\b" + textToken + "\\b", replacement);
AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(replacedTokenSentence);
RuleMatch[] matches = rule.match(analyzedSentence);
boolean consideredCorrect = matches.length == 0;
String displayStr = plainText.replaceFirst("(?i)\\b" + textToken + "\\b", "**" + replacement + "**");
if (consideredCorrect && isCorrect) {
trueNegatives++;
} else if (!consideredCorrect && isCorrect) {
falsePositives++;
println("false positive: " + displayStr);
} else if (consideredCorrect && !isCorrect) {
//println("false negative: " + displayStr);
falseNegatives++;
} else {
truePositives++;
//System.out.println("true positive: " + displayStr);
}
}
}
private String printEvalResult(List<Sentence> allTokenSentences, List<Sentence> allHomophoneSentences, List<String> inputsOrDir) {
float precision = (float) truePositives / (truePositives + falsePositives);
float recall = (float) truePositives / (truePositives + falseNegatives);
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String summary = String.format(ENGLISH, "p=%.3f, r=%.3f, %d, %dgrams, %s",
precision, recall, allTokenSentences.size() + allHomophoneSentences.size(), grams, date);
if (verbose) {
int sentences = allTokenSentences.size() + allHomophoneSentences.size();
System.out.println("======================");
System.out.println("Evaluation results for " + TOKEN + "/" + TOKEN_HOMOPHONE
+ " with " + sentences + " sentences as of " + new Date() + ":");
System.out.printf(ENGLISH, " Precision: %.3f (%d false positives)\n", precision, falsePositives);
System.out.printf(ENGLISH, " Recall: %.3f (%d false negatives)\n", recall, falseNegatives);
double fMeasure = FMeasure.getWeightedFMeasure(precision, recall);
System.out.printf(ENGLISH, " F-measure: %.3f (beta=0.5)\n", fMeasure);
System.out.printf(ENGLISH, " Matches: %d (true positives)\n", truePositives);
System.out.printf(ENGLISH, " Inputs: %s\n", inputsOrDir);
System.out.printf(" Summary: " + summary + "\n");
}
return summary;
}
private List<Sentence> getRelevantSentences(List<String> inputs, String token, int maxSentences) throws IOException {
List<Sentence> sentences = new ArrayList<>();
for (String input : inputs) {
if (new File(input).isDirectory()) {
File file = new File(input, token + ".txt");
if (!file.exists()) {
throw new RuntimeException("File with example sentences not found: " + file);
}
try (FileInputStream fis = new FileInputStream(file)) {
SentenceSource sentenceSource = new PlainTextSentenceSource(fis, language);
sentences = getSentencesFromSource(inputs, token, maxSentences, sentenceSource);
}
} else {
SentenceSource sentenceSource = MixingSentenceSource.create(inputs, language);
sentences = getSentencesFromSource(inputs, token, maxSentences, sentenceSource);
}
}
return sentences;
}
private List<Sentence> getSentencesFromSource(List<String> inputs, String token, int maxSentences, SentenceSource sentenceSource) {
List<Sentence> sentences = new ArrayList<>();
Pattern pattern = Pattern.compile(".*\\b" + token.toLowerCase() + "\\b.*");
while (sentenceSource.hasNext()) {
Sentence sentence = sentenceSource.next();
Matcher matcher = pattern.matcher(sentence.getText().toLowerCase());
if (matcher.matches()) {
sentences.add(sentence);
if (sentences.size() % 250 == 0) {
println("Loaded sentence " + sentences.size() + " with '" + token + "' from " + inputs);
}
if (sentences.size() >= maxSentences) {
break;
}
}
}
println("Loaded " + sentences.size() + " sentences with '" + token + "' from " + inputs);
return sentences;
}
private void println(String msg) {
if (verbose) {
System.out.println(msg);
}
}
private void printf(String msg, String... args) {
if (verbose) {
System.out.printf(msg, args);
}
}
public static void main(String[] args) throws IOException {
if (args.length < 3 || args.length > 4) {
System.err.println("Usage: " + ConfusionRuleEvaluator.class.getSimpleName()
+ " <langCode> <languageModelTopDir> <wikipediaXml|tatoebaFile|dir>...");
System.err.println(" <languageModelTopDir> is a directory with sub-directories '1grams', '2grams' and '3grams' with Lucene indexes");
System.err.println(" <wikipediaXml|tatoebaFile|dir> either a Wikipedia XML dump, or a Tatoeba file or");
System.err.println(" a directory with example sentences (where <word>.txt contains only the sentences for <word>).");
System.err.println(" You can specify both a Wikipedia file and a Tatoeba file.");
System.exit(1);
}
long startTime = System.currentTimeMillis();
Language lang = new EnglishLight();
LanguageModel languageModel = new LuceneLanguageModel(new File(args[1]));
List<String> inputsFiles = new ArrayList<>();
inputsFiles.add(args[2]);
if (args.length >= 4) {
inputsFiles.add(args[3]);
}
ConfusionRuleEvaluator generator = new ConfusionRuleEvaluator(lang, languageModel, NGRAM_LEVEL);
generator.run(inputsFiles, TOKEN, TOKEN_HOMOPHONE, FACTOR, MAX_SENTENCES);
long endTime = System.currentTimeMillis();
System.out.println("Time: " + (endTime-startTime)+"ms");
}
static class EnglishLight extends English {
private DemoTagger tagger;
@Override
public String getName() {
return "English Light";
}
@Override
public Tagger getTagger() {
if (tagger == null) {
tagger = new DemoTagger();
}
return tagger;
}
@Override
public Chunker getChunker() {
return null;
}
}
}
|
package cgeo.geocaching.utils;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SelectTrackFileActivity;
import cgeo.geocaching.files.GPXTrackImporter;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.settings.Settings;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import static android.app.Activity.RESULT_OK;
import androidx.annotation.Nullable;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
public class TrackUtils {
private static final int REQUEST_CODE_GET_TRACKFILE = 47121;
public static class Track {
private String trackName;
private ArrayList<Geopoint> track;
public Track() {
trackName = "";
track = new ArrayList<>();
}
public String getTrackName() {
return trackName;
}
public void setTrackName(final String trackName) {
this.trackName = trackName;
}
public ArrayList<Geopoint> getTrack() {
return track;
}
public int getSize() {
return track.size();
}
public void add(final Geopoint geopoint) {
track.add(geopoint);
}
}
public static class Tracks {
private ArrayList<Track> tracks;
public Tracks() {
tracks = new ArrayList<>();
}
public void add(final Track track) {
tracks.add(track);
}
public int getSize() {
return tracks.size();
}
public Track get(final int i) {
return tracks.get(i);
}
}
public interface TrackUpdaterSingle {
void updateTrack(Track track);
}
public interface TrackUpdaterMulti {
void updateTracks(Tracks tracks);
}
protected TrackUtils() {
}
/**
* Enable/disable track related menu entries
* @param menu menu to be configured
*/
public static void onPrepareOptionsMenu(final Menu menu) {
final boolean trackfileSet = StringUtils.isNotBlank(Settings.getTrackFile());
menu.findItem(R.id.menu_hide_track).setVisible(trackfileSet);
menu.findItem(R.id.menu_hide_track).setChecked(Settings.isHideTrack());
}
/**
* Check if selected menu entry is for "load track" or hide/unhide track
* @param activity calling activity
* @param id menu entry id
* @return true, if selected menu entry is track related and consumed / false else
*/
public static boolean onOptionsItemSelected(final Activity activity, final int id, final Runnable hideOptionsChanged) {
if (id == R.id.menu_load_track) {
final Intent intent = new Intent(activity, SelectTrackFileActivity.class);
activity.startActivityForResult(intent, REQUEST_CODE_GET_TRACKFILE);
return true;
} else if (id == R.id.menu_hide_track) {
Settings.setHideTrack(!Settings.isHideTrack());
hideOptionsChanged.run();
return true;
} else {
return false;
}
}
/**
* Check if current activity result is a selected track file
* @param requestCode current requestCode to check
* @param resultCode current resultCode to check
* @param data additional intent data delivered
* @return true, if successfully selected track file / false else
*/
public static boolean onActivityResult(final int requestCode, final int resultCode, final Intent data, @Nullable final TrackUpdaterMulti updateTracks) {
if (requestCode == REQUEST_CODE_GET_TRACKFILE && resultCode == RESULT_OK && data.hasExtra(Intents.EXTRA_GPX_FILE)) {
final String filename = data.getStringExtra(Intents.EXTRA_GPX_FILE);
if (null != filename) {
final File file = new File(filename);
if (!file.isDirectory()) {
Settings.setTrackFile(filename);
if (null != updateTracks) {
loadTracks(updateTracks);
}
}
}
return true;
}
return false;
}
public static void loadTracks(final TrackUpdaterMulti updateTracks) {
final String trackfile = Settings.getTrackFile();
if (null != trackfile) {
GPXTrackImporter.doImport(new File(trackfile), updateTracks);
}
}
}
|
package org.languagetool.openoffice;
import java.util.ArrayList;
import java.util.List;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.text.TextMarkupType;
import com.sun.star.text.XFlatParagraph;
import com.sun.star.text.XFlatParagraphIterator;
import com.sun.star.text.XFlatParagraphIteratorProvider;
import com.sun.star.text.XParagraphCursor;
import com.sun.star.text.XText;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextViewCursor;
import com.sun.star.text.XTextViewCursorSupplier;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/**
* Information about LibreOffice/OpenOffice documents
* needed for full text search
* @since 4.0
*
* @author Fred Kruse
*/
public class LODocument {
/** Returns the current XDesktop */
private static XDesktop getCurrentDesktop(XComponentContext xContext) {
if(xContext == null) return null;
XMultiComponentFactory xMCF = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
xContext.getServiceManager());
Object desktop = null;
try {
desktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
} catch (Exception e) {
return null;
}
return (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
}
/** Returns the current XComponent */
private static XComponent getCurrentComponent(XComponentContext xContext) {
XDesktop xdesktop = getCurrentDesktop(xContext);
if(xdesktop == null) return null;
else return (XComponent) xdesktop.getCurrentComponent();
}
/** Returns the current text document (if any) */
private static XTextDocument getCurrentDocument(XComponentContext xContext) {
XComponent curcomp = getCurrentComponent(xContext);
if (curcomp == null) return null;
else return (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, curcomp);
}
/** Returns the text cursor (if any) */
private static XTextCursor getCursor(XComponentContext xContext) {
XTextDocument curdoc = getCurrentDocument(xContext);
if (curdoc == null) return null;
XText xText = curdoc.getText();
if (xText == null) return null;
else return xText.createTextCursor();
}
/** Returns ParagraphCursor from TextCursor */
private static XParagraphCursor getParagraphCursor(XComponentContext xContext) {
XTextCursor xcursor = getCursor(xContext);
if(xcursor == null) return null;
return (XParagraphCursor) UnoRuntime.queryInterface(XParagraphCursor.class, xcursor);
}
/** Returns Number of all Paragraphs of Document without footnotes etc. */
public static int getNumberOfAllTextParagraphs(XComponentContext xContext) {
XParagraphCursor xpcursor = getParagraphCursor(xContext);
if (xpcursor == null) return 0;
xpcursor.gotoStart(false);
int npara = 1;
while (xpcursor.gotoNextParagraph(false)) npara++;
return npara;
}
/** Returns ViewCursor */
private static XTextViewCursor getViewCursor(XComponentContext xContext) {
XDesktop xDesktop = getCurrentDesktop(xContext);
if(xDesktop == null) return null;
XComponent xCurrentComponent = xDesktop.getCurrentComponent();
if(xCurrentComponent == null) return null;
XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent);
if(xModel == null) return null;
XController xController = xModel.getCurrentController();
if(xController == null) return null;
XTextViewCursorSupplier xViewCursorSupplier =
UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController);
if(xViewCursorSupplier == null) return null;
return xViewCursorSupplier.getViewCursor();
}
/** Returns Paragraph number under ViewCursor */
public static int getViewCursorParagraph(XComponentContext xContext) {
XTextViewCursor xViewCursor = getViewCursor(xContext);
if(xViewCursor == null) return -4;
XText xDocumentText = xViewCursor.getText();
if(xDocumentText == null) return -3;
XTextCursor xModelCursor = xDocumentText.createTextCursorByRange(xViewCursor.getStart());
if(xModelCursor == null) return -2;
XParagraphCursor xParagraphCursor = (XParagraphCursor)UnoRuntime.queryInterface(
XParagraphCursor.class, xModelCursor);
if(xParagraphCursor == null) return -1;
int pos = 0;
while (xParagraphCursor.gotoPreviousParagraph(false)) pos++;
return pos;
}
/** Returns Number of Paragraph from FlatParagaph */
public static int getNumFlatParagraphs(XComponentContext xContext) {
XComponent xCurrentComponent = getCurrentComponent(xContext);
if(xCurrentComponent == null) return -3;
XFlatParagraphIteratorProvider xFlatParaItPro
= UnoRuntime.queryInterface(XFlatParagraphIteratorProvider.class, xCurrentComponent);
if(xFlatParaItPro == null) return -2;
try {
XFlatParagraphIterator xFlatParaIter
= xFlatParaItPro.getFlatParagraphIterator(TextMarkupType.PROOFREADING, true);
XFlatParagraph xFlatPara = xFlatParaIter.getLastPara();
if(xFlatPara == null) return -1;
int pos = -1;
while (xFlatPara != null) {
xFlatPara = xFlatParaIter.getParaBefore(xFlatPara);
pos++;
}
return pos;
} catch (Throwable t) {
Main.showError(t);
return 0;
}
}
/** Returns all Paragraphs of Document */
public static List<String> getAllParagraphs(XComponentContext xContext) {
List<String> allParas = new ArrayList<String>();
XFlatParagraph lastFlatPara = null;
XComponent xCurrentComponent = getCurrentComponent(xContext);
if(xCurrentComponent == null) return allParas;
XFlatParagraphIteratorProvider xFlatParaItPro = UnoRuntime.queryInterface(XFlatParagraphIteratorProvider.class, xCurrentComponent);
if(xFlatParaItPro == null) return allParas;
try {
XFlatParagraphIterator xFlatParaIter = xFlatParaItPro.getFlatParagraphIterator(TextMarkupType.PROOFREADING, true);
XFlatParagraph xFlatPara = xFlatParaIter.getLastPara();
if(xFlatPara == null) return allParas;
while (xFlatPara != null) {
lastFlatPara = xFlatPara;
xFlatPara = xFlatParaIter.getParaBefore(xFlatPara);
}
xFlatPara = lastFlatPara;
while (xFlatPara != null) {
allParas.add(xFlatPara.getText());
xFlatPara = xFlatParaIter.getParaAfter(xFlatPara);
}
} catch (Throwable t) {
Main.showError(t);
}
return allParas;
}
/** Returns Number of all Paragraphs of Document / Returns < 0 on Error */
public static int getNumberOfAllParagraphs(XComponentContext xContext) {
XFlatParagraph lastFlatPara = null;
XComponent xCurrentComponent = getCurrentComponent(xContext);
if(xCurrentComponent == null) return -3;
XFlatParagraphIteratorProvider xFlatParaItPro
= UnoRuntime.queryInterface(XFlatParagraphIteratorProvider.class, xCurrentComponent);
if(xFlatParaItPro == null) return -2;
try {
XFlatParagraphIterator xFlatParaIter
= xFlatParaItPro.getFlatParagraphIterator(TextMarkupType.PROOFREADING, true);
XFlatParagraph xFlatPara = xFlatParaIter.getLastPara();
if(xFlatPara == null) return -1;
lastFlatPara = xFlatPara;
int num = 0;
while (xFlatPara != null) {
xFlatPara = xFlatParaIter.getParaBefore(xFlatPara);
num++;
}
xFlatPara = lastFlatPara;
num
while (xFlatPara != null) {
xFlatPara = xFlatParaIter.getParaAfter(xFlatPara);
num++;
}
return num;
} catch (Throwable t) {
Main.showError(t);
return -4;
}
}
}
|
package stroom.statistics.server.stroomstats.internal;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import stroom.connectors.kafka.StroomKafkaProducer;
import stroom.connectors.kafka.StroomKafkaProducerFactoryService;
import stroom.connectors.kafka.StroomKafkaProducerRecord;
import stroom.node.server.StroomPropertyService;
import stroom.query.api.v2.DocRef;
import stroom.statistics.internal.InternalStatisticEvent;
import stroom.statistics.internal.InternalStatisticsService;
import stroom.stats.schema.v3.ObjectFactory;
import stroom.stats.schema.v3.Statistics;
import stroom.stats.schema.v3.TagType;
import javax.inject.Inject;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.StringWriter;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
@SuppressWarnings("unused")
@Component
class StroomStatsInternalStatisticsService implements InternalStatisticsService {
static final String PROP_KEY_DOC_REF_TYPE = "stroom.services.stroomStats.docRefType";
static final String PROP_KEY_PREFIX_KAFKA_TOPICS = "stroom.services.stroomStats.kafkaTopics.";
private static final Logger LOGGER = LoggerFactory.getLogger(StroomStatsInternalStatisticsService.class);
private static final Class<Statistics> STATISTICS_CLASS = Statistics.class;
private static final TimeZone TIME_ZONE_UTC = TimeZone.getTimeZone(ZoneId.from(ZoneOffset.UTC));
private final StroomKafkaProducer stroomKafkaProducer;
private final StroomPropertyService stroomPropertyService;
private final String docRefType;
private final JAXBContext jaxbContext;
private final DatatypeFactory datatypeFactory;
// If we move to a 'named' kafka config later, change the java.util.function.Supplier to a java.util.function.Function
StroomStatsInternalStatisticsService(final StroomKafkaProducer stroomKafkaProducer,
final StroomPropertyService stroomPropertyService) {
this.stroomPropertyService = stroomPropertyService;
this.stroomKafkaProducer = stroomKafkaProducer;
this.docRefType = stroomPropertyService.getProperty(PROP_KEY_DOC_REF_TYPE);
try {
this.jaxbContext = JAXBContext.newInstance(Statistics.class);
} catch (JAXBException e) {
throw new RuntimeException(String.format("Unable to create JAXBContext for class %s",
STATISTICS_CLASS.getCanonicalName()), e);
}
try {
this.datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new RuntimeException("Unable to create new DatatypeFactory instance", e);
}
}
@Inject
StroomStatsInternalStatisticsService(final StroomKafkaProducerFactoryService stroomKafkaProducerFactory,
final StroomPropertyService stroomPropertyService) {
this(stroomKafkaProducerFactory.getProducer(exception -> LOGGER.error("Unable to call function on Kafka producer!", exception))
, stroomPropertyService);
}
@Override
public void putEvents(final Map<DocRef, List<InternalStatisticEvent>> eventsMap) {
Preconditions.checkNotNull(eventsMap);
try {
//We work on the basis that a stat may or may not have a valid datasource (StatisticConfiguration) but we
//will let stroom-stats worry about that and just fire what we have at kafka
eventsMap.entrySet().stream()
.filter(entry ->
!entry.getValue().isEmpty())
.forEach(entry -> {
DocRef docRef = entry.getKey();
List<InternalStatisticEvent> events = entry.getValue();
String statName = docRef.getName();
//all have same name so have same type
String topic = getTopic(events.get(0).getType());
String message = buildMessage(docRef, events);
StroomKafkaProducerRecord<String, String> producerRecord =
new StroomKafkaProducerRecord.Builder<String, String>()
.topic(topic)
.key(docRef.getUuid())
.value(message)
.build();
stroomKafkaProducer.send(producerRecord, false, exception -> {
throw new RuntimeException(String.format(
"Error sending %s internal stats with name %s to kafka on topic %s, due to (%s)",
events.size(), statName, topic, exception.getMessage()), exception);
});
});
} finally {
//any problems with the send will call the exceptionhandler above to be triggered at this point
stroomKafkaProducer.flush();
}
}
private String buildMessage(final DocRef docRef, final List<InternalStatisticEvent> events) {
Statistics statistics = new Statistics();
Preconditions.checkNotNull(events).stream()
.map(event -> internalStatisticMapper(docRef, event))
.forEach(statistic -> statistics.getStatistic().add(statistic));
return marshall(statistics);
}
private Statistics.Statistic internalStatisticMapper(final DocRef docRef,
final InternalStatisticEvent internalStatisticEvent) {
Preconditions.checkNotNull(internalStatisticEvent);
ObjectFactory objectFactory = new ObjectFactory();
Statistics.Statistic statistic = objectFactory.createStatisticsStatistic();
Statistics.Statistic.Key key = objectFactory.createStatisticsStatisticKey();
key.setValue(docRef.getUuid());
key.setStatisticName(docRef.getName());
statistic.setKey(key);
statistic.setTime(toXMLGregorianCalendar(internalStatisticEvent.getTimeMs()));
InternalStatisticEvent.Type type = internalStatisticEvent.getType();
switch (internalStatisticEvent.getType()) {
case COUNT:
statistic.setCount(getValueAsType(type,
Long.class,
internalStatisticEvent.getValue()));
break;
case VALUE:
statistic.setValue(getValueAsType(type,
Double.class,
internalStatisticEvent.getValue()));
break;
default:
throw new IllegalArgumentException("Unexpected type " + type.toString());
}
if (!internalStatisticEvent.getTags().isEmpty()) {
Statistics.Statistic.Tags tags = new Statistics.Statistic.Tags();
internalStatisticEvent.getTags().entrySet().stream()
.map(entry -> {
TagType tag = new TagType();
tag.setName(entry.getKey());
tag.setValue(entry.getValue());
return tag;
})
.forEach(tag -> tags.getTag().add(tag));
statistic.setTags(tags);
}
return statistic;
}
private <T> T getValueAsType(final InternalStatisticEvent.Type type, final Class<T> clazz, final Object value) {
try {
return clazz.cast(value);
} catch (Exception e) {
throw new RuntimeException(String.format("Statistic of type %s has value of wrong type %s",
type, clazz.getCanonicalName()));
}
}
private XMLGregorianCalendar toXMLGregorianCalendar(final long timeMs) {
GregorianCalendar gregorianCalendar = new GregorianCalendar(TIME_ZONE_UTC);
gregorianCalendar.setTimeInMillis(timeMs);
return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
}
private String marshall(final Statistics statistics) {
StringWriter stringWriter = new StringWriter();
try {
getMarshaller().marshal(statistics, stringWriter);
} catch (JAXBException e) {
throw new RuntimeException("Error marshalling Statistics object", e);
}
return stringWriter.toString();
}
private Marshaller getMarshaller() {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
return marshaller;
} catch (JAXBException e) {
throw new RuntimeException("Error creating marshaller for class " + STATISTICS_CLASS.getCanonicalName());
}
}
private String getTopic(final InternalStatisticEvent.Type type) {
String propKey = PROP_KEY_PREFIX_KAFKA_TOPICS + type.toString().toLowerCase();
String topic = stroomPropertyService.getProperty(propKey);
if (Strings.isNullOrEmpty(topic)) {
throw new RuntimeException(
String.format("Missing value for property %s, unable to send internal statistics", topic));
}
return topic;
}
@Override
public String getDocRefType() {
return docRefType;
}
}
|
package net.finkn.inputspec.tools;
import net.finkn.inputspec.tools.types.Point;
import se.miun.itm.input.model.InPUTException;
import se.miun.itm.input.model.design.IDesign;
/**
* Helper for writing more concise tests.
* Exports common configurations and small functions that are common to
* multiple tests.
*/
public class Helper {
private static final GenTestCase genTest = GenTestCase.getInstance();
private static final SinkTestCase sinkTest = SinkTestCase.getInstance();
public static final ParamCfg pointParam = ParamCfg.builder()
.id("X").inclMin("10").inclMax("20").add()
.id("Y").inclMin("15").inclMax("25").add()
.structured()
.id("Point")
.build();
public static final MappingCfg pointMapping = MappingCfg.builder()
.infer(pointParam, Point.class)
.build();
public static ParamCfg.Builder pb() {
return ParamCfg.builder();
}
public static SinkTestCase sinkTest(ParamCfg.Builder builder) throws InPUTException {
return sinkTest.sink(Sink.fromParam(builder.build()));
}
public static GenTestCase genTest(ParamCfg.Builder builder) throws InPUTException {
return genTest.gen(Generator.fromParam(builder.build()));
}
public static GenTestCase genTest(String id, ParamCfg ... cfgs) throws InPUTException {
DesignSpaceCfg space = DesignSpaceCfg.builder().param(cfgs).build();
return genTest.gen(Generator.fromDesignSpace(space.getDesignSpace(), id));
}
public static IDesign design(ParamCfg ... params) throws InPUTException {
return DesignSpaceCfg.builder()
.param(params)
.build()
.getDesignSpace()
.nextDesign("Design");
}
}
|
package com.amatkivskiy.gitter.rx.sdk.converter;
import com.amatkivskiy.gitter.rx.sdk.model.response.UserResponse;
import com.google.gson.*;
import java.lang.reflect.Type;
public class UserJsonDeserializer implements JsonDeserializer<UserResponse> {
@Override
public UserResponse deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject element = null;
if (jsonElement.isJsonArray()) {
element = jsonElement.getAsJsonArray().get(0).getAsJsonObject();
} else {
element = jsonElement.getAsJsonObject();
}
String id = element.get("id") != null ? element.get("id").getAsString() : null;
Integer v = element.get("v") != null ? element.get("v").getAsInt() : null;
String username = element.get("username") != null ? element.get("username").getAsString() : null;
String avatarUrlSmall = element.get("avatarUrlSmall") != null ? element.get("avatarUrlSmall").getAsString() : null;
String avatarUrlMedium = element.get("avatarUrlMedium") != null ? element.get("avatarUrlMedium").getAsString() : null;
String gv = element.get("gv") != null ? element.get("gv").getAsString() : null;
String displayName = element.get("displayName") != null ? element.get("displayName").getAsString() : null;
String url = element.get("url") != null ? element.get("url").getAsString() : null;
return new UserResponse(id, v, username, avatarUrlSmall, gv, displayName, url, avatarUrlMedium);
}
}
|
package com.mindera.skeletoid.analytics.appenders;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import java.util.Map;
/**
* Interface for Analytics appenders
*/
public interface IAnalyticsAppender {
/**
* Enable analytics
*
* @param context Application context
*/
void enableAppender(Context context);
/**
* Disable analytics.
*/
void disableAppender();
/**
* Track app event
*
* @param eventName Event name
* @param analyticsPayload Generic analytics payload
*/
void trackEvent(String eventName, Map<String, Object> analyticsPayload);
/**
* Track app event
*
* @param eventName Event name
* @param analyticsPayload Generic analytics payload
*/
void trackEvent(String eventName, Bundle analyticsPayload);
/**
* Track app page hit
*
* @param activity Activity that represent
* @param screenName Screen name
* @param screenClassOverride Screen class override name
*/
void trackPageHit(Activity activity, String screenName, String screenClassOverride);
/**
* Get Analytics id (it should be unique within AnalyticsAppenders)
*/
String getAnalyticsId();
/**
* Sets the user ID
*
* @param userID ID of the user
*/
void setUserID(String userID);
/**
* Sets a custom property of the user
*
* @param name Property name
* @param value Property value
*/
void setUserProperty(String name, String value);
}
|
package org.xwiki.tool.extension.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.extension.Extension;
import org.xwiki.extension.MutableExtension;
import org.xwiki.extension.internal.ExtensionUtils;
import org.xwiki.extension.internal.converter.ExtensionIdConverter;
import org.xwiki.extension.repository.internal.ExtensionSerializer;
import org.xwiki.extension.repository.internal.local.DefaultLocalExtension;
import org.xwiki.properties.converter.Converter;
import org.xwiki.tool.extension.ExtensionOverride;
/**
* Base class for Maven plugins manipulating extensions.
*
* @version $Id$
* @since 8.4RC1
*/
public abstract class AbstractExtensionMojo extends AbstractMojo
{
/**
* The current Maven session being executed.
*/
@Parameter(defaultValue = "${session}", required = true, readonly = true)
protected MavenSession session;
/**
* Project builder -- builds a model from a pom.xml.
*/
@Component
protected ProjectBuilder projectBuilder;
@Parameter
protected List<ExtensionOverride> extensionOverrides;
protected ExtensionSerializer extensionSerializer;
protected Converter<Extension> extensionConverter;
protected void initializeComponents() throws MojoExecutionException
{
// Initialize ComponentManager
EmbeddableComponentManager componentManager = new EmbeddableComponentManager();
componentManager.initialize(this.getClass().getClassLoader());
// Initialize components
try {
this.extensionSerializer = componentManager.getInstance(ExtensionSerializer.class);
this.extensionConverter =
componentManager.getInstance(new DefaultParameterizedType(null, Converter.class, Extension.class));
} catch (ComponentLookupException e) {
throw new MojoExecutionException("Failed to load components", e);
}
}
protected MavenProject getMavenProject(Artifact artifact) throws MojoExecutionException
{
try {
ProjectBuildingRequest request = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest())
// We don't want to execute any plugin here
.setProcessPlugins(false)
// It's not this plugin job to validate this pom.xml
.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL)
// Use the repositories configured for the built project instead of the default Maven ones
.setRemoteRepositories(this.session.getCurrentProject().getRemoteArtifactRepositories());
// Note: build() will automatically get the POM artifact corresponding to the passed artifact.
ProjectBuildingResult result = this.projectBuilder.build(artifact, request);
return result.getProject();
} catch (ProjectBuildingException e) {
throw new MojoExecutionException(String.format("Failed to build project for [%s]", artifact), e);
}
}
protected Extension toExtension(Artifact artifact) throws MojoExecutionException
{
MavenProject mavenProject = getMavenProject(artifact);
return toExtension(mavenProject.getModel());
}
protected Extension toExtension(Model model)
{
return this.extensionConverter.convert(Extension.class, model);
}
protected void saveExtension(File path, Artifact artifact)
throws MojoExecutionException, IOException, ParserConfigurationException, TransformerException
{
// Get MavenProject instance
MavenProject mavenProject = getMavenProject(artifact);
saveExtension(path, mavenProject.getModel());
}
protected void saveExtension(File path, Model model)
throws IOException, ParserConfigurationException, TransformerException
{
// Get Extension instance
Extension mavenExtension = this.extensionConverter.convert(Extension.class, model);
MutableExtension mutableExtension;
if (mavenExtension instanceof MutableExtension) {
mutableExtension = (MutableExtension) mavenExtension;
} else {
mutableExtension = new DefaultLocalExtension(null, mavenExtension);
}
if (!path.exists()) {
// Apply overrides
override(mutableExtension);
// Save the Extension descriptor
try (FileOutputStream stream = new FileOutputStream(path)) {
this.extensionSerializer.saveExtensionDescriptor(mavenExtension, stream);
}
}
}
protected void override(MutableExtension extension)
{
if (this.extensionOverrides != null) {
for (ExtensionOverride extensionOverride : this.extensionOverrides) {
String id = extensionOverride.get(Extension.FIELD_ID);
if (id != null) {
// Override features
String featuresString = extensionOverride.get(Extension.FIELD_FEATURES);
if (featuresString != null) {
Collection<String> features = ExtensionUtils.importPropertyStringList(featuresString, true);
extension.setExtensionFeatures(
ExtensionIdConverter.toExtensionIdList(features, extension.getId().getVersion()));
}
}
}
}
}
protected void saveExtension(Artifact artifact, File directory) throws MojoExecutionException
{
// Get path
// WAR plugin use based version for the name of the actual file stored in the package
File path = new File(directory, artifact.getArtifactId() + '-' + artifact.getBaseVersion() + ".xed");
try {
saveExtension(path, artifact);
} catch (Exception e) {
throw new MojoExecutionException("Failed to write descriptor for artifact [" + artifact + "]", e);
}
}
protected void saveExtensions(Collection<Artifact> artifacts, File directory, String type)
throws MojoExecutionException
{
// Register dependencies
for (Artifact artifact : artifacts) {
if (!artifact.isOptional()) {
if (type == null || type.equals(artifact.getType())) {
saveExtension(artifact, directory);
}
}
}
}
}
|
package org.openhab.binding.smartmeter.internal.sml;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Stack;
import java.util.function.Supplier;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.util.HexUtils;
import org.eclipse.smarthome.io.transport.serial.PortInUseException;
import org.eclipse.smarthome.io.transport.serial.SerialPort;
import org.eclipse.smarthome.io.transport.serial.SerialPortIdentifier;
import org.eclipse.smarthome.io.transport.serial.SerialPortManager;
import org.eclipse.smarthome.io.transport.serial.UnsupportedCommOperationException;
import org.openhab.binding.smartmeter.connectors.ConnectorBase;
import org.openhab.binding.smartmeter.internal.helper.Baudrate;
import org.openhab.binding.smartmeter.internal.helper.SerialParameter;
import org.openmuc.jsml.structures.SmlFile;
import org.openmuc.jsml.transport.Transport;
/**
* Represents a serial SML device connector.
*
* @author Matthias Steigenberger - Initial contribution
* @author Mathias Gilhuber - Also-By
*/
@NonNullByDefault
public final class SmlSerialConnector extends ConnectorBase<SmlFile> {
private static final Transport TRANSPORT = new Transport();
private Supplier<SerialPortManager> serialManagerSupplier;
@NonNullByDefault({})
private SerialPort serialPort;
@Nullable
private DataInputStream is;
@Nullable
private DataOutputStream os;
private int baudrate;
/**
* Constructor to create a serial connector instance.
*
* @param portName the port where the device is connected as defined in openHAB configuration.
*/
public SmlSerialConnector(Supplier<SerialPortManager> serialPortManagerSupplier, String portName) {
super(portName);
this.serialManagerSupplier = serialPortManagerSupplier;
}
/**
* Constructor to create a serial connector instance with a specific serial parameter.
*
* @param portName the port where the device is connected as defined in openHAB configuration.
* @param baudrate
* @throws IOException
*/
public SmlSerialConnector(Supplier<SerialPortManager> serialPortManagerSupplier, String portName, int baudrate,
int baudrateChangeDelay) {
this(serialPortManagerSupplier, portName);
this.baudrate = baudrate;
}
@Override
protected SmlFile readNext(byte @Nullable [] initMessage) throws IOException {
if (initMessage != null) {
logger.debug("Writing init message: {}", HexUtils.bytesToHex(initMessage, " "));
if (os != null) {
os.write(initMessage);
os.flush();
}
}
// read out the whole buffer. We are only interested in the most recent SML file.
Stack<SmlFile> smlFiles = new Stack<>();
do {
smlFiles.push(TRANSPORT.getSMLFile(is));
} while (is != null && is.available() > 0);
if (smlFiles.isEmpty()) {
throw new IOException(getPortName() + " : There is no SML file in buffer. Try to increase Refresh rate.");
}
logger.debug("{} : Read {} SML files from Buffer", this.getPortName(), smlFiles.size());
return smlFiles.pop();
}
@Override
public void openConnection() throws IOException {
closeConnection();
SerialPortIdentifier id = serialManagerSupplier.get().getIdentifier(getPortName());
if (id != null) {
try {
serialPort = id.open("meterreaderbinding", 0);
} catch (PortInUseException e) {
throw new IOException(MessageFormat
.format("Error at SerialConnector.openConnection: unable to open port {0}.", getPortName()), e);
}
SerialParameter serialParameter = SerialParameter._8N1;
int baudrateToUse = this.baudrate == Baudrate.AUTO.getBaudrate() ? Baudrate._9600.getBaudrate()
: this.baudrate;
try {
serialPort.setSerialPortParams(baudrateToUse, serialParameter.getDatabits(),
serialParameter.getStopbits(), serialParameter.getParity());
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
try {
serialPort.enableReceiveTimeout(100);
} catch (UnsupportedCommOperationException e) {
// doesn't matter (rfc2217 is not supporting this)
}
} catch (UnsupportedCommOperationException e) {
throw new IOException(MessageFormat.format(
"Error at SerialConnector.openConnection: unable to set serial port parameters for port {0}.",
getPortName()), e);
}
// serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.notifyOnDataAvailable(true);
is = new DataInputStream(serialPort.getInputStream());
os = new DataOutputStream(serialPort.getOutputStream());
} else {
throw new IllegalStateException(MessageFormat.format("No provider for port {0} found", getPortName()));
}
}
/**
* @{inheritDoc}
*/
@Override
public void closeConnection() {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
logger.error("Failed to close serial input stream", e);
}
try {
if (os != null) {
os.close();
os = null;
}
} catch (IOException e) {
logger.error("Failed to close serial output stream", e);
}
if (serialPort != null) {
serialPort.close();
serialPort = null;
}
}
@Override
protected boolean applyPeriod() {
return true;
}
}
|
package org.apache.mesos.logstash.executor;
import org.apache.mesos.logstash.common.ConcurrentUtils;
import org.apache.mesos.logstash.common.LogstashProtos.ExecutorMessage.ExecutorStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Encapsulates a logstash instance. Keeps track of the current container id for logstash.
*/
public class LogstashService {
public static final Logger LOGGER = LoggerFactory.getLogger(LogstashService.class);
private ExecutorStatus status;
private final ScheduledExecutorService executorService;
private final Object lock = new Object();
private String latestConfig;
private Process process;
public LogstashService() {
status = ExecutorStatus.INITIALIZING;
executorService = Executors.newSingleThreadScheduledExecutor();
}
public void start() {
executorService.scheduleWithFixedDelay(this::run, 0, 1, TimeUnit.SECONDS);
}
public void stop() {
if (process != null) {
process.destroy();
}
ConcurrentUtils.stop(executorService);
}
public void update(int syslogPort, String elasticsearchDomainAndPort) {
// Producer: We only keep the latest config in case of multiple
// updates.
String config =
LS.config(
LS.section("input",
LS.plugin("syslog", LS.map(
LS.kv("port", LS.number(syslogPort))
))
),
LS.section("output",
LS.plugin("elasticsearch", LS.map(
LS.kv("hosts", LS.array(LS.string(elasticsearchDomainAndPort)))
))
)
).serialize();
LOGGER.debug("Writing new configuration:\n{}", config);
synchronized (lock) {
latestConfig = config;
}
}
private void run() {
if (process != null) {
status = process.isAlive() ? ExecutorStatus.RUNNING : ExecutorStatus.ERROR;
}
// Consumer: Read the latest config. If any, write it to disk and restart
// the logstash process.
String newConfig = getLatestConfig();
if (newConfig == null) {
return;
}
LOGGER.info("Restarting the Logstash Process.");
status = ExecutorStatus.RESTARTING;
try {
Path configFile = Paths.get("/tmp/logstash/logstash.conf");
Files.createDirectories(configFile.getParent());
Files.write(configFile.resolve(configFile), newConfig.getBytes());
// Stop any existing logstash instance. It does not have to complete
// before we start the new one.
if (process != null) {
process.destroy();
process.waitFor(5, TimeUnit.MINUTES);
}
process = Runtime.getRuntime().exec(
new String[]{
"/opt/logstash/bin/logstash",
"--log", "/var/log/logstash.log",
"--config", "/tmp/logstash/"
},
new String[]{
"LS_HEAP_SIZE=" + System.getProperty("mesos.logstash.logstash.heap.size"),
"HOME=/root"
}
);
} catch (Exception e) {
status = ExecutorStatus.ERROR;
LOGGER.error("Failed to start logstash process.", e);
}
}
public ExecutorStatus status() {
return status;
}
private String getLatestConfig() {
synchronized (lock) {
String config = latestConfig;
latestConfig = null;
return config;
}
}
}
|
package com.sedmelluq.discord.lavaplayer.container.mp3;
import com.sedmelluq.discord.lavaplayer.filter.FilterChainBuilder;
import com.sedmelluq.discord.lavaplayer.filter.ShortPcmAudioFilter;
import com.sedmelluq.discord.lavaplayer.natives.mp3.Mp3Decoder;
import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioProcessingContext;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.sedmelluq.discord.lavaplayer.natives.mp3.Mp3Decoder.SAMPLES_PER_FRAME;
/**
* Handles parsing MP3 files, seeking and sending the decoded frames to the specified frame consumer.
*/
public class Mp3TrackProvider {
private static final byte[] IDV3_TAG = new byte[] { 0x49, 0x44, 0x33 };
private static final int IDV3_FLAG_EXTENDED = 0x40;
private static final List<String> knownTextExtensions = Arrays.asList("TIT2", "TPE1");
private final AudioProcessingContext context;
private final SeekableInputStream inputStream;
private final DataInputStream dataInput;
private final Mp3Decoder mp3Decoder;
private final ShortBuffer outputBuffer;
private final ByteBuffer inputBuffer;
private final byte[] frameBuffer;
private final byte[] tagHeaderBuffer;
private final Mp3FrameReader frameReader;
private final Map<String, String> tags;
private int sampleRate;
private ShortPcmAudioFilter downstream;
private Mp3Seeker seeker;
/**
* @param context Configuration and output information for processing. May be null in case no frames are read and this
* instance is only used to retrieve information about the track.
* @param inputStream Stream to read the file from
*/
public Mp3TrackProvider(AudioProcessingContext context, SeekableInputStream inputStream) {
this.context = context;
this.inputStream = inputStream;
this.dataInput = new DataInputStream(inputStream);
this.outputBuffer = ByteBuffer.allocateDirect((int) SAMPLES_PER_FRAME * 4).order(ByteOrder.nativeOrder()).asShortBuffer();
this.inputBuffer = ByteBuffer.allocateDirect(Mp3Decoder.getMaximumFrameSize());
this.frameBuffer = new byte[Mp3Decoder.getMaximumFrameSize()];
this.tagHeaderBuffer = new byte[4];
this.frameReader = new Mp3FrameReader(inputStream, frameBuffer);
this.mp3Decoder = new Mp3Decoder();
this.tags = new HashMap<>();
}
/**
* Parses file headers to find the first MP3 frame and to get the settings for initialising the filter chain.
* @throws IOException On read error
*/
public void parseHeaders() throws IOException {
skipIdv3Tags();
if (!frameReader.scanForFrame(2048, true)) {
throw new IllegalStateException("File ended before the first frame was found.");
}
sampleRate = Mp3Decoder.getFrameSampleRate(frameBuffer, 0);
downstream = context != null ? FilterChainBuilder.forShortPcm(context, 2, sampleRate, true) : null;
initialiseSeeker();
}
private void initialiseSeeker() throws IOException {
long startPosition = frameReader.getFrameStartPosition();
frameReader.fillFrameBuffer();
seeker = Mp3XingSeeker.createFromFrame(startPosition, inputStream.getContentLength(), frameBuffer);
if (seeker == null) {
if (inputStream.getContentLength() == Long.MAX_VALUE) {
seeker = new Mp3StreamSeeker();
} else {
seeker = Mp3ConstantRateSeeker.createFromFrame(startPosition, inputStream.getContentLength(), frameBuffer);
}
}
}
/**
* Decodes audio frames and sends them to frame consumer
* @throws InterruptedException
*/
public void provideFrames() throws InterruptedException {
try {
while (true) {
if (!frameReader.fillFrameBuffer()) {
break;
}
inputBuffer.clear();
inputBuffer.put(frameBuffer, 0, frameReader.getFrameSize());
inputBuffer.flip();
int produced = mp3Decoder.decode(inputBuffer, outputBuffer);
if (produced > 0) {
downstream.process(outputBuffer);
}
frameReader.nextFrame();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Seeks to the specified timecode.
* @param timecode The timecode in milliseconds
*/
public void seekToTimecode(long timecode) {
try {
long frameIndex = seeker.seekAndGetFrameIndex(timecode, inputStream);
long actualTimecode = frameIndex * SAMPLES_PER_FRAME * 1000 / sampleRate;
downstream.seekPerformed(timecode, actualTimecode);
frameReader.nextFrame();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @return True if the track is seekable (false for streams for example).
*/
public boolean isSeekable() {
return seeker.isSeekable();
}
/**
* @return An estimated duration of the file in milliseconds
*/
public long getDuration() {
return seeker.getDuration();
}
/**
* Gets an ID3 tag. These are loaded when parsing headers and only for a fixed list of tags.
*
* @param tagId The FourCC of the tag
* @return The value of the tag if present, otherwise null
*/
public String getIdv3Tag(String tagId) {
return tags.get(tagId);
}
/**
* Closes resources.
*/
public void close() {
if (downstream != null) {
downstream.close();
}
mp3Decoder.close();
}
private void skipIdv3Tags() throws IOException {
dataInput.readFully(tagHeaderBuffer, 0, 3);
for (int i = 0; i < 3; i++) {
if (tagHeaderBuffer[i] != IDV3_TAG[i]) {
frameReader.appendToScanBuffer(tagHeaderBuffer, 0, 3);
return;
}
}
int majorVersion = dataInput.readByte() & 0xFF;
// Minor version
dataInput.readByte();
if (majorVersion < 2 && majorVersion > 5) {
return;
}
int flags = dataInput.readByte() & 0xFF;
int tagsSize = readSyncProofInteger();
long tagsEndPosition = inputStream.getPosition() + tagsSize;
skipExtendedHeader(flags);
if (majorVersion < 5) {
parseIdv3Frames(majorVersion, tagsEndPosition);
}
inputStream.seek(tagsEndPosition);
}
private int readSyncProofInteger() throws IOException {
return (dataInput.readByte() & 0xFF) << 21
| (dataInput.readByte() & 0xFF) << 14
| (dataInput.readByte() & 0xFF) << 7
| (dataInput.readByte() & 0xFF);
}
private int readSyncProof3ByteInteger() throws IOException {
return (dataInput.readByte() & 0xFF) << 14
| (dataInput.readByte() & 0xFF) << 7
| (dataInput.readByte() & 0xFF);
}
private void skipExtendedHeader(int flags) throws IOException {
if ((flags & IDV3_FLAG_EXTENDED) != 0) {
int size = readSyncProofInteger();
inputStream.seek(inputStream.getPosition() + size - 4);
}
}
private void parseIdv3Frames(int version, long tagsEndPosition) throws IOException {
FrameHeader header;
while (inputStream.getPosition() + 10 <= tagsEndPosition && (header = readFrameHeader(version)) != null) {
long nextTagPosition = inputStream.getPosition() + header.size;
if (header.hasRawFormat() && knownTextExtensions.contains(header.id)) {
String text = parseIdv3TextContent(header.size);
if (text != null) {
tags.put(header.id, text);
}
}
inputStream.seek(nextTagPosition);
}
}
private String parseIdv3TextContent(int size) throws IOException {
int encoding = dataInput.readByte() & 0xFF;
byte[] data = new byte[size - 1];
dataInput.readFully(data);
boolean shortTerminator = data.length > 0 && data[data.length - 1] == 0;
boolean wideTerminator = data.length > 1 && data[data.length - 2] == 0 && shortTerminator;
switch (encoding) {
case 0:
return new String(data, 0, size - (shortTerminator ? 2 : 1), "ISO-8859-1");
case 1:
return new String(data, 0, size - (wideTerminator ? 3 : 1), "UTF-16");
case 2:
return new String(data, 0, size - (wideTerminator ? 3 : 1), "UTF-16BE");
case 3:
return new String(data, 0, size - (shortTerminator ? 2 : 1), "UTF-8");
default:
return null;
}
}
private String readId3v22TagName() throws IOException {
dataInput.readFully(tagHeaderBuffer, 0, 3);
if (tagHeaderBuffer[0] == 0) {
return null;
}
String shortName = new String(tagHeaderBuffer, 0, 3, StandardCharsets.ISO_8859_1);
if ("TT2".equals(shortName)) {
return "TIT2";
} else if ("TP1".equals(shortName)) {
return "TPE1";
} else {
return shortName;
}
}
private String readTagName() throws IOException {
dataInput.readFully(tagHeaderBuffer, 0, 4);
if (tagHeaderBuffer[0] == 0) {
return null;
}
return new String(tagHeaderBuffer, 0, 4, StandardCharsets.ISO_8859_1);
}
private FrameHeader readFrameHeader(int version) throws IOException {
if (version == 2) {
String tagName = readId3v22TagName();
if (tagName != null) {
return new FrameHeader(tagName, readSyncProof3ByteInteger(), 0);
}
} else {
String tagName = readTagName();
if (tagName != null) {
int size = version == 3 ? dataInput.readInt() : readSyncProofInteger();
return new FrameHeader(tagName, size, dataInput.readUnsignedShort());
}
}
return null;
}
@SuppressWarnings("unused")
private static class FrameHeader {
private final String id;
private final int size;
private final boolean tagAlterPreservation;
private final boolean fileAlterPreservation;
private final boolean readOnly;
private final boolean groupingIdentity;
private final boolean compression;
private final boolean encryption;
private final boolean unsynchronization;
private final boolean dataLengthIndicator;
private FrameHeader(String id, int size, int flags) {
this.id = id;
this.size = size;
this.tagAlterPreservation = (flags & 0x4000) != 0;
this.fileAlterPreservation = (flags & 0x2000) != 0;
this.readOnly = (flags & 0x1000) != 0;
this.groupingIdentity = (flags & 0x0040) != 0;
this.compression = (flags & 0x0008) != 0;
this.encryption = (flags & 0x0004) != 0;
this.unsynchronization = (flags & 0x0002) != 0;
this.dataLengthIndicator = (flags & 0x0001) != 0;
}
private boolean hasRawFormat() {
return !compression && !encryption && !unsynchronization && !dataLengthIndicator;
}
}
}
|
package tools;
import java.io.ByteArrayOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.geomajas.command.CommandDispatcher;
import org.geomajas.command.dto.GetVectorTileRequest;
import org.geomajas.command.dto.GetVectorTileResponse;
import org.geomajas.configuration.NamedStyleInfo;
import org.geomajas.geometry.Coordinate;
import org.geomajas.layer.tile.TileCode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/tools/client.xml" })
public class RunSingleTileTest {
@Autowired
private CommandDispatcher commandDispatcher;
@Test
public void testTile() throws Exception {
GetVectorTileRequest request = createRequest();
long time = System.currentTimeMillis();
for (int i = 0; i < 1; i++) {
long time2 = System.currentTimeMillis();
GetVectorTileResponse response = (GetVectorTileResponse) commandDispatcher.execute(
GetVectorTileRequest.COMMAND, request, null, null);
System.out.println("
time2 = System.currentTimeMillis();
consumeTile(response);
System.out.println("
}
System.out.println("+++++ time " + (System.currentTimeMillis() - time) + "ms");
}
private void consumeTile(GetVectorTileResponse response) throws Exception {
String url = response.getTile().getFeatureContent();
System.out.println("
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse r = httpclient.execute(httpget);
HttpEntity entity = r.getEntity();
entity.writeTo(new ByteArrayOutputStream());
}
private GetVectorTileRequest createRequest() {
GetVectorTileRequest request = new GetVectorTileRequest();
TileCode code = new TileCode(5, 16, 8);
request.setCode(code);
request.setLayerId("referenceBase");
request.setCrs("EPSG:900913");
request.setScale(0.006541332273339661);
request.setPanOrigin(new Coordinate(-1.2803202237767024E7, 6306054.833527042));
NamedStyleInfo style = new NamedStyleInfo();
style.setName("referenceBaseStyleInfo");
request.setStyleInfo(style);
request.setScale(0.05233065818671729);
request.setPaintGeometries(true);
request.setPaintLabels(false);
request.setFilter("layer.code = 1 or layer.code = 2 or layer.code = 5 or layer.code = 6 or layer.code = 7 or layer.code = 8 or layer.code = 9 or layer.code = 19 or layer.code = 20 or layer.code = 21 or layer.code = 22 or layer.code = 23 or layer.code = 24 or layer.code = 25 or layer.code = 26 or layer.code = 27 or layer.code = 28 or layer.code = 34 or layer.code = 78 or layer.code = 79 or layer.code = 82 or layer.code = 83");
return request;
}
}
|
package io.cattle.platform.servicediscovery.process;
import io.cattle.platform.configitem.request.ConfigUpdateRequest;
import io.cattle.platform.configitem.version.ConfigItemStatusManager;
import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.InstanceDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.Stack;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import io.cattle.platform.servicediscovery.service.ServiceDiscoveryService;
import io.cattle.platform.util.type.Priority;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class StackHealthStateUpdateTrigger extends AbstractObjectProcessLogic implements ProcessPostListener, Priority {
public static final String STACK = "stack-reconcile";
@Inject
InstanceDao instanceDao;
@Inject
ServiceDiscoveryService sdService;
@Inject
ConfigItemStatusManager itemManager;
@Override
public String[] getProcessNames() {
return new String[] { HealthcheckConstants.PROCESS_UPDATE_HEALTHY,
HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, InstanceConstants.PROCESS_STOP,
InstanceConstants.PROCESS_REMOVE, InstanceConstants.PROCESS_START,
"service.*"};
}
@Override
public HandlerResult handle(ProcessState state, ProcessInstance process) {
List<Service> services = new ArrayList<>();
if (state.getResource() instanceof Service) {
services.add((Service) state.getResource());
} else if (state.getResource() instanceof Instance) {
services.addAll(instanceDao.findServicesFor((Instance) state.getResource()));
}
Set<Long> stackIds = new HashSet<>();
for (Service service : services) {
stackIds.add(service.getStackId());
}
for (Long stackId : stackIds) {
ConfigUpdateRequest request = ConfigUpdateRequest.forResource(Stack.class,
stackId);
request.addItem(STACK);
request.withDeferredTrigger(true);
itemManager.updateConfig(request);
}
return null;
}
@Override
public int getPriority() {
return Priority.DEFAULT;
}
}
|
package org.maxur.mserv.doc;
import org.junit.Ignore;
import org.junit.Test;
import org.maxur.mserv.core.domain.BaseService;
import org.maxur.mserv.core.java.Locator;
import org.maxur.mserv.core.runner.Java;
import org.maxur.mserv.core.service.properties.Properties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Maxim Yunusov
* @version 1.0
* @since <pre>8/4/2017</pre>
*/
public class MicroServiceJavaClientIT {
private BaseService service1 = null;
@Test
@Ignore
public void main() {
// tag::launcher[]
Java.runner()
.name(":name")
.packages("org.maxur.mserv.sample")
.properties("hocon")
.rest()
.afterStart(this::afterStart)
.beforeStop(this::beforeStop)
.start();
// end::launcher[]
if (service1 != null) {
service1.stop();
}
Locator.stop();
}
private void beforeStop(final BaseService service) {
assertThat(service).isNotNull();
}
private void afterStart(final BaseService service) {
service1 = service;
assertThat(service).isNotNull();
final Locator locator = Locator.getInstance();
final Properties config = locator.service(Properties.class);
assertThat(config).isNotNull();
assertThat(config.getSources().get(0).getFormat()).isEqualToIgnoringCase("Hocon");
}
}
|
package org.mockserver.maven;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.repository.RepositorySystem;
import org.mockserver.cli.Main;
import org.mockserver.configuration.ConfigurationProperties;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author jamesdbloom
*/
@Mojo(name = "runForked", requiresProject = false, threadSafe = false)
public class MockServerRunForkedMojo extends MockServerAbstractMojo {
private ProcessBuildFactory processBuildFactory = new ProcessBuildFactory();
/**
* Get a list of artifacts used by this plugin
*/
@Parameter(defaultValue = "${plugin.artifacts}", required = true, readonly = true)
protected List<Artifact> pluginArtifacts;
/**
* Used to look up Artifacts in the remote repository.
*/
@Component
protected RepositorySystem repositorySystem;
/**
* Used to look up Artifacts in the remote repository.
*/
@Component
protected ArtifactResolver artifactResolver;
public static String fileSeparators(String path) {
StringBuilder ret = new StringBuilder();
for (char c : path.toCharArray()) {
if ((c == '/') || (c == '\\')) {
ret.append(File.separatorChar);
} else {
ret.append(c);
}
}
return ret.toString();
}
public void execute() throws MojoExecutionException {
if (skip) {
getLog().info("Skipping plugin execution");
} else {
if (getLog().isInfoEnabled()) {
getLog().info("mockserver:runForked about to start MockServer on: "
+ (serverPort != -1 ? " serverPort " + serverPort : "")
+ (proxyPort != -1 ? " proxyPort " + proxyPort : "")
);
}
List<String> arguments = new ArrayList<String>(Arrays.asList(getJavaBin()));
// arguments.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5010");
arguments.add("-Dfile.encoding=UTF-8");
arguments.add("-Dmockserver.logLevel=" + logLevel);
arguments.add("-cp");
String classPath = resolveJarWithDependenciesPath();
if (dependencies != null && !dependencies.isEmpty()) {
for (Dependency dependency : dependencies) {
classPath += System.getProperty("path.separator");
classPath += resolvePluginDependencyJarPath(dependency);
}
}
arguments.add(classPath);
arguments.add(Main.class.getName());
if (serverPort != -1) {
arguments.add("-serverPort");
arguments.add("" + serverPort);
ConfigurationProperties.mockServerPort(serverPort);
}
if (proxyPort != -1) {
arguments.add("-proxyPort");
arguments.add("" + proxyPort);
ConfigurationProperties.proxyPort(proxyPort);
}
getLog().info(" ");
getLog().info(StringUtils.rightPad("", 72, "-"));
getLog().info("Running MockServer: " + Joiner.on(" ").join(arguments));
getLog().info(StringUtils.rightPad("", 72, "-"));
getLog().info(" ");
ProcessBuilder processBuilder = processBuildFactory.create(arguments);
if (pipeLogToConsole) {
processBuilder.redirectErrorStream(true);
}
try {
processBuilder.start();
} catch (IOException e) {
getLog().error("Exception while starting MockServer", e);
}
try {
TimeUnit.SECONDS.sleep((timeout == 0 ? 2 : timeout));
} catch (InterruptedException e) {
throw new RuntimeException("Exception while waiting for mock server JVM to start", e);
}
InstanceHolder.runInitializationClass(serverPort, createInitializer());
}
}
@VisibleForTesting
String getJavaBin() {
String javaBinary = "java";
File javaHomeDirectory = new File(System.getProperty("java.home"));
for (String javaExecutable : new String[]{"java", "java.exe"}) {
File javaExeLocation = new File(javaHomeDirectory, fileSeparators("bin/" + javaExecutable));
if (javaExeLocation.exists() && javaExeLocation.isFile()) {
javaBinary = javaExeLocation.getAbsolutePath();
break;
}
}
return javaBinary;
}
@VisibleForTesting
String resolvePluginDependencyJarPath(Dependency dependency) {
Artifact dependencyArtifact = repositorySystem.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier());
artifactResolver.resolve(new ArtifactResolutionRequest().setArtifact(dependencyArtifact));
return dependencyArtifact.getFile().getAbsolutePath();
}
@VisibleForTesting
String resolveJarWithDependenciesPath() {
Artifact jarWithDependencies = repositorySystem.createArtifactWithClassifier("org.mock-server", "mockserver-netty", getVersion(), "jar", "jar-with-dependencies");
artifactResolver.resolve(new ArtifactResolutionRequest().setArtifact(jarWithDependencies));
return jarWithDependencies.getFile().getAbsolutePath();
}
@VisibleForTesting
String getVersion() {
String version = "3.9.9";
try {
java.util.Properties p = new java.util.Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/org.mock-server/mockserver-maven-plugin/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "3.9.9");
}
} catch (Exception e) {
// ignore
}
getLog().info("Using org.mock-server:mockserver-netty:" + version + ":jar-with-dependencies");
return version;
}
}
|
package io.quarkus.hibernate.reactive.deployment;
import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT;
import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT;
import static io.quarkus.hibernate.orm.deployment.HibernateConfigUtil.firstPresent;
import static org.hibernate.cfg.AvailableSettings.JPA_SHARED_CACHE_MODE;
import static org.hibernate.cfg.AvailableSettings.USE_DIRECT_REFERENCE_CACHE_ENTRIES;
import static org.hibernate.cfg.AvailableSettings.USE_QUERY_CACHE;
import static org.hibernate.cfg.AvailableSettings.USE_SECOND_LEVEL_CACHE;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
import org.hibernate.loader.BatchFetchStyle;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.datasource.deployment.spi.DefaultDataSourceDbKindBuildItem;
import io.quarkus.datasource.runtime.DataSourcesBuildTimeConfig;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
import io.quarkus.deployment.builditem.SystemPropertyBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.configuration.ConfigurationError;
import io.quarkus.deployment.pkg.builditem.CurateOutcomeBuildItem;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.hibernate.orm.deployment.Dialects;
import io.quarkus.hibernate.orm.deployment.HibernateConfigUtil;
import io.quarkus.hibernate.orm.deployment.HibernateOrmConfig;
import io.quarkus.hibernate.orm.deployment.HibernateOrmConfigPersistenceUnit;
import io.quarkus.hibernate.orm.deployment.HibernateOrmProcessor;
import io.quarkus.hibernate.orm.deployment.JpaModelBuildItem;
import io.quarkus.hibernate.orm.deployment.PersistenceProviderSetUpBuildItem;
import io.quarkus.hibernate.orm.deployment.PersistenceUnitDescriptorBuildItem;
import io.quarkus.hibernate.orm.deployment.PersistenceXmlDescriptorBuildItem;
import io.quarkus.hibernate.orm.deployment.integration.HibernateOrmIntegrationRuntimeConfiguredBuildItem;
import io.quarkus.hibernate.orm.runtime.HibernateOrmRuntimeConfig;
import io.quarkus.hibernate.reactive.runtime.FastBootHibernateReactivePersistenceProvider;
import io.quarkus.hibernate.reactive.runtime.HibernateReactiveRecorder;
import io.quarkus.hibernate.reactive.runtime.ReactiveSessionFactoryProducer;
import io.quarkus.hibernate.reactive.runtime.ReactiveSessionProducer;
import io.quarkus.reactive.datasource.deployment.VertxPoolBuildItem;
import io.quarkus.runtime.LaunchMode;
public final class HibernateReactiveProcessor {
private static final String HIBERNATE_REACTIVE = "Hibernate Reactive";
static final String[] REFLECTIVE_CONSTRUCTORS_NEEDED = {
"org.hibernate.reactive.persister.entity.impl.ReactiveSingleTableEntityPersister",
"org.hibernate.reactive.persister.entity.impl.ReactiveJoinedSubclassEntityPersister",
"org.hibernate.reactive.persister.entity.impl.ReactiveUnionSubclassEntityPersister",
"org.hibernate.reactive.persister.collection.impl.ReactiveOneToManyPersister",
"org.hibernate.reactive.persister.collection.impl.ReactiveBasicCollectionPersister",
};
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.HIBERNATE_REACTIVE);
}
@BuildStep
void registerBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans, CombinedIndexBuildItem combinedIndex,
List<PersistenceUnitDescriptorBuildItem> descriptors,
JpaModelBuildItem jpaModel) {
if (!hasEntities(jpaModel)) {
return;
}
if (descriptors.size() == 1) {
// Only register those beans if their EMF dependency is also available, so use the same guard as the ORM extension
additionalBeans.produce(new AdditionalBeanBuildItem(ReactiveSessionFactoryProducer.class));
additionalBeans.produce(new AdditionalBeanBuildItem(ReactiveSessionProducer.class));
}
}
@BuildStep
void reflections(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) {
reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, REFLECTIVE_CONSTRUCTORS_NEEDED));
}
@BuildStep
@Record(STATIC_INIT)
public void build(RecorderContext recorderContext,
HibernateReactiveRecorder recorder,
JpaModelBuildItem jpaModel) {
final boolean enableRx = hasEntities(jpaModel);
recorder.callHibernateReactiveFeatureInit(enableRx);
}
@BuildStep
public void buildReactivePersistenceUnit(
HibernateOrmConfig hibernateOrmConfig,
DataSourcesBuildTimeConfig dataSourcesBuildTimeConfig,
List<PersistenceXmlDescriptorBuildItem> persistenceXmlDescriptors,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
LaunchModeBuildItem launchMode,
JpaModelBuildItem jpaModel,
BuildProducer<SystemPropertyBuildItem> systemProperties,
BuildProducer<NativeImageResourceBuildItem> nativeImageResources,
BuildProducer<HotDeploymentWatchedFileBuildItem> hotDeploymentWatchedFiles,
BuildProducer<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptors,
List<DefaultDataSourceDbKindBuildItem> defaultDataSourceDbKindBuildItems,
CurateOutcomeBuildItem curateOutcomeBuildItem) {
final boolean enableHR = hasEntities(jpaModel);
if (!enableHR) {
// we have to bail out early as we might not have a Vertx pool configuration
return;
}
// Block any reactive persistence units from using persistence.xml
for (PersistenceXmlDescriptorBuildItem persistenceXmlDescriptorBuildItem : persistenceXmlDescriptors) {
String provider = persistenceXmlDescriptorBuildItem.getDescriptor().getProviderClassName();
if (provider == null ||
provider.equals(FastBootHibernateReactivePersistenceProvider.class.getCanonicalName()) ||
provider.equals(FastBootHibernateReactivePersistenceProvider.IMPLEMENTATION_NAME)) {
throw new ConfigurationError(
"Cannot use persistence.xml with Hibernate Reactive in Quarkus. Must use application.properties instead.");
}
}
// we only support the default pool for now
Optional<String> dbKindOptional = DefaultDataSourceDbKindBuildItem.resolve(
dataSourcesBuildTimeConfig.defaultDataSource.dbKind,
defaultDataSourceDbKindBuildItems,
dataSourcesBuildTimeConfig.defaultDataSource.devservices.enabled
.orElse(dataSourcesBuildTimeConfig.namedDataSources.isEmpty()),
curateOutcomeBuildItem);
if (dbKindOptional.isPresent()) {
final String dbKind = dbKindOptional.get();
ParsedPersistenceXmlDescriptor reactivePU = generateReactivePersistenceUnit(
hibernateOrmConfig, jpaModel,
dbKind, applicationArchivesBuildItem, launchMode.getLaunchMode(),
systemProperties, nativeImageResources, hotDeploymentWatchedFiles);
//Some constant arguments to the following method:
// - this is Reactive
// - we don't support starting Hibernate Reactive from a persistence.xml
// - we don't support Hibernate Envers with Hibernate Reactive
persistenceUnitDescriptors.produce(new PersistenceUnitDescriptorBuildItem(reactivePU,
jpaModel.getXmlMappings(reactivePU.getName()),
true, false));
}
}
@BuildStep
void waitForVertxPool(List<VertxPoolBuildItem> vertxPool,
List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems,
BuildProducer<HibernateOrmIntegrationRuntimeConfiguredBuildItem> runtimeConfigured) {
for (PersistenceUnitDescriptorBuildItem puDescriptor : persistenceUnitDescriptorBuildItems) {
// Define a dependency on VertxPoolBuildItem to ensure that any Pool instances are available
// when HibernateORM starts its persistence units
runtimeConfigured.produce(new HibernateOrmIntegrationRuntimeConfiguredBuildItem(HIBERNATE_REACTIVE,
puDescriptor.getPersistenceUnitName()));
}
}
@BuildStep
@Record(RUNTIME_INIT)
PersistenceProviderSetUpBuildItem setUpPersistenceProviderAndWaitForVertxPool(HibernateReactiveRecorder recorder,
HibernateOrmRuntimeConfig hibernateOrmRuntimeConfig,
List<HibernateOrmIntegrationRuntimeConfiguredBuildItem> integrationBuildItems) {
recorder.initializePersistenceProvider(hibernateOrmRuntimeConfig,
HibernateOrmIntegrationRuntimeConfiguredBuildItem.collectDescriptors(integrationBuildItems));
return new PersistenceProviderSetUpBuildItem();
}
/**
* This is mostly copied from
* io.quarkus.hibernate.orm.deployment.HibernateOrmProcessor#handleHibernateORMWithNoPersistenceXml
* Key differences are:
* - Always produces a persistence unit descriptor, since we assume there always 1 reactive persistence unit
* - Any JDBC-only configuration settings are removed
* - If we ever add any Reactive-only config settings, they can be set here
*/
private static ParsedPersistenceXmlDescriptor generateReactivePersistenceUnit(
HibernateOrmConfig hibernateOrmConfig,
JpaModelBuildItem jpaModel,
String dbKind,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
LaunchMode launchMode,
BuildProducer<SystemPropertyBuildItem> systemProperties,
BuildProducer<NativeImageResourceBuildItem> nativeImageResources,
BuildProducer<HotDeploymentWatchedFileBuildItem> hotDeploymentWatchedFiles) {
HibernateOrmConfigPersistenceUnit persistenceUnitConfig = hibernateOrmConfig.defaultPersistenceUnit;
//we have no persistence.xml so we will create a default one
Optional<String> dialect = persistenceUnitConfig.dialect.dialect;
if (!dialect.isPresent()) {
dialect = Dialects.guessDialect(dbKind);
}
String dialectClassName = dialect.get();
// we found one
ParsedPersistenceXmlDescriptor desc = new ParsedPersistenceXmlDescriptor(null); //todo URL
desc.setName("default-reactive");
desc.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
desc.getProperties().setProperty(AvailableSettings.DIALECT, dialectClassName);
desc.setExcludeUnlistedClasses(true);
desc.addClasses(new ArrayList<>(jpaModel.getAllModelClassNames()));
// The storage engine has to be set as a system property.
if (persistenceUnitConfig.dialect.storageEngine.isPresent()) {
systemProperties.produce(new SystemPropertyBuildItem(AvailableSettings.STORAGE_ENGINE,
persistenceUnitConfig.dialect.storageEngine.get()));
}
// Physical Naming Strategy
persistenceUnitConfig.physicalNamingStrategy.ifPresent(
namingStrategy -> desc.getProperties()
.setProperty(AvailableSettings.PHYSICAL_NAMING_STRATEGY, namingStrategy));
// Implicit Naming Strategy
persistenceUnitConfig.implicitNamingStrategy.ifPresent(
namingStrategy -> desc.getProperties()
.setProperty(AvailableSettings.IMPLICIT_NAMING_STRATEGY, namingStrategy));
//charset
desc.getProperties().setProperty(AvailableSettings.HBM2DDL_CHARSET_NAME,
persistenceUnitConfig.database.charset.name());
persistenceUnitConfig.database.defaultCatalog.ifPresent(
catalog -> desc.getProperties().setProperty(AvailableSettings.DEFAULT_CATALOG, catalog));
persistenceUnitConfig.database.defaultSchema.ifPresent(
schema -> desc.getProperties().setProperty(AvailableSettings.DEFAULT_SCHEMA, schema));
if (persistenceUnitConfig.database.globallyQuotedIdentifiers) {
desc.getProperties().setProperty(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, "true");
}
// Query
// TODO ideally we should align on ORM and use 16 as a default, but that would break applications
int batchSize = firstPresent(persistenceUnitConfig.fetch.batchSize, persistenceUnitConfig.batchFetchSize)
.orElse(-1);
if (batchSize > 0) {
desc.getProperties().setProperty(AvailableSettings.DEFAULT_BATCH_FETCH_SIZE,
Integer.toString(batchSize));
desc.getProperties().setProperty(AvailableSettings.BATCH_FETCH_STYLE, BatchFetchStyle.PADDED.toString());
}
if (persistenceUnitConfig.fetch.maxDepth.isPresent()) {
setMaxFetchDepth(desc, persistenceUnitConfig.fetch.maxDepth);
} else if (persistenceUnitConfig.maxFetchDepth.isPresent()) {
setMaxFetchDepth(desc, persistenceUnitConfig.maxFetchDepth);
}
desc.getProperties().setProperty(AvailableSettings.QUERY_PLAN_CACHE_MAX_SIZE, Integer.toString(
persistenceUnitConfig.query.queryPlanCacheMaxSize));
desc.getProperties().setProperty(AvailableSettings.DEFAULT_NULL_ORDERING,
persistenceUnitConfig.query.defaultNullOrdering.name().toLowerCase());
// JDBC
persistenceUnitConfig.jdbc.statementBatchSize.ifPresent(
statementBatchSize -> desc.getProperties().setProperty(AvailableSettings.STATEMENT_BATCH_SIZE,
String.valueOf(statementBatchSize)));
// Statistics
if (hibernateOrmConfig.metricsEnabled
|| (hibernateOrmConfig.statistics.isPresent() && hibernateOrmConfig.statistics.get())) {
desc.getProperties().setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
}
// sql-load-script
Optional<String> importFile = getSqlLoadScript(persistenceUnitConfig.sqlLoadScript, launchMode);
if (importFile.isPresent()) {
Path loadScriptPath = applicationArchivesBuildItem.getRootArchive().getChildPath(importFile.get());
if (loadScriptPath != null && !Files.isDirectory(loadScriptPath)) {
// enlist resource if present
nativeImageResources.produce(new NativeImageResourceBuildItem(importFile.get()));
hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(importFile.get()));
desc.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, importFile.get());
} else if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
//raise exception if explicit file is not present (i.e. not the default)
throw new ConfigurationError(
"Unable to find file referenced in '" + HibernateOrmProcessor.HIBERNATE_ORM_CONFIG_PREFIX
+ "sql-load-script="
+ persistenceUnitConfig.sqlLoadScript.get() + "'. Remove property or add file to your path.");
}
} else {
//Disable implicit loading of the default import script (import.sql)
desc.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, "");
}
// Caching
if (persistenceUnitConfig.secondLevelCachingEnabled) {
Properties p = desc.getProperties();
//Only set these if the user isn't making an explicit choice:
p.putIfAbsent(USE_DIRECT_REFERENCE_CACHE_ENTRIES, Boolean.TRUE);
p.putIfAbsent(USE_SECOND_LEVEL_CACHE, Boolean.TRUE);
p.putIfAbsent(USE_QUERY_CACHE, Boolean.TRUE);
p.putIfAbsent(JPA_SHARED_CACHE_MODE, SharedCacheMode.ENABLE_SELECTIVE);
Map<String, String> cacheConfigEntries = HibernateConfigUtil.getCacheConfigEntries(persistenceUnitConfig);
for (Entry<String, String> entry : cacheConfigEntries.entrySet()) {
desc.getProperties().setProperty(entry.getKey(), entry.getValue());
}
} else {
//Unless the global switch is explicitly set to off, in which case we disable all caching:
Properties p = desc.getProperties();
p.put(USE_DIRECT_REFERENCE_CACHE_ENTRIES, Boolean.FALSE);
p.put(USE_SECOND_LEVEL_CACHE, Boolean.FALSE);
p.put(USE_QUERY_CACHE, Boolean.FALSE);
p.put(JPA_SHARED_CACHE_MODE, SharedCacheMode.NONE);
}
return desc;
}
private static void setMaxFetchDepth(ParsedPersistenceXmlDescriptor descriptor, OptionalInt maxFetchDepth) {
descriptor.getProperties().setProperty(AvailableSettings.MAX_FETCH_DEPTH, String.valueOf(maxFetchDepth.getAsInt()));
}
private static Optional<String> getSqlLoadScript(Optional<String> sqlLoadScript, LaunchMode launchMode) {
// Explicit file or default Hibernate ORM file.
if (sqlLoadScript.isPresent()) {
if (HibernateOrmProcessor.NO_SQL_LOAD_SCRIPT_FILE.equalsIgnoreCase(sqlLoadScript.get())) {
return Optional.empty();
} else {
return Optional.of(sqlLoadScript.get());
}
} else if (launchMode == LaunchMode.NORMAL) {
return Optional.empty();
} else {
return Optional.of("import.sql");
}
}
private boolean hasEntities(JpaModelBuildItem jpaModel) {
return !jpaModel.getEntityClassNames().isEmpty();
}
}
|
package edu.isi.karma.web.services.publish.es;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.isi.karma.config.ModelingConfiguration;
import edu.isi.karma.config.ModelingConfigurationRegistry;
import edu.isi.karma.controller.update.UpdateContainer;
import edu.isi.karma.er.helper.PythonRepository;
import edu.isi.karma.er.helper.PythonRepositoryRegistry;
import edu.isi.karma.kr2rml.ContextIdentifier;
import edu.isi.karma.kr2rml.mapping.R2RMLMappingIdentifier;
import edu.isi.karma.kr2rml.planning.UserSpecifiedRootStrategy;
import edu.isi.karma.kr2rml.writer.JSONKR2RMLRDFWriter;
import edu.isi.karma.kr2rml.writer.KR2RMLRDFWriter;
import edu.isi.karma.metadata.KarmaMetadataManager;
import edu.isi.karma.metadata.PythonTransformationMetadata;
import edu.isi.karma.metadata.UserConfigMetadata;
import edu.isi.karma.metadata.UserPreferencesMetadata;
import edu.isi.karma.modeling.Uris;
import edu.isi.karma.modeling.semantictypes.SemanticTypeUtil;
import edu.isi.karma.rdf.GenericRDFGenerator;
import edu.isi.karma.rdf.RDFGeneratorRequest;
import edu.isi.karma.webserver.ContextParametersRegistry;
import edu.isi.karma.webserver.KarmaException;
import edu.isi.karma.webserver.ServletContextParameterMap;
import edu.isi.karma.webserver.ServletContextParameterMap.ContextParameter;
@Path("/")
public class ElasticSearchPublishServlet extends Application {
private static Logger logger = LoggerFactory
.getLogger(ElasticSearchPublishServlet.class);
private static final int retry = 10;
private int bulksize = 100;
private int sleepTime = 100;
private ServletContext context;
public ElasticSearchPublishServlet(@Context ServletContext context) {
this.context = context;
try {
initialization(context);
} catch (KarmaException ke) {
logger.error("KarmaException: " + ke.getMessage());
}
String bulksize = context.getInitParameter("ESBulkSize");
if(bulksize != null)
this.bulksize = Integer.parseInt(bulksize);
String sleep = context.getInitParameter("ESUploadInterval");
if(sleep != null)
this.sleepTime = Integer.parseInt(sleep);
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/data")
public String publishFromData(MultivaluedMap<String, String> formParams) {
try {
logger.info("Path - es/json . Generate jsonld and publish to ES");
ElasticSearchConfig esConfig = ElasticSearchConfig.parse(context, formParams);
R2RMLConfig r2rmlConfig = R2RMLConfig.parse(context, formParams);
String jsonld = generateJSONLD(r2rmlConfig);
if(jsonld != null)
return publishES(jsonld, esConfig);
} catch (Exception e) {
logger.error("Error generating JSON", e);
return "Exception: " + e.getMessage();
}
return null;
}
@POST
@Path("/data")
@Consumes(MediaType.APPLICATION_JSON)
public String publishFromData(JSONObject json) {
try {
logger.info("Path - es/json . Generate jsonld from multipart and publish to ES");
ElasticSearchConfig esConfig = ElasticSearchConfig.parse(context, null);
R2RMLConfig r2rmlConfig = R2RMLConfig.parse(context, null);
InputStream is = IOUtils.toInputStream(json.toString());
r2rmlConfig.setInput(is);
String jsonld = generateJSONLD(r2rmlConfig);
if(jsonld != null)
return publishES(jsonld, esConfig);
} catch (Exception e) {
logger.error("Error generating JSON", e);
return "Exception: " + e.getMessage();
}
return null;
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/jsonld")
public String publishFromJsonLD(MultivaluedMap<String, String> formParams) {
try {
logger.info("Path - es/jsonld . Publish JSONLD to ES");
ElasticSearchConfig esConfig = ElasticSearchConfig.parse(context, formParams);
R2RMLConfig r2rmlConfig = R2RMLConfig.parse(context, formParams);
String jsonld = IOUtils.toString(r2rmlConfig.getInput());
if(jsonld != null)
return publishES(jsonld, esConfig);
} catch (Exception e) {
logger.error("Error generating JSON", e);
return "Exception: " + e.getMessage();
}
return null;
}
private String publishES(String jsonld, ElasticSearchConfig esConfig) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
CloseableHttpClient httpClient = getHttpClient(esConfig);
HttpPost httpPost = getHttpPost(esConfig);
String bulkFormat = null;
StringBuilder sb = new StringBuilder();
// System.out.println("GOt JSONLD:");
// System.out.println(jsonld);
logger.info("Got JSONLD, now pushing to ES");
JSONArray jsonArray = null;
if(jsonld.startsWith("["))
jsonArray = new JSONArray(jsonld);
else {
JSONObject jObj = new JSONObject(jsonld);
jsonArray = new JSONArray();
jsonArray.put(jObj);
}
logger.info("FInished de-serializing JSON-LD");
long counter = 0;
Exception postException = null;
String index = esConfig.getIndex();
String type = esConfig.getType();
for(int k=0; k<jsonArray.length(); k++) {
JSONObject jObj = jsonArray.getJSONObject(k);
String id = null;
if(jObj.has("uri"))
{
id = jObj.getString("uri");
}
if(id != null)
{
bulkFormat = "{\"index\":{\"_index\":\"" + index+ "\",\"_type\":\""+ type +"\",\"_id\":\""+id+"\"}}";
}
else
{
bulkFormat = "{\"index\":{\"_index\":\"" + index+ "\",\"_type\":\""+ type +"\"}}";
}
sb.append(bulkFormat);
sb.append(System.getProperty("line.separator"));
sb.append(jObj.toString());
sb.append(System.getProperty("line.separator"));
counter++;
if (counter % bulksize == 0) {
int i = 0;
Exception ex = null;
while (i < retry) {
try {
StringEntity entity = new StringEntity(sb.toString(),"UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
httpClient.close();
System.out.println(counter + " processed");
break;
}catch(Exception e) {
ex = e;
logger.error("Error", e);
i++;
}
}
if (i > 0) {
logger.error("Exception occurred!", ex);
postException = ex;
break;
}
httpClient = getHttpClient(esConfig);
httpPost = getHttpPost(esConfig);
sb = new StringBuilder();
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
try {
StringEntity entity = new StringEntity(sb.toString(),"UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
httpClient.close();
} catch(Exception e) {
postException = e;
}
if (postException != null) {
logger.error("Exception occurred!", postException);
return "{\"result\": {\"code\": \"0\", \"message\": \"" + postException.getMessage() + "\"}}";
}
return "{\"result\": {\"code\": \"1\", \"message\": \"success\"}}";
}
private HttpPost getHttpPost(ElasticSearchConfig esConfig) {
return new HttpPost(esConfig.getProtocol()+"://" + esConfig.getHostname() +
":" + esConfig.getPort() + "/" + esConfig.getIndex() + "/_bulk");
}
private CloseableHttpClient getHttpClient(ElasticSearchConfig esConfig) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
if(esConfig.getProtocol().equalsIgnoreCase("https")) {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else if(esConfig.getProtocol().equalsIgnoreCase("http"))
return HttpClients.createDefault();
return null;
}
private String generateJSONLD(R2RMLConfig config) throws JSONException, MalformedURLException, KarmaException, IOException{
InputStream is = config.getInput();
if(is != null) {
URL contextLocation = config.getContextUrl();
URLConnection contextConnection = contextLocation.openConnection();
GenericRDFGenerator rdfGen = new GenericRDFGenerator(null);
// Add the models in;
R2RMLMappingIdentifier modelIdentifier = new R2RMLMappingIdentifier(
"generic-model", config.getR2rmlUrl());
rdfGen.addModel(modelIdentifier);
Model model = rdfGen.getModelParser("generic-model").getModel();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
JSONTokener token = new JSONTokener(contextConnection.getInputStream());
ContextIdentifier contextId = new ContextIdentifier("generic-context", contextLocation);
JSONKR2RMLRDFWriter writer = new JSONKR2RMLRDFWriter(pw);
writer.setGlobalContext(new org.json.JSONObject(token), contextId);
RDFGeneratorRequest request = generateRDFRequest("generic-model", model, "Karma-Web-Services", is, config, writer);
rdfGen.generateRDF(request);
String rdf = sw.toString();
return rdf;
}
return null;
}
private RDFGeneratorRequest generateRDFRequest(String modelName, Model model, String sourceName, InputStream is, R2RMLConfig config, KR2RMLRDFWriter writer) {
RDFGeneratorRequest request = new RDFGeneratorRequest(modelName, sourceName);
request.addWriter(writer);
request.setInputStream(is);
request.setDataType(config.getContentType());
request.setAddProvenance(false);
request.setMaxNumLines(config.getMaxNumLines());
request.setEncoding(config.getEncoding());
request.setDelimiter(config.getColumnDelimiter());
request.setTextQualifier(config.getTextQualifier());
request.setDataStartIndex(config.getDataStartIndex());
request.setHeaderStartIndex(config.getHeaderStartIndex());
request.setWorksheetIndex(config.getWorksheetIndex());
String rootTripleMap = config.getContextRoot();
if(rootTripleMap != null && !rootTripleMap.isEmpty()) {
StmtIterator itr = model.listStatements(null, model.getProperty(Uris.KM_NODE_ID_URI), rootTripleMap);
Resource subject = null;
while (itr.hasNext()) {
subject = itr.next().getSubject();
}
if (subject != null) {
itr = model.listStatements(null, model.getProperty(Uris.RR_SUBJECTMAP_URI), subject);
while (itr.hasNext()) {
rootTripleMap = itr.next().getSubject().toString();
}
}
}
request.setStrategy(new UserSpecifiedRootStrategy(rootTripleMap));
return request;
}
//TODO find a way to refactor this out. Also in servletstart
public static void initContextParameters(ServletContext ctx, ServletContextParameterMap contextParameters)
{
Enumeration<?> params = ctx.getInitParameterNames();
ArrayList<String> validParams = new ArrayList<String>();
for (ContextParameter param : ContextParameter.values()) {
validParams.add(param.name());
}
while (params.hasMoreElements()) {
String param = params.nextElement().toString();
if (validParams.contains(param)) {
ContextParameter mapParam = ContextParameter.valueOf(param);
String value = ctx.getInitParameter(param);
contextParameters.setParameterValue(mapParam, value);
}
}
//String contextPath = ctx.getRealPath(File.separator);
String contextPath = ctx.getRealPath("/"); //File.separator was not working in Windows. / works
contextParameters.setParameterValue(ContextParameter.WEBAPP_PATH, contextPath);
}
private void initialization(ServletContext context) throws KarmaException {
ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getDefault();
initContextParameters(context, contextParameters);
ContextParametersRegistry contextParametersRegistry = ContextParametersRegistry.getInstance();
contextParameters = contextParametersRegistry.registerByKarmaHome(null);
UpdateContainer uc = new UpdateContainer();
KarmaMetadataManager userMetadataManager = new KarmaMetadataManager(contextParameters);
userMetadataManager.register(new UserPreferencesMetadata(contextParameters), uc);
userMetadataManager.register(new UserConfigMetadata(contextParameters), uc);
userMetadataManager.register(new PythonTransformationMetadata(contextParameters), uc);
PythonRepository pythonRepository = new PythonRepository(false, contextParameters.getParameterValue(ContextParameter.USER_PYTHON_SCRIPTS_DIRECTORY));
PythonRepositoryRegistry.getInstance().register(pythonRepository);
SemanticTypeUtil.setSemanticTypeTrainingStatus(false);
ModelingConfiguration modelingConfiguration = ModelingConfigurationRegistry.getInstance().register(contextParameters.getId());
modelingConfiguration.setLearnerEnabled(false); // disable automatic learning // learning
}
}
|
package com.verce.forwardmodelling;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.File;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;
import java.util.zip.*;
import java.util.TimeZone;
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Properties;
import java.util.Collections;
import java.util.Comparator;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.bind.DatatypeConverter;
import java.security.PrivateKey;
import java.security.KeyFactory;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.CharPool;
import com.liferay.portal.kernel.util.HttpUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
import com.liferay.portlet.documentlibrary.DuplicateFileException;
import com.liferay.util.bridges.mvc.MVCPortlet;
import hu.sztaki.lpds.pgportal.services.asm.ASMJob;
import hu.sztaki.lpds.pgportal.services.asm.ASMService;
import hu.sztaki.lpds.pgportal.services.asm.ASMWorkflow;
import hu.sztaki.lpds.pgportal.services.asm.beans.ASMRepositoryItemBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.WorkflowInstanceBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.RunningJobDetailsBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.ASMResourceBean;
import hu.sztaki.lpds.pgportal.services.asm.constants.RepositoryItemTypeConstants;
import hu.sztaki.lpds.pgportal.services.asm.constants.DownloadTypeConstants;
import hu.sztaki.lpds.pgportal.service.base.data.WorkflowData;
import hu.sztaki.lpds.pgportal.service.base.PortalCacheService;
import hu.sztaki.lpds.dcibridge.client.ResourceConfigurationFace;
import hu.sztaki.lpds.information.local.InformationBase;
import hu.sztaki.lpds.pgportal.service.workflow.RealWorkflowUtils;
import hu.sztaki.lpds.wfs.com.WorkflowConfigErrorBean;
import hu.sztaki.lpds.pgportal.services.asm.constants.StatusConstants;
import hu.sztaki.lpds.information.com.ServiceType;
import hu.sztaki.lpds.wfs.com.RepositoryWorkflowBean;
import hu.sztaki.lpds.repository.service.veronica.commons.RepositoryFileUtils;
import hu.sztaki.lpds.wfs.inf.PortalWfsClient;
import hu.sztaki.lpds.storage.inf.PortalStorageClient;
import hu.sztaki.lpds.pgportal.services.asm.exceptions.upload.*;
import com.verce.forwardmodelling.Constants;
import org.json.*;
public class ForwardPortlet extends MVCPortlet{
ASMService asm_service = null;
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException
{
System.out.println("
if(resourceRequest.getResourceID().equals("uploadFile"))
uploadFile(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submit"))
submitSimulationWorkflow(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submitDownloadWorkflow"))
submitDownloadWorkflow(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submitProcessingWorkflow"))
submitProcessingWorkflow(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadOutput"))
downloadOutput(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("deleteWorkflow"))
deleteWorkflow(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("meshVelocityModelUpload"))
meshVelocityModelUpload(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadMeshDetails"))
downloadMeshDetails(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadVelocityModelDetails"))
downloadVelocityModelDetails(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("getWorkflowList"))
getWorkflowList(resourceRequest, resourceResponse);
}
public JSONObject getProvenanceWorkflows(ResourceRequest req, ResourceResponse res) {
// int offset = Integer.parseInt(ParamUtil.getString(req, "start"));
// int limit = Integer.parseInt(ParamUtil.getString(req, "limit"));
int offset = 0;
int limit = 1000;
JSONObject jsonObject = new JSONObject();
try {
String username = PortalUtil.getUser(req).getScreenName();
HttpServletRequest servletRequest = PortalUtil.getHttpServletRequest(req);
String url = PortalUtil.getPortalURL(servletRequest) + "/j2ep-1.0/prov/workflow/user/"+username+"?start="+offset+"&limit="+limit;
System.out.println("Fetching provenance workflows from " + url);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
InputStream response = connection.getInputStream();
String jsonString = inputStreamToString(response);
jsonObject = new JSONObject(jsonString);
} catch (Exception e) {
System.out.println("ERROR: Failed to get provenance workflows - " + e.getMessage());
}
return jsonObject;
}
public void getWorkflowList(ResourceRequest req, ResourceResponse res) {
int offset = Integer.parseInt(ParamUtil.getString(req, "start"));
int limit = Integer.parseInt(ParamUtil.getString(req, "limit"));
String filterString = ParamUtil.getString(req, "filter");
HashMap<String, String> filters = new HashMap<String, String>();
if (filterString != null && !"".equals(filterString)) {
JSONArray filterList = new JSONArray(filterString);
for (int ii = 0; ii < filterList.length(); ii++) {
JSONObject filter = filterList.getJSONObject(ii);
filters.put(filter.getString("property"), filter.getString("value"));
}
}
System.out.println("Fetching runs " + offset + " - " + (offset + limit) + " of user " + req.getRemoteUser() + " with filters: " + filters);
try{
asm_service = ASMService.getInstance();
ArrayList<ASMWorkflow> importedWfs = asm_service.getASMWorkflows(req.getRemoteUser());
String type = filters.get("prov:type");
if (type != null) {
java.util.Iterator<ASMWorkflow> iter = importedWfs.iterator();
while (iter.hasNext()) {
ASMWorkflow workflow = iter.next();
// remove those workflows that begin with a prefix that doesn't match type
if (workflow.getWorkflowName().indexOf(type + "_") >= 0) {
} else if (
workflow.getWorkflowName().indexOf("simulation_") >= 0
|| workflow.getWorkflowName().indexOf("download_") >= 0
|| workflow.getWorkflowName().indexOf("processing_") >= 0
|| workflow.getWorkflowName().indexOf("misfit_") >= 0
) {
iter.remove();
}
}
}
Collections.sort(importedWfs, new Comparator<ASMWorkflow>() {
// sort by date from the workflow name in reverse order
public int compare(ASMWorkflow wf1, ASMWorkflow wf2) {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd-hhmmss");
try {
Date wf2date = ft.parse(wf2.getWorkflowName().substring(wf2.getWorkflowName().lastIndexOf("_")+1));
Date wf1date = ft.parse(wf1.getWorkflowName().substring(wf1.getWorkflowName().lastIndexOf("_")+1));
return wf2date.compareTo(wf1date);
} catch (Exception e) {
System.out.println(e);
return 0;
}
}
});
JSONObject provWorkflows = getProvenanceWorkflows(req, res);
JSONArray list = provWorkflows.optJSONArray("runIds");
JSONObject result = new JSONObject();
JSONArray array = new JSONArray();
result.put("list", array);
result.put("totalCount", importedWfs.size());
for(int ii = offset; ii < Math.min(offset + limit, importedWfs.size()); ii++) {
ASMWorkflow wf = importedWfs.get(ii);
if (wf == null) {
System.out.println("**** Workflow null");
break;
}
//wf.getWorkflowName() is formated: (submitedName+RandomID)_YYYY-MM-DD-TTTTTT
//wfDate is YYYY-MM-DD
//wfDate2 is YYYY-MM-DD-TTTTTT (used to sort the results)
//wfName is submitedName+RandomID
String wfDate = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1, wf.getWorkflowName().lastIndexOf("-"));
String wfDate2 = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1);
String wfName = wf.getWorkflowName().substring(0,wf.getWorkflowName().lastIndexOf("_"));
String status = wf.getStatusbean().getStatus();
// only fetch status for runs that are not already stopped
if (!status.equals("ERROR") && !status.equals("FINISHED") && !status.equals("WORKFLOW_SUSPENDING")) {
WorkflowInstanceBean wfIB = asm_service.getDetails(req.getRemoteUser(), wf.getWorkflowName());
HashMap<String,String> statuses = new HashMap();
if (wfIB != null) {
StatusConstants statusConstants = new StatusConstants();
for (RunningJobDetailsBean job : wfIB.getJobs()) {
if (job.getInstances().size() <= 0) {
statuses.put(job.getName(), "UNKNOWN");
continue;
}
statuses.put(job.getName(), statusConstants.getStatus(job.getInstances().get(0).getStatus()));
}
System.out.println(statuses);
}
String computeStatus = statuses.containsKey("COMPUTE") ? statuses.get("COMPUTE") : statuses.containsKey("Job0") ? statuses.get("Job0") : null;
String stageOutStatus = statuses.containsKey("STAGEOUT") ? statuses.get("STAGEOUT") : statuses.containsKey("Job1") ? statuses.get("Job1") : null;
if (statuses.containsValue("ERROR")) {
status = "ERROR";
} else if (computeStatus == null || "UNKNOWN".equals(computeStatus)) {
status = "INIT";
} else if ("PENDING".equals(computeStatus) || "INIT".equals(computeStatus)) {
status = "PENDING";
} else if ("RUNNING".equals(stageOutStatus)) {
status = "STAGE OUT";
} else if ("FINISHED".equals(stageOutStatus)) {
status = "FINISHED";
} else if ("RUNNING".equals(computeStatus)) {
status = "RUNNING";
} else {
// Fallback to overall workflow status
System.out.println("FALLBACK to workflow status");
}
}
JSONObject object = new JSONObject();
object
.put("name", wfName)
.put("desc", wf.getSubmissionText())
.put("status", status)
.put("date", wfDate)
.put("date2", wfDate2)
.put("workflowId", wf.getWorkflowName());
for (int jj = 0; jj < list.length(); ++jj) {
JSONObject provWorkflow = list.getJSONObject(jj);
if (!provWorkflow.getString("_id").equals(wfName)) {
continue;
}
object
.put("workflowName", provWorkflow.optString("workflowName"))
.put("grid", provWorkflow.optString("grid"))
.put("resourceType", provWorkflow.optString("resourceType"))
.put("resource", provWorkflow.optString("resource"))
.put("queue", provWorkflow.optString("queue"));
}
array.put(object);
}
HttpServletResponse response = PortalUtil.getHttpServletResponse(res);
PrintWriter out = response.getWriter();
out.print(result.toString());
out.flush();
out.close();
}
catch(Exception e)
{
System.out.println("[ForwardModellingPortlet.getWorkflowList] Could not update the workflow list");
e.printStackTrace();
}
}
public void updateWorkflowDescription(ActionRequest req, ActionResponse res)
{
asm_service = ASMService.getInstance();
String begName = ParamUtil.getString(req, "workflowId");
String newText = ParamUtil.getString(req, "newText");
ArrayList<ASMWorkflow> importedWfs;
importedWfs = asm_service.getASMWorkflows(req.getRemoteUser());
for(ASMWorkflow wf : importedWfs)
{
if(wf.getWorkflowName().startsWith(begName))
{
wf.setSubmissionText(newText);
System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Description in workflow "+begName+" has been updated to "+newText+" by user "+req.getRemoteUser());
return;
}
}
System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Error! Workflow "+begName+" could not be found");
}
private void deleteWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
{
String userId = resourceRequest.getRemoteUser();
try{
asm_service = ASMService.getInstance();
String wfId = ParamUtil.getString(resourceRequest, "workflowId");
String encryptedIrodsSession = ParamUtil.getString(resourceRequest, "encryptedIrodsSession");
String irodsSession = decryptIrodsSession(encryptedIrodsSession);
asm_service.abort(userId, wfId); //TODO: fixme!
asm_service.DeleteWorkflow(userId, wfId);
System.out.println("[ForwardModellingPortlet.delete] workflow "+wfId+" has been deleted by user "+userId);
deleteFromIrods(irodsSession);
}
catch(Exception e)
{
catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.delete] Exception catched!! User :"+userId);
}
}
private void deleteFromIrods(String irodsSession) {
String url = "https://dir-irods.epcc.ed.ac.uk/irodsweb/services/delete.php";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String ruri = "jonas.UEDINZone@dir-irods.epcc.ed.ac.uk:1247/UEDINZone/home/jonas";
String files = "Newfile.txt";
// String dirs[] = "";
try {
String query = String.format("ruri=%s&files[]=%s", // or &dirs[]=%s
URLEncoder.encode(ruri, charset),
URLEncoder.encode(files, charset));
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
connection.setRequestProperty("Cookie", "PHPSESSID="+irodsSession);
OutputStream output = connection.getOutputStream();
output.write(query.getBytes(charset));
InputStream response = connection.getInputStream();
System.out.println(inputStreamToString(response));
} catch(Exception e) {
System.out.println(e);
}
}
private String decryptIrodsSession(String encryptedIrodsSession) {
byte[] irodsSession = null;
try {
byte[] keyBytes = DatatypeConverter.parseBase64Binary("MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDxmcVFGI9PMO5Z\n0Ukw5POpT0N8izhMM3zWYG9rfhJ48Gcbwr20P+obK7pUTLhkswReW62foY1SHY6c\nf50jL5MFXVCrg4Hxby0Vx49P4nBz66Kr4bAB1W1NuMTB1qTReGmNu0EQ70u2JlLO\nEBBwbOTv72zBssEBQRNy8q+Jo5b5BDjQ+0rpVwfD3J7fQ8wurAPklB6ekXK8jelx\nyKulJvUSPGjo9B+LbH+FLvQmZqdRP97MHzCc63nPxXHpV+y5Jr8crP8SEtkfy+9U\nSfTdnBkeFpvp6Ucje8KPBm6EHK4SShohjxKgzR0uXvar9NFMnukLO9lmc6yXxGWo\n1E9H980/b4vOR5I4Ts+XGY3oA3J9N8hIVJg4pvYUES8+UpDVoYsIgXTStQhvjL/5\n87n3td6YtZZPANDU+a4XSWIoGlhmeLUeNgaf4BGfH2icp5rGax2wyc2G4M7+4F7w\nDmnNgHR63GGDR86CU5kmSsO/vd1lm1eZAbiQKurscPh1PS3mwwvEmfQVXPDO+o8T\nns7+Z0SVRRLdEe+B9fR0YrAdIYM+mMWz+QLmXbFbN+WMghRWJQYCL4GvMNv5RvRZ\nnUKyiHziSEGkLDvJWkKp1QdlOVs80vq1g0Gsfmgs5oeGRVMctvrcrkbd5N0MJtXz\nW1FmisvDirFGpSYFZB2hIgiVna2stQIDAQABAoICAGdAODZXUKefWb2423ax4hAx\nd736IY0vU+KqQ/PEZVCaLPaIO1qVFg+WmIL+Zq9icjOBKqpV+HdnelMXlqg65LIe\nNyOViCsOQE5WgsC5HSXtRg/+26Fs/NGCbVQJz1ZWB4YyyJPcMJcfubOm2d+yKgUA\nZZJCOom2rgEqBirkZtj1HPLy8gjW0NK7ronsB47KpL9DLfLGZip+241tHS3vgDzS\n5GLqMbD8JWNdtanTpR3sFeNWUQg++kf5Mb1vfhOCo5o1tKycsX4NQbLcCHHNDE73\nippkv6pCcdt9/C0ptJrMYG6HHobqIdZ3byP99JSyNRY/9aD7Pn99x5RnZ5pyJJxr\nErhm+ds4L9hVPHo3C5yhbtj+73MaEGA21UrKqCD9aTi6XDSONNAA4AxA89IxNh0m\n/PSGSPEBkrSA1mvqyRVC6yL+pWVKXVhgXr+dlP42Lwsm+OpHPb95aQMDu+6NuOiu\n5HSjHF5MvF3NvO1sZ7/DKBUyFOIcKAYrPSIyQvUn6ifKqMC047MxQqBBHb445iVk\nhtmvBjzX/BYD8W37S7dszGeA4L6ZAfqnG469Pu38vxDIZ5aGATL5CrikS2yjd501\nmxIgXVlpHPbvAyMbKt78ykHJFXIJMeFiDviT4Jg48JzITSYOuTK2dHFGdZDnPJIG\nFiqXweRgTrEVaZ6wpOIBAoIBAQD7RIcOmt5vCqXsKATg4J9LLqkZGe77LcvzkN7V\nU26BqHIayWxSwXv5l0C/HK2a/S8+3Oak/qaTDeINlgoqZPPB9dch6Yd6LNApep1W\nqQZTSJbU3VmOQgNtrpaeD2+Kof9mBECWVUhmjE3u5TB45HF1gtGSwvtunLl/KL4M\ncbdoXiyrVCNIWIhVTxfIVG/le7VEslfsVDk+NeYY5OHp115XoZq3PrB64vKCr0pC\nMfkSLTSnlF29bq6GGAl1/ZiIbNyx9bsreQQpDN5yDVxs/v1vkWSmXUg0uYfJ8bOp\ngInjh9keRqECC/jEyASJNFizPXnFdTra/EW6wlw7+1CcvMTRAoIBAQD2JqJRJiEK\nJuu4SSfDrWZ4TesnPAVJxGKqjCaZzckOrmU6+Hr7dIXXBArfpWCUoDO+4Fl8PLn3\nvS6MDvrmnmgl0NiTMjEK1TVaMBmHAzEcUWWCict73UgpH6x2SRbe3edkZwbPccFD\nv5rqzEAQ73udwKrSrbymkZignaaGKuWe+vWOrw0VgVCeLVLkUSz5hL2uzqh79t7a\neALq4vp2Gh55/rGq/JeiTrRhEJ7jQpABiz43fU4b+cAX+E2tHnwRIl6HYIhzWQUK\nsJDaSvYFfLGuWZuQHwHOEf6A+nzPglI+yOFCjA/hbyb7nkcy3Uwr0L6YVf+GMRih\ngSIziVHs8jKlAoIBAAcM+jk3sUwuYU+KI/DnfLDQY2BX8PPNai6wfwA/chdjUahc\nxJRh54eubduvA1QZDK1X54TzvFreBdzZu/lKkeh8bIgAFJQiE8lGLooS/iFyJQFe\nILg0NAJs5r8Ssc+TEiabsfBF/l0aTMmKVtzdlC12+UiD/igxb6cYzpRs0He2RMyd\n9Mt/6Ht0V7eAXw9ydDi0RHFWP7D2NDm4mnpEV9pfp4bC1JLuMV3na08GNfYDnLmj\nGSpKo80ReZp8/j29yEeaHKFwqOQ5/zf2FgTc9uGdk9RzQ6ZvGldZV/BGshfXZQlL\ndBMpoNZswmvTMzX8YKFg08D3WUGPWKU6PR3Y0jECggEBAJVR4m1vv+M0sRHd7u1Z\nJywbuGbYliyloWTsGA59M1ZgnLAlRBV+HiLNJPt+ixQeCsXjuuUOwZFzheUYwUNd\nHLiz9G12qSF1LSREwXeRjB0tk3KYvIOrPLcVq70loWYZHuFdTlhRHXhHp2Z/+O1N\nGaQc2INtOV+iOwBUIkyJgTnr60JfFoTRKWKLBBnU1H+Y8qg0XSi2HYJSAxMSFfXG\n6m3+/zBGgoXHUM0BFCGwo0MMgPWQYe2+l7Tyv8whDgom20ksWhn/CnvtmDGT/6Jc\nfjzRxviqlqG3cLg1O7l1yQalPWDtLkUG9JL29SH59Ncvji9DG/r/lX2DpIe26aff\nVLECggEAenj0YmvnybT1/kkTP4eys5bbBxaIA1Tb+HPL5OcgUMTF4tRXKfk3cI2W\nfKcmoOdGnvC8NL5FKSe6JRB8QmzrxiStgvDOZb0cL4UkUw2MHJthkOXPNsIJUVAc\nAAwsrUfJvNP6lWSpcrsi4tbo8aTID+ZHzFmVWst9urxkolI9gAVBMPorX/8OVPmL\n3nIUVMJhL9nIHlAUVEMXTDvygbT/pdRPLO9IdMDkNYSYpE4GUN5gmWEIo1wPMnB6\n25ry4acPP9GnD2SNhL2bOfNiEqqrtnPKZRSWgLI220V7BimIE9Vq/cGkvOlhqUX5\nb4O58E4g/r0nGSYFpU1lqdDFUBSSqg==");
// decrypt the text using the private key
PrivateKey privateKey =
KeyFactory.getInstance("RSA").generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(keyBytes));
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] input = DatatypeConverter.parseBase64Binary(encryptedIrodsSession);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayInputStream inStream = new ByteArrayInputStream(input);
CipherInputStream cipherInputStream = new CipherInputStream(inStream, cipher);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
outputStream.write(buf, 0, bytesRead);
}
irodsSession = outputStream.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(irodsSession);
}
private void submitDownloadWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
System.out.println(workflowId + " / " + ownerId);
JSONObject config = new JSONObject(resourceRequest.getParameterValues("config")[0]);
config.put("user_name", userSN);
config.put("user_id", userId);
System.out.println(config);
String runId = config.getString("runId");
String submitMessage = "Download workflow for " + config.getString("simulationRunId");
String importedWfId = importWorkflow(userId, ownerId, workflowId, runId);
File solverFile = FileUtil.createTempFile();
FileUtil.write(solverFile, config.toString());
// TODO check port numbers
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "Job0", "2");
// stagein => Sync for final workflow
// temporary for fake workflow
try {
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "sync", "0");
} catch (Exception e) {
System.out.println("Failed uploading config file");
e.printStackTrace();
}
// add vercepes.zip
String zipName = runId+".zip";
createZipFile("temp/"+zipName);
File tempZipFile = new File("temp/"+zipName);
String zipPublicPath = addFileToDL(tempZipFile, zipName, groupId, userSN, Constants.ZIP_TYPE);
zipPublicPath = portalUrl + zipPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Zip file created in the document library by "+userSN+", accessible in: "+zipPublicPath);
asm_service.placeUploadedFile(userId, tempZipFile, importedWfId, "Job0", "2");
Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
if(errorVector!=null && !errorVector.isEmpty())
{
for (WorkflowConfigErrorBean err : errorVector) {
System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+err.getErrorID()+"'! JobName: " + err.getJobName() + " userSN: "+userSN+", runId: "+runId);
if(err.getErrorID().contains("noproxy") || err.getErrorID().contains("proxyexpired"))
{
catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
return;
}
}
}
asm_service.submit(userId, importedWfId, submitMessage, "Never");
// Log resource information
ASMResourceBean resourceBean = asm_service.getResource(userId, importedWfId, "Job0");
System.out.println("RESOURCE type: " + resourceBean.getType() + ", grid: " + resourceBean.getGrid() + ", resource: " + resourceBean.getResource() + ", queue: " + resourceBean.getQueue());
JSONObject provenanceData = new JSONObject();
} catch (Exception e) {
e.printStackTrace();
}
}
private void submitProcessingWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
System.out.println(workflowId + " / " + ownerId);
String simulationRunId = resourceRequest.getParameterValues("runId")[0];
String runId = "processing_" + simulationRunId;
JSONObject stations = new JSONObject(resourceRequest.getParameterValues("stations")[0]);
JSONObject pipelines = new JSONObject(resourceRequest.getParameterValues("PEs")[0]);
System.out.println(runId);
System.out.println(stations);
System.out.println(pipelines);
String submitMessage = "Processing workflow for " + simulationRunId;
String importedWfId = importWorkflow(userId, ownerId, workflowId, runId);
File configFile = FileUtil.createTempFile();
FileUtil.write(configFile, stations.toString());
// temporary for fake workflow
try {
asm_service.placeUploadedFile(userId, configFile, importedWfId, "sync", "1");
} catch (Exception e) {
}
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
String eventUrl = resourceRequest.getParameterValues("quakemlURL")[0];
String portalUrl2 = PortalUtil.getPortalURL(resourceRequest);
if(portalUrl2.equals("http://localhost:8081")) {
portalUrl2 = "http://localhost:8080"; //TODO: careful
}
EventFile eventFile = downloadAndStoreEventFile(portalUrl, portalUrl2, eventUrl, runId, userSN, groupId);
File tmpFile = FileUtil.createTempFile();
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(tmpFile));
append.putNextEntry(new ZipEntry("pipelines.json"));
append.write(pipelines.toString().getBytes("utf-8"));
append.closeEntry();
append.putNextEntry(new ZipEntry("quakeml"));
FileInputStream fileInputStream = new FileInputStream(eventFile.file);
byte[] buffer = new byte[1024];
int charsRead = 0;
while ((charsRead = fileInputStream.read(buffer)) > 0) {
append.write(buffer, 0, charsRead);
};
append.closeEntry();
// close
fileInputStream.close();
append.close();
asm_service.placeUploadedFile(userId, tmpFile, importedWfId, "Job0", "1");
Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
if(errorVector!=null && !errorVector.isEmpty())
{
for (WorkflowConfigErrorBean err : errorVector) {
System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+err.getErrorID()+"'! JobName: " + err.getJobName() + " userSN: "+userSN+", runId: "+runId);
if(err.getErrorID().contains("noproxy") || err.getErrorID().contains("proxyexpired"))
{
catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
return;
}
}
}
asm_service.submit(userId, importedWfId, submitMessage, "Never");
// Log resource information
ASMResourceBean resourceBean = asm_service.getResource(userId, importedWfId, "Job0");
System.out.println("RESOURCE type: " + resourceBean.getType() + ", grid: " + resourceBean.getGrid() + ", resource: " + resourceBean.getResource() + ", queue: " + resourceBean.getQueue());
} catch (Exception e) {
e.printStackTrace();
}
}
private Vector<WorkflowConfigErrorBean> checkCredentialErrors(String userId, String importedWfId) throws Exception {
WorkflowData wfData = PortalCacheService.getInstance().getUser(userId).getWorkflow(importedWfId);
ResourceConfigurationFace rc=(ResourceConfigurationFace)InformationBase.getI().getServiceClient("resourceconfigure", "portal");
List resources = rc.get();
Vector<WorkflowConfigErrorBean> errorVector = (Vector<WorkflowConfigErrorBean>)RealWorkflowUtils.getInstance().getWorkflowConfigErrorVector(resources, userId, wfData);
if(errorVector!=null && !errorVector.isEmpty()) {
return errorVector;
}
return null;
}
private void submitSimulationWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException
{
try {
asm_service = ASMService.getInstance();
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
String solverType = ParamUtil.getString(resourceRequest, "solver");
String[] jsonContentArray = resourceRequest.getParameterValues("jsonObject");
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String workflowName = ParamUtil.getString(resourceRequest, "workflowName");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
String stationUrl = ParamUtil.getString(resourceRequest, "stationUrl");
String eventUrl = ParamUtil.getString(resourceRequest, "eventUrl");
String[] runIds = resourceRequest.getParameterValues("runId");
String stFileType = ParamUtil.getString(resourceRequest, "stationType");
String jobName = "Job0";
String submitMessage = ParamUtil.getString(resourceRequest, "submitMessage");
String nProc = ParamUtil.getString(resourceRequest, "nProc");
boolean stationDLFile = stationUrl.contains("documents");
File stationFile = null;
String stPublicPath;
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
Format formatter = new SimpleDateFormat("yyyyMMddHHmm");
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
String portalUrl2 = PortalUtil.getPortalURL(resourceRequest);
if(portalUrl2.equals("http://localhost:8081")) {
portalUrl2 = "http://localhost:8080"; //TODO: careful
}
// System.out.println("Try to fetch workflow zip from repository for workflow with ID: " + workflowId);
String job0bin = "";
Date job0binModified = new Date(0L);
// Hashtable hsh = new Hashtable();
// ServiceType st = InformationBase.getI().getService("wfs", "portal", hsh, new Vector());
// PortalWfsClient wfsClient = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
// wfsClient.setServiceURL(st.getServiceUrl());
// wfsClient.setServiceID(st.getServiceID());
// RepositoryWorkflowBean bean = new RepositoryWorkflowBean();
// bean.setId(Long.parseLong(workflowId));
// bean.setWorkflowType(RepositoryItemTypeConstants.Application);
// Vector wfList = wfsClient.getRepositoryItems(bean);
// if (wfList == null) {
// throw new Exception("Not valid wf list !");
// for (Object wfBeanObject : wfList) {
// RepositoryWorkflowBean wfBean = (RepositoryWorkflowBean) wfBeanObject;
// String relativePath = wfBean.getZipRepositoryPath();
// String fullPath = new String(RepositoryFileUtils.getInstance().getRepositoryDir() + relativePath);
// ZipFile zipFile = new ZipFile(fullPath);
// Enumeration<? extends ZipEntry> entries = zipFile.entries();
// while (entries.hasMoreElements()) {
// ZipEntry entry = (ZipEntry) entries.nextElement();
// System.out.println(entry.getName());
// if (entry.getName().indexOf("Job0/execute.bin") >= 0) {
// job0bin = inputStreamToString(zipFile.getInputStream(entry));
// job0binModified = new Date(entry.getTime());
// // System.out.println(job0bin);
// break;
// zipFile.close();
if(!stationDLFile) //1a. create StationFile and store it
{
stationFile = FileUtil.createTempFile();
URL wsUrl = new URL(portalUrl2+stationUrl);
FileUtil.write(stationFile, wsUrl.openStream());
String stFileName = "stations_"+runIds[0];
stPublicPath = addFileToDL(stationFile, stFileName, groupId, userSN, Constants.WS_TYPE);
stPublicPath = portalUrl + stPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Stations file created in the document library by "+userSN+", accessible in: "+stPublicPath);
stFileType = Constants.STXML_TYPE;
}
else //1b. Retrieve StationFile
{
String[] urlParts = stationUrl.split("/");
long folderId = Long.parseLong(urlParts[urlParts.length - 2]);
String stFileName = urlParts[urlParts.length - 1];
FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, stFileName);
stationFile = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
stPublicPath = stationUrl;
}
// 2. EventFile (QuakeML)
EventFile eventFile = downloadAndStoreEventFile(portalUrl, portalUrl2, eventUrl, runIds[0], userSN, groupId);
//3. Generate zip file
String zipName = runIds[0]+".zip";
createZipFile("temp/"+zipName);
File tempZipFile = new File("temp/"+zipName);
String zipPublicPath = addFileToDL(tempZipFile, zipName, groupId, userSN, Constants.ZIP_TYPE);
zipPublicPath = portalUrl + zipPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Zip file created in the document library by "+userSN+", accessible in: "+zipPublicPath);
for(int i=0;i<jsonContentArray.length;i++)
{
String jsonContent = jsonContentArray[i];
//4. Import the workflow
String importedWfId = importWorkflow(userId, ownerId, workflowId, runIds[i]);
//5. Create the solver file and store it
File solverFile = FileUtil.createTempFile();
FileUtil.write(solverFile, jsonContent);
String fileName = solverType+"_"+runIds[i]+".json";
String publicPath = addFileToDL(solverFile, fileName, groupId, userSN, Constants.SOLVER_TYPE);
publicPath = portalUrl + publicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Solver file created in the document library by "+userSN+", accessible in: "+publicPath);
//6. Upload files
asm_service.placeUploadedFile(userId, stationFile, importedWfId, jobName, "0");
asm_service.placeUploadedFile(userId, eventFile.file, importedWfId, jobName, "1");
asm_service.placeUploadedFile(userId, solverFile, importedWfId, jobName, "2");
asm_service.placeUploadedFile(userId, tempZipFile, importedWfId, jobName, "3");
try {
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "sync", "0");
} catch (Upload_GeneralException exception) {
System.out.println("*** Port 0 on job Sync doesn't exist.");
}
//8. Change number of MPI nodes
if(solverType.toLowerCase().contains(Constants.SPECFEM_TYPE))
{
System.out.println("[ForwardModellingPortlet.submitSolver] Set number of processors to "+nProc+", by "+userSN);
asm_service.setJobAttribute(userId, importedWfId, jobName, "gt5.keycount", nProc);
}
//TODO: we should check just once
Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
if(errorVector!=null && !errorVector.isEmpty())
{
for (WorkflowConfigErrorBean er : errorVector) {
System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+er.getErrorID()+"'! userSN: "+userSN+", runId: "+runIds[i]);
if(er.getErrorID().contains("noproxy") || er.getErrorID().contains("proxyexpired"))
{
catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
return;
}
}
}
asm_service.submit(userId, importedWfId, submitMessage, "Never");
// Log resource information
ASMResourceBean resourceBean = asm_service.getResource(userId, importedWfId, jobName);
System.out.println("RESOURCE type: " + resourceBean.getType() + ", grid: " + resourceBean.getGrid() + ", resource: " + resourceBean.getResource() + ", queue: " + resourceBean.getQueue());
//10. Add run info in the Provenance Repository
saveSimulationProvenance(userSN, runIds[i], submitMessage, workflowName, workflowId, importedWfId, stPublicPath, eventFile.url, publicPath, zipPublicPath, stFileType, job0bin, job0binModified, resourceBean.getType(), resourceBean.getGrid(), resourceBean.getResource(), resourceBean.getQueue());
System.out.println("[ForwardModellingPortlet.submitSolver] Submission finished: "+userSN+", "+runIds[i]+", "+submitMessage+", "+workflowId+", "+importedWfId);
}
tempZipFile.delete();
}
catch (Exception e)
{
catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.submitSolver] Exception catched!");
}
}
class EventFile {
public File file;
public String url;
public EventFile() {
}
}
public EventFile downloadAndStoreEventFile(String portalURL, String portalURL2, String eventUrl, String runId, String userSN, long groupId) throws Exception {
EventFile eventFile = new EventFile();
System.out.println("**++** Using event from " + eventUrl);
if(!eventUrl.contains("documents")) { // eventfile not from documentLibrary
eventFile.file = FileUtil.createTempFile();
URL wsUrl = new URL(portalURL2+eventUrl);
FileUtil.write(eventFile.file, wsUrl.openStream());
String evFileName = "events_"+runId;
eventFile.url = portalURL + addFileToDL(eventFile.file, evFileName, groupId, userSN, Constants.WS_TYPE);
System.out.println("[ForwardModellingPortlet.submitSolver] Events file created in the document library by "+userSN+", accessible in: "+eventFile.url);
} else {
String[] urlParts = eventUrl.split("/");
long folderId = Long.parseLong(urlParts[urlParts.length - 2]);
String evFileName = urlParts[urlParts.length - 1];
FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, evFileName);
eventFile.file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
eventFile.url = eventUrl;
}
return eventFile;
}
public void downloadOutput(ResourceRequest resourceRequest,
ResourceResponse resourceResponse)
{
asm_service = ASMService.getInstance();
String userId = resourceRequest.getRemoteUser();
String wfId = ParamUtil.getString(resourceRequest, "workflowId");
resourceResponse.setContentType("application/zip");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"logs.zip\"");
try{
asm_service.getWorkflowOutputs(userId, wfId, resourceResponse);
}
catch(Exception e)
{
System.out.println("[ForwardModellingPortlet.downloadOutput] Exception caught!!");
e.printStackTrace();
// TODO send error to client
}
}
private void meshVelocityModelUpload(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
String meshURL = uploadRequest.getParameter("mesh-link");
if (uploadRequest.getFileName("mesh-file") != null && uploadRequest.getFileName("mesh-file").length() > 0) {
meshURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("mesh-file"), uploadRequest.getFileName("mesh-file"), "mesh");
}
System.out.println(meshURL);
if (meshURL == null || meshURL.equals("")) {
resourceResponse.getWriter().write("{ success: false, errors: { \"mesh-file\": \"No mesh file or URL included or included file too large.\" } }");
return;
}
String velocityModelURL = uploadRequest.getParameter("velocity-model-link");
if (uploadRequest.getFileName("velocity-model-file") != null && uploadRequest.getFileName("velocity-model-file").length() > 0) {
velocityModelURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("velocity-model-file"), uploadRequest.getFileName("velocity-model-file"), "velocitymodel");
}
System.out.println(velocityModelURL);
if (velocityModelURL == null || velocityModelURL.equals("")) {
resourceResponse.getWriter().write("{ success: false, errors: { \"velocity-model-file\": \"No velocity model file or URL included or included file too large.\" } }");
return;
}
String minLat = uploadRequest.getParameter("min_lat");
String maxLat = uploadRequest.getParameter("max_lat");
String minLon = uploadRequest.getParameter("min_lon");
String maxLon = uploadRequest.getParameter("max_lon");
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(InternetAddress.parse("admin@verce.eu")[0]);
// message.setReplyTo(InternetAddress.parse(PortalUtil.getUser(resourceRequest).getDisplayEmailAddress()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("spinuso@knmi.nl, emanuele.casarotti@ingv.it, federica.magnoni@ingv.it, " + PortalUtil.getUser(resourceRequest).getDisplayEmailAddress()));
message.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse("jonas.matser@knmi.nl"));
message.setSubject("VERCE: Mesh and velocity model submitted");
message.setText(
"User " + PortalUtil.getUser(resourceRequest).getScreenName() + " has submitted a new mesh and velocity model for review.\n" +
"\n" +
"The mesh and velocity model are available at the following links.\n" +
"Mesh: " + meshURL + "\n" +
"Velocity Model: " + velocityModelURL + "\n" +
"\n" +
"The bounds for the mesh are:\n" +
"Minimum latitude: " + minLat + "\n" +
"Maximum latitude: " + maxLat + "\n" +
"Minimum longitude: " + minLon + "\n" +
"Maximum longitude: " + maxLon + "\n" +
"\n" +
"The user also added the following note:\n" +
HtmlUtil.escape(uploadRequest.getParameter("note"))
);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
resourceResponse.getWriter().write("{ success: true }");
} catch (Exception e) {
System.out.println(e);
catchError(e, resourceResponse, "500", e.getMessage());
}
}
private void uploadFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
{
resourceResponse.setContentType("text/html");
try {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
InputStream inputStream = uploadRequest.getFileAsStream("form-file");
if(inputStream == null){
throw new Exception("[ForwardModellingPortlet.uploadFile] ERROR: FileInput \"form-file\" not found in request.");
}
String name = ParamUtil.getString(uploadRequest, "name");
String filetype = ParamUtil.getString(uploadRequest, "filetype");
String publicPath = saveFileUpload(resourceRequest, inputStream, name, filetype);
String successString = " {'success':'true', 'path':'"+publicPath+"'}";
resourceResponse.getWriter().write(successString);
} catch (Exception e) {
catchError(e, resourceResponse, "500", e.getMessage());
}
}
private String saveFileUpload(ResourceRequest resourceRequest, InputStream inputStream, String name, String filetype)
throws Exception
{
if(PortalUtil.getUser(resourceRequest)==null)
throw new Exception("[ForwardModellingPortlet.uploadFile] No user logged in!");
String userSN = PortalUtil.getUser(resourceRequest).getScreenName();
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
File file = FileUtil.createTempFile(inputStream);
if (file.length() < 1)
{
throw new Exception("[ForwardModellingPortlet.uploadFile] Failed!! The file is empty. User: "+userSN);
}
String publicPath = addFileToDL(file, name, groupId, userSN, filetype);
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
publicPath = portalUrl+publicPath;
System.out.println("[ForwardModellingPortlet.uploadFile] File created in the document library by user "+userSN+", accessible in: "+publicPath);
return publicPath;
}
private String inputStreamToString(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[1024];
int charsRead = 0;
while ((charsRead = inputStreamReader.read(buffer)) > 0) {
stringBuilder.append(buffer, 0, charsRead);
};
inputStream.close();
return stringBuilder.toString();
}
private void downloadMeshDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
String solverName = ParamUtil.getString(resourceRequest, "solver");
String meshName = ParamUtil.getString(resourceRequest, "meshName");
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
if(con.getResponseCode()!=200) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + con.getResponseCode());
return;
}
String input = inputStreamToString(con.getInputStream());
JSONObject jsonObject = new JSONObject(input);
JSONArray meshes = jsonObject.getJSONArray("meshes");
JSONObject mesh = null;
for (int ii = 0; ii < meshes.length(); ii++) {
mesh = meshes.getJSONObject(ii);
if (mesh.getString("name").equals(meshName)) {
break;
}
}
if (mesh == null) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: Mesh " + meshName + " not found for solver " + solverName);
return;
}
String details = mesh.getString("details");
resourceResponse.setContentType("application/text");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"mesh-details.txt\"");
resourceResponse.getWriter().write(details);
} catch (Exception e) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + e.getStackTrace());
}
}
private void downloadVelocityModelDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
String solverName = ParamUtil.getString(resourceRequest, "solver");
String meshName = ParamUtil.getString(resourceRequest, "meshName");
String velocityModelName = ParamUtil.getString(resourceRequest, "velocityModelName");
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
if(con.getResponseCode()!=200)
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + con.getResponseCode());
InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[1024];
int charsRead = 0;
while ((charsRead = inputStreamReader.read(buffer)) > 0) {
stringBuilder.append(buffer, 0, charsRead);
};
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray meshes = jsonObject.getJSONArray("meshes");
JSONObject mesh = null;
for (int ii = 0; ii < meshes.length(); ii++) {
mesh = meshes.getJSONObject(ii);
if (mesh.getString("name").equals(meshName)) {
break;
}
}
if (mesh == null) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Mesh " + meshName + " not found for solver " + solverName);
return;
}
JSONArray velocityModels = mesh.getJSONArray("velmod");
JSONObject velocityModel = null;
for (int ii = 0; ii < velocityModels.length(); ii++) {
velocityModel = velocityModels.getJSONObject(ii);
if (velocityModel.getString("name").equals(velocityModelName)) {
break;
}
}
if (velocityModel == null) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Velocity Model " + velocityModelName + " not found for Mesh " + meshName + " and solver " + solverName);
return;
}
String details = velocityModel.getString("details");
resourceResponse.setContentType("application/text");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"velocitymodel-details.txt\"");
resourceResponse.getWriter().write(details);
} catch (Exception e) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + e.getStackTrace());
}
}
private String addFileToDL(File file, String name, long groupId, String userSN, String filetype)
throws SystemException, PortalException, Exception
{
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
String sourceFileName = file.getName();
String mimeType = "text/plain";
String description = Constants.DOC_DESC + userSN;
String changeLog = "1.0";
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
long folderId = getFolderId(repositoryId, userSN, filetype, serviceContext);
// Search for unused file number
// Don't use recursion because of stack limit (although the algorithm shouldn't run that deep)
// Two step algorithm
// 1. Find the first n (2^m) that is not in use be an existing file
// 2. Do a binary search between 2^(m-1) and 2^m for the first non-existing filename
// Define lower and upper bounds for searching
int lowerBound = 0;
int upperBound = 0;
// define midpoint for binary search part
int mid = 0;
// keep track of if we're search upwards or in binary search
boolean up = true;
String filename = name;
do {
try {
if (up) {
filename = name + (upperBound > 0 ? "_"+upperBound : "");
} else {
filename = name + (mid > 0 ? "_"+mid : "");
}
// try if file exists
DLAppServiceUtil.getFileEntry(repositoryId, folderId, filename);
} catch (PortalException e) {
// File doesnt Exist
if (up) {
// lowest n = 2^m found that's not in use
// start binary search
up = false;
continue;
} else {
// continue binary search in [lowerbound-mid]
upperBound = mid;
mid = lowerBound + (upperBound - lowerBound) / 2;
continue;
}
}
// File exists
if (up) {
// look at next n = 2^m if it's in use
lowerBound = Math.max(upperBound, 1);
upperBound = lowerBound * 2;
} else {
// continue binary search in [mid+1-lowerbound]
lowerBound = mid + 1;
mid = lowerBound + (upperBound - lowerBound) / 2;
}
} while (lowerBound != upperBound);
// set final filename
filename = name + (lowerBound > 0 ? "_"+lowerBound : "");
DLAppServiceUtil.addFileEntry(repositoryId, folderId, sourceFileName, mimeType, filename, description, changeLog, file, serviceContext);
System.out.println("[ForwardModellingPortlet.addFileToDL] The file "+filename+" has been created.");
return "/documents/" + groupId + "/" + folderId + "/" + HttpUtil.encodeURL(HtmlUtil.unescape(filename));
}
/*
* get the folderId for the specific user following the directory structure:
* root/Forwar Modelling/userSN/station (XML)
* if it doesn't exist it is created
*/
private long getFolderId(long repositoryId, String userSN, String filetype, ServiceContext serviceContext) throws SystemException, PortalException
{
Folder folder = null;
String lastFolderName = "";
if(filetype.equals(Constants.EVENT_TYPE)) lastFolderName = Constants.EVENT_FOLDER_NAME;
if(filetype.equals(Constants.STXML_TYPE)) lastFolderName = Constants.STXML_FOLDER_NAME;
if(filetype.equals(Constants.STPOINTS_TYPE)) lastFolderName = Constants.STPOINTS_FOLDER_NAME;
if(filetype.equals(Constants.SOLVER_TYPE)) lastFolderName = Constants.SOLVER_FOLDER_NAME;
if(filetype.equals(Constants.WS_TYPE)) lastFolderName = Constants.WS_FOLDER_NAME;
if(lastFolderName.equals("")) lastFolderName = filetype;
try{
folder = DLAppServiceUtil.getFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME, Constants.BASE_FOLDER_DESC, serviceContext);
}
try{
folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), userSN);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), userSN, Constants.USER_FOLDER_DESC, serviceContext);
}
try{
folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), lastFolderName);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), lastFolderName, "", serviceContext);
}
return folder.getFolderId();
}
private String getFileAsString(File file) throws FileNotFoundException, IOException{
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
sb.append(dis.readLine() + "\n");
}
fis.close();
bis.close();
dis.close();
return sb.toString();
}
private static final byte[] BUFFER = new byte[4096 * 1024];
private static void copy(InputStream input, OutputStream output) throws IOException
{
int bytesRead;
while ((bytesRead = input.read(BUFFER))!= -1) {
output.write(BUFFER, 0, bytesRead);
}
}
private void createZipFile(String fileName) throws IOException
{
ZipFile zipFile = new ZipFile("data/verce-hpc-pe.zip");
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(fileName));
// copy contents from existing war
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(zipFile.getInputStream(e), append);
}
append.closeEntry();
}
// close
zipFile.close();
append.close();
System.out.println("[ForwardModellingPortlet.createZipFile] File created in the server file system: "+fileName);
}
private void createMeshModelZipFile(String fileName, String meshFileName, String modelFileName) throws IOException
{
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
zos.putNextEntry(new ZipEntry("meshfile"));
copy(new FileInputStream(meshFileName), zos);
zos.closeEntry();
zos.putNextEntry(new ZipEntry("modelfile"));
copy(new FileInputStream(modelFileName), zos);
zos.closeEntry();
zos.close();
}
private void saveSimulationProvenance(String userSN, String runId, String submitMessage, String wfName, String wfId, String asmRunId,
String stationUrl, String eventUrl, String solverUrl, String zipUrl, String stationFileType, String job0bin, Date job0binModified, String resourceType, String grid, String resource, String queue) {
String runType = "workflow_run";
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
if(stationFileType.equals(Constants.STPOINTS_TYPE)) stationFileType = Constants.MIMETYPE_PLAIN;
if(stationFileType.equals(Constants.STXML_TYPE)) stationFileType = Constants.MIMETYPE_XML;
JSONObject params = new JSONObject();
params.put("username", userSN)
.put("_id", runId)
.put("type", runType)
.put("prov:type", "simulation")
.put("description", submitMessage)
.put("workflowName", wfName)
.put("workflowId", wfId)
.put("system_id", asmRunId)
.put("startTime", nowAsISO)
.put("job0bin", job0bin)
.put("job0binModified", new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").format(job0binModified))
.put("resourceType", resourceType)
.put("grid", grid)
.put("resource", resource)
.put("queue", queue);
JSONArray input = new JSONArray();
input.put(new JSONObject().put("mime-type", stationFileType).put("name",Constants.ST_INPUT_NAME).put("url", stationUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_XML).put("name",Constants.EVENT_INPUT_NAME).put("url", eventUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_JSON).put("name",Constants.SOLVER_INPUT_NAME).put("url", solverUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_ZIP).put("name",Constants.ZIP_INPUT_NAME).put("url", zipUrl));
params.put("input", input);
updateProvenanceRepository(params);
}
private void updateProvenanceRepository(JSONObject params) {
try{
//TODO: put the url in a properties file
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/workflow/insert");
//HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept", "application/json");
// System.out.println("[updateProvenanceRepository] Params: "+params.toString());
String urlParameters = "prov="+URLEncoder.encode(params.toString(), "ISO-8859-1");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
if(con.getResponseCode()!=200)
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Error: " + con.getResponseCode());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Response: "+response.toString());
}
catch(Exception e)
{
// We log the exception but continue the normal flow
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Exception catched!!");
e.printStackTrace();
}
}
private String importWorkflow(String userId, String ownerId, String repositoryEntryId, String importedWfName) throws Exception
{
try
{
//asm_service = ASMService.getInstance();
String wfName = asm_service.ImportWorkflow(userId, importedWfName, ownerId, RepositoryItemTypeConstants.Application, repositoryEntryId);
System.out.println("[ForwardModellingPortlet.importWorkflow] Workflow "+repositoryEntryId+"("+ownerId+") with name "+importedWfName+" imported by user "+userId);
return wfName;
}
catch (Exception e) {
System.out.println("[ForwardModellingPortlet.importWorkflow] Exception catched! Could not import workflow "+repositoryEntryId+" from "+ownerId+", with name "+importedWfName);
throw e;
}
}
/*
* Sends the error through the response. Writes logMessage through the logs
* if e is not null prints the stackTrace through the logs
*/
private void catchError(Exception e, ResourceResponse res, String errorCode, String logMessage)
{
res.setContentType("text/html");
System.out.println("[ForwardModellingPortlet.catchError] Preparing response...");
try{
res.getWriter().write("{success: false, msg:\""+logMessage+"\"}"); //Submit call expects json success parameter
}catch(Exception e2)
{
System.out.println("[ForwardModellingPortlet.catchError] Could not write in response...");
}
res.setProperty(res.HTTP_STATUS_CODE, errorCode); //Ajax call expects status code
System.out.println(logMessage);
if(e!=null) e.printStackTrace();
}
}
|
package org.safehaus.subutai.core.peer.ui.forms;
import java.security.KeyStore;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.safehaus.subutai.common.peer.PeerException;
import org.safehaus.subutai.common.peer.PeerInfo;
import org.safehaus.subutai.common.peer.PeerStatus;
import org.safehaus.subutai.common.security.crypto.keystore.KeyStoreData;
import org.safehaus.subutai.common.security.crypto.keystore.KeyStoreManager;
import org.safehaus.subutai.common.settings.ChannelSettings;
import org.safehaus.subutai.common.util.JsonUtil;
import org.safehaus.subutai.common.util.RestUtil;
import org.safehaus.subutai.core.peer.ui.PeerManagerPortalModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.form.Form;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
/**
* Registration process should be handled in save manner so no middleware attacks occur. In order to get there peers
* need to exchange with public keys. This will create ssl layer by encrypting all traffic passing through their
* connection. So first initial handshake will be one direction, to pass keys through encrypted channel and register
* them in peers' trust stores. These newly saved keys will be used further for safe communication, with bidirectional
* authentication.
*
*
* TODO here still exists some issues concerned via registration/reject/approve requests. Some of them must pass through
* secure channel such as unregister process. Which already must be in bidirectional auth completed stage.
*/
public class PeerRegisterForm extends CustomComponent
{
private static final Logger LOG = LoggerFactory.getLogger( PeerRegisterForm.class.getName() );
public final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@AutoGenerated
private AbsoluteLayout mainLayout;
@AutoGenerated
private Table peersTable;
@AutoGenerated
private Button showPeersButton;
@AutoGenerated
private Button registerRequestButton;
@AutoGenerated
private TextField ipTextField;
private PeerManagerPortalModule module;
/**
* The constructor should first build the main layout, set the composition root and then do any custom
* initialization. <p/> The constructor will not be automatically regenerated by the visual editor.
*/
public PeerRegisterForm( final PeerManagerPortalModule module )
{
buildMainLayout();
setCompositionRoot( mainLayout );
this.module = module;
showPeersButton.click();
}
@AutoGenerated
private AbsoluteLayout buildMainLayout()
{
// common part: create layout
mainLayout = new AbsoluteLayout();
mainLayout.setImmediate( false );
mainLayout.setWidth( "100%" );
mainLayout.setHeight( "100%" );
// top-level component properties
setWidth( "100.0%" );
setHeight( "100.0%" );
// peerRegisterLayout
final AbsoluteLayout peerRegisterLayout = buildAbsoluteLayout_2();
mainLayout.addComponent( peerRegisterLayout, "top:20.0px;right:0.0px;bottom:-20.0px;left:0.0px;" );
return mainLayout;
}
@AutoGenerated
private AbsoluteLayout buildAbsoluteLayout_2()
{
// common part: create layout
AbsoluteLayout absoluteLayout = new AbsoluteLayout();
absoluteLayout.setImmediate( false );
absoluteLayout.setWidth( "100.0%" );
absoluteLayout.setHeight( "100.0%" );
// peerRegistration
final Label peerRegistration = new Label();
peerRegistration.setImmediate( false );
peerRegistration.setWidth( "-1px" );
peerRegistration.setHeight( "-1px" );
peerRegistration.setValue( "Peer registration" );
absoluteLayout.addComponent( peerRegistration, "top:0.0px;left:20.0px;" );
final Label IP = new Label();
IP.setImmediate( false );
IP.setWidth( "-1px" );
IP.setHeight( "-1px" );
IP.setValue( "IP" );
absoluteLayout.addComponent( IP, "top:36.0px;left:20.0px;" );
// ipTextField
ipTextField = new TextField();
ipTextField.setImmediate( false );
ipTextField.setWidth( "-1px" );
ipTextField.setHeight( "-1px" );
ipTextField.setMaxLength( 15 );
absoluteLayout.addComponent( ipTextField, "top:36.0px;left:150.0px;" );
// registerRequestButton
registerRequestButton = createRegisterButton();
absoluteLayout.addComponent( registerRequestButton, "top:160.0px;left:20.0px;" );
registerRequestButton = createRegisterButton();
// showPeersButton
showPeersButton = createShowPeersButton();
absoluteLayout.addComponent( showPeersButton, "top:234.0px;left:20.0px;" );
// peersTable
peersTable = new Table();
peersTable.setCaption( "Peers" );
peersTable.setImmediate( false );
peersTable.setWidth( "1000px" );
peersTable.setHeight( "283px" );
absoluteLayout.addComponent( peersTable, "top:294.0px;left:20.0px;" );
return absoluteLayout;
}
private Button createShowPeersButton()
{
showPeersButton = new Button();
showPeersButton.setCaption( "Show peers" );
showPeersButton.setImmediate( false );
showPeersButton.setWidth( "-1px" );
showPeersButton.setHeight( "-1px" );
showPeersButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
populateData();
peersTable.refreshRowCache();
}
} );
return showPeersButton;
}
private void populateData()
{
List<PeerInfo> peers = module.getPeerManager().peers();
peersTable.removeAllItems();
peersTable.addContainerProperty( "ID", UUID.class, null );
peersTable.addContainerProperty( "Name", String.class, null );
peersTable.addContainerProperty( "IP", String.class, null );
peersTable.addContainerProperty( "Status", PeerStatus.class, null );
peersTable.addContainerProperty( "ActionsAdvanced", PeerManageActionsComponent.class, null );
for ( final PeerInfo peer : peers )
{
if ( peer == null || peer.getStatus() == null )
{
continue;
}
/**
* According to peer status perform sufficient action
*/
PeerManageActionsComponent.PeerManagerActionsListener listener =
new PeerManageActionsComponent.PeerManagerActionsListener()
{
@Override
public void OnPositiveButtonTrigger( final PeerInfo peer )
{
switch ( peer.getStatus() )
{
case REQUESTED:
PeerInfo selfPeer;
selfPeer = module.getPeerManager().getLocalPeerInfo();
/**
* Send peer to register on remote peer. To construct secure connection. For now initializer peer doesn't send its
* px2 (public key requiring bidirectional authentication).
*
* @param peerToRegister - initializer peer info for registration process
* @param ip - target peer ip address
*
* @return - remote peer info to whom registration is requested
*/
private PeerInfo registerMeToRemote( PeerInfo peerToRegister, String ip )
{
String baseUrl = String.format( "https://%s:%s/cxf", ip, ChannelSettings.SECURE_PORT_X1 );
WebClient client = RestUtil.createTrustedWebClient( baseUrl );//WebClient.create( baseUrl );
client.type( MediaType.MULTIPART_FORM_DATA ).accept( MediaType.APPLICATION_JSON );
Form form = new Form();
form.set( "peer", GSON.toJson( peerToRegister ) );
Response response = client.path( "peer/register" ).form( form );
if ( response.getStatus() == Response.Status.OK.getStatusCode() )
{
Notification.show( String.format( "Request sent to %s!", ip ) );
String responseString = response.readEntity( String.class );
LOG.info( response.toString() );
PeerInfo remotePeerInfo = JsonUtil.from( responseString, new TypeToken<PeerInfo>()
{
}.getType() );
if ( remotePeerInfo != null )
{
remotePeerInfo.setStatus( PeerStatus.REQUEST_SENT );
return remotePeerInfo;
}
}
else
{
LOG.warn( "Response for registering peer: " + response.toString() );
}
return null;
}
private void unregisterMeFromRemote( PeerInfo peerToUnregister, PeerInfo remotePeerInfo )
{
//TODO remove peer certificate from trust store
String baseUrl = String.format( "https://%s:%s/cxf", remotePeerInfo.getIp(), ChannelSettings.SECURE_PORT_X2 );
WebClient client = RestUtil.createTrustedWebClientWithAuth( baseUrl );// WebClient.create( baseUrl );
Response response =
client.path( "peer/unregister" ).type( MediaType.APPLICATION_JSON ).accept( MediaType.APPLICATION_JSON )
.query( "peerId", GSON.toJson( peerToUnregister.getId().toString() ) ).delete();
if ( response.getStatus() == Response.Status.OK.getStatusCode() )
{
LOG.info( response.toString() );
Notification.show( String.format( "Request sent to %s!", remotePeerInfo.getName() ) );
/**
* Peer request rejection intented to be handled before they exchange with keys
*
* @param peerToUpdateOnRemote - local peer info to update/send to remote peer
* @param remotePeer - remote peer whose request was rejected
*
* @return - status mentioning does remote has responded with 202 status code.
*/
private boolean rejectPeerRegistration( PeerInfo peerToUpdateOnRemote, PeerInfo remotePeer )
{
String baseUrl = String.format( "https://%s:%s/cxf", remotePeer.getIp(), ChannelSettings.SECURE_PORT_X1 );
WebClient client = RestUtil.createTrustedWebClient( baseUrl );// WebClient.create( baseUrl );
client.type( MediaType.APPLICATION_FORM_URLENCODED ).accept( MediaType.APPLICATION_JSON );
Form form = new Form();
form.set( "rejectedPeerId", peerToUpdateOnRemote.getId().toString() );
Response response = client.path( "peer/reject" ).put( form );
if ( response.getStatus() == Response.Status.NO_CONTENT.getStatusCode() )
{
LOG.info( "Successfully reject peer request" );
Notification.show( String.format( "Request sent to %s!", remotePeer.getName() ) );
//TODO maybe will implement certificates exchange later on initial request, before peer approves
// initializer' request
/**
* Send peer registration request for further handshakes.
*
* @return - vaadin button with request initializing click listener
*/
private Button createRegisterButton()
{
registerRequestButton = new Button();
registerRequestButton.setCaption( "Register" );
registerRequestButton.setImmediate( true );
registerRequestButton.setWidth( "-1px" );
registerRequestButton.setHeight( "-1px" );
registerRequestButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
getUI().access( new Runnable()
{
@Override
public void run()
{
String ip = ipTextField.getValue();
LOG.warn( ip );
try
{
PeerInfo selfPeer = module.getPeerManager().getLocalPeerInfo();
PeerInfo remotePeer = registerMeToRemote( selfPeer, ip );
if ( remotePeer != null )
{
module.getPeerManager().register( remotePeer );
}
showPeersButton.click();
}
catch ( PeerException e )
{
Notification.show( e.getMessage(), Notification.Type.ERROR_MESSAGE );
}
}
} );
}
} );
return registerRequestButton;
}
}
|
package org.opendaylight.controller.sal.binding.api;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public abstract class AbstractBrokerAwareActivator implements BundleActivator {
private static final ExecutorService mdActivationPool = Executors.newCachedThreadPool();
private BundleContext context;
private ServiceTracker<BindingAwareBroker, BindingAwareBroker> tracker;
private BindingAwareBroker broker;
private ServiceTrackerCustomizer<BindingAwareBroker, BindingAwareBroker> customizer = new ServiceTrackerCustomizer<BindingAwareBroker, BindingAwareBroker>() {
@Override
public BindingAwareBroker addingService(ServiceReference<BindingAwareBroker> reference) {
broker = context.getService(reference);
mdActivationPool.execute(new Runnable() {
@Override
public void run() {
onBrokerAvailable(broker, context);
}
});
return broker;
}
@Override
public void modifiedService(ServiceReference<BindingAwareBroker> reference, BindingAwareBroker service) {
removedService(reference, service);
addingService(reference);
}
@Override
public void removedService(ServiceReference<BindingAwareBroker> reference, BindingAwareBroker service) {
broker = context.getService(reference);
mdActivationPool.execute(new Runnable() {
@Override
public void run() {
onBrokerRemoved(broker, context);
}
});
}
};
@Override
public final void start(BundleContext context) throws Exception {
this.context = context;
startImpl(context);
tracker = new ServiceTracker<>(context, BindingAwareBroker.class, customizer);
tracker.open();
}
@Override
public final void stop(BundleContext context) throws Exception {
tracker.close();
stopImpl(context);
}
/**
* Called when this bundle is started (before
* {@link #onSessionInitiated(ProviderContext)} so the Framework can perform
* the bundle-specific activities necessary to start this bundle. This
* method can be used to register services or to allocate any resources that
* this bundle needs.
*
* <p>
* This method must complete and return to its caller in a timely manner.
*
* @param context
* The execution context of the bundle being started.
* @throws Exception
* If this method throws an exception, this bundle is marked as
* stopped and the Framework will remove this bundle's
* listeners, unregister all services registered by this bundle,
* and release all services used by this bundle.
*/
protected void startImpl(BundleContext context) {
// NOOP
}
/**
* Called when this bundle is stopped so the Framework can perform the
* bundle-specific activities necessary to stop the bundle. In general, this
* method should undo the work that the {@code BundleActivator.start} method
* started. There should be no active threads that were started by this
* bundle when this bundle returns. A stopped bundle must not call any
* Framework objects.
*
* <p>
* This method must complete and return to its caller in a timely manner.
*
* @param context The execution context of the bundle being stopped.
* @throws Exception If this method throws an exception, the bundle is still
* marked as stopped, and the Framework will remove the bundle's
* listeners, unregister all services registered by the bundle, and
* release all services used by the bundle.
*/
protected void stopImpl(BundleContext context) {
// NOOP
}
protected abstract void onBrokerAvailable(BindingAwareBroker broker, BundleContext context);
protected void onBrokerRemoved(BindingAwareBroker broker, BundleContext context) {
stopImpl(context);
}
}
|
package org.openlmis.restapi.service;
import lombok.NoArgsConstructor;
import org.openlmis.core.domain.Facility;
import org.openlmis.core.domain.Program;
import org.openlmis.core.exception.DataException;
import org.openlmis.core.service.FacilityService;
import org.openlmis.core.service.MessageService;
import org.openlmis.core.service.ProgramService;
import org.openlmis.order.service.OrderService;
import org.openlmis.restapi.domain.ReplenishmentDTO;
import org.openlmis.restapi.domain.Report;
import org.openlmis.rnr.domain.Rnr;
import org.openlmis.rnr.domain.RnrLineItem;
import org.openlmis.rnr.search.criteria.RequisitionSearchCriteria;
import org.openlmis.rnr.service.RequisitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import static org.openlmis.restapi.domain.ReplenishmentDTO.prepareForREST;
@Service
@NoArgsConstructor
public class RestRequisitionService {
@Autowired
private RequisitionService requisitionService;
@Autowired
private OrderService orderService;
@Autowired
private FacilityService facilityService;
@Autowired
private ProgramService programService;
@Autowired
private MessageService messageService;
@Transactional
public Rnr submitReport(Report report, Long userId) {
report.validate();
Facility reportingFacility = facilityService.getOperativeFacilityByCode(report.getAgentCode());
Program reportingProgram = programService.getValidatedProgramByCode(report.getProgramCode());
validate(reportingFacility, reportingProgram);
Rnr rnr = requisitionService.initiate(reportingFacility, reportingProgram, userId, false);
validateProducts(report, rnr);
report.getRnrWithSkippedProducts(rnr);
return requisitionService.save(rnr);
}
private void validate(Facility reportingFacility, Program reportingProgram) {
if (reportingFacility.getVirtualFacility()) return;
RequisitionSearchCriteria searchCriteria = new RequisitionSearchCriteria();
searchCriteria.setProgramId(reportingProgram.getId());
searchCriteria.setFacilityId(reportingFacility.getId());
if (!requisitionService.getCurrentPeriod(searchCriteria).getId().equals(requisitionService.getPeriodForInitiating(reportingFacility, reportingProgram).getId())) {
throw new DataException("error.rnr.previous.not.filled");
}
}
@Transactional
public void approve(Report report, Long userId) {
Rnr requisition = report.getRequisition();
requisition.setModifiedBy(userId);
Rnr savedRequisition = requisitionService.getFullRequisitionById(requisition.getId());
if (!savedRequisition.getFacility().getVirtualFacility())
throw new DataException("error.approval.not.allowed");
if (savedRequisition.getFullSupplyLineItems().size() != report.getProducts().size()) {
throw new DataException("error.number.of.line.items.mismatch");
}
validateProducts(report, savedRequisition);
requisitionService.save(requisition);
requisitionService.approve(requisition);
}
private void validateProducts(Report report, Rnr savedRequisition) {
if (report.getProducts() == null) {
return;
}
List<String> invalidProductCodes = new ArrayList<>();
for (final RnrLineItem lineItem : report.getProducts()) {
if (savedRequisition.findCorrespondingLineItem(lineItem) == null) {
invalidProductCodes.add(lineItem.getProductCode());
}
}
if (invalidProductCodes.size() != 0) {
throw new DataException(messageService.message("invalid.product.codes", invalidProductCodes.toString()));
}
}
public ReplenishmentDTO getReplenishmentDetails(Long id) {
Rnr requisition = requisitionService.getFullRequisitionById(id);
ReplenishmentDTO replenishmentDTO = prepareForREST(requisition, orderService.getOrder(id));
return replenishmentDTO;
}
}
|
package org.opendaylight.controller.cluster.datastore;
import akka.util.Timeout;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.text.WordUtils;
import org.opendaylight.controller.cluster.common.actor.AkkaConfigurationReader;
import org.opendaylight.controller.cluster.common.actor.FileAkkaConfigurationReader;
import org.opendaylight.controller.cluster.raft.ConfigParams;
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import org.opendaylight.controller.cluster.raft.PeerAddressResolver;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreConfigProperties;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
/**
* Contains contextual data for a data store.
*
* @author Thomas Pantelis
*/
public class DatastoreContext {
public static final String METRICS_DOMAIN = "org.opendaylight.controller.cluster.datastore";
public static final Duration DEFAULT_SHARD_TRANSACTION_IDLE_TIMEOUT = Duration.create(10, TimeUnit.MINUTES);
public static final int DEFAULT_OPERATION_TIMEOUT_IN_MS = 5000;
public static final int DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS = 30;
public static final int DEFAULT_JOURNAL_RECOVERY_BATCH_SIZE = 1;
public static final int DEFAULT_SNAPSHOT_BATCH_COUNT = 20000;
public static final int DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS = 500;
public static final int DEFAULT_ISOLATED_LEADER_CHECK_INTERVAL_IN_MILLIS = DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS * 10;
public static final int DEFAULT_SHARD_TX_COMMIT_QUEUE_CAPACITY = 50000;
public static final Timeout DEFAULT_SHARD_INITIALIZATION_TIMEOUT = new Timeout(5, TimeUnit.MINUTES);
public static final Timeout DEFAULT_SHARD_LEADER_ELECTION_TIMEOUT = new Timeout(30, TimeUnit.SECONDS);
public static final boolean DEFAULT_PERSISTENT = true;
public static final FileAkkaConfigurationReader DEFAULT_CONFIGURATION_READER = new FileAkkaConfigurationReader();
public static final int DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE = 12;
public static final int DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR = 2;
public static final int DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT = 100;
public static final String UNKNOWN_DATA_STORE_TYPE = "unknown";
public static final int DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT = 1000;
public static final long DEFAULT_SHARD_COMMIT_QUEUE_EXPIRY_TIMEOUT_IN_MS = TimeUnit.MILLISECONDS.convert(2, TimeUnit.MINUTES);
public static final int DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE = 2048000;
private static final Set<String> globalDatastoreNames = Sets.newConcurrentHashSet();
private InMemoryDOMDataStoreConfigProperties dataStoreProperties;
private Duration shardTransactionIdleTimeout = DatastoreContext.DEFAULT_SHARD_TRANSACTION_IDLE_TIMEOUT;
private long operationTimeoutInMillis = DEFAULT_OPERATION_TIMEOUT_IN_MS;
private String dataStoreMXBeanType;
private int shardTransactionCommitTimeoutInSeconds = DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS;
private int shardTransactionCommitQueueCapacity = DEFAULT_SHARD_TX_COMMIT_QUEUE_CAPACITY;
private Timeout shardInitializationTimeout = DEFAULT_SHARD_INITIALIZATION_TIMEOUT;
private Timeout shardLeaderElectionTimeout = DEFAULT_SHARD_LEADER_ELECTION_TIMEOUT;
private boolean persistent = DEFAULT_PERSISTENT;
private AkkaConfigurationReader configurationReader = DEFAULT_CONFIGURATION_READER;
private long transactionCreationInitialRateLimit = DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT;
private final DefaultConfigParamsImpl raftConfig = new DefaultConfigParamsImpl();
private String dataStoreName = UNKNOWN_DATA_STORE_TYPE;
private LogicalDatastoreType logicalStoreType = LogicalDatastoreType.OPERATIONAL;
private int shardBatchedModificationCount = DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT;
private boolean writeOnlyTransactionOptimizationsEnabled = true;
private long shardCommitQueueExpiryTimeoutInMillis = DEFAULT_SHARD_COMMIT_QUEUE_EXPIRY_TIMEOUT_IN_MS;
private boolean transactionDebugContextEnabled = false;
private String shardManagerPersistenceId;
public static Set<String> getGlobalDatastoreNames() {
return globalDatastoreNames;
}
private DatastoreContext() {
setShardJournalRecoveryLogBatchSize(DEFAULT_JOURNAL_RECOVERY_BATCH_SIZE);
setSnapshotBatchCount(DEFAULT_SNAPSHOT_BATCH_COUNT);
setHeartbeatInterval(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS);
setIsolatedLeaderCheckInterval(DEFAULT_ISOLATED_LEADER_CHECK_INTERVAL_IN_MILLIS);
setSnapshotDataThresholdPercentage(DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE);
setElectionTimeoutFactor(DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR);
setShardSnapshotChunkSize(DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE);
}
private DatastoreContext(DatastoreContext other) {
this.dataStoreProperties = other.dataStoreProperties;
this.shardTransactionIdleTimeout = other.shardTransactionIdleTimeout;
this.operationTimeoutInMillis = other.operationTimeoutInMillis;
this.dataStoreMXBeanType = other.dataStoreMXBeanType;
this.shardTransactionCommitTimeoutInSeconds = other.shardTransactionCommitTimeoutInSeconds;
this.shardTransactionCommitQueueCapacity = other.shardTransactionCommitQueueCapacity;
this.shardInitializationTimeout = other.shardInitializationTimeout;
this.shardLeaderElectionTimeout = other.shardLeaderElectionTimeout;
this.persistent = other.persistent;
this.configurationReader = other.configurationReader;
this.transactionCreationInitialRateLimit = other.transactionCreationInitialRateLimit;
this.dataStoreName = other.dataStoreName;
this.logicalStoreType = other.logicalStoreType;
this.shardBatchedModificationCount = other.shardBatchedModificationCount;
this.writeOnlyTransactionOptimizationsEnabled = other.writeOnlyTransactionOptimizationsEnabled;
this.shardCommitQueueExpiryTimeoutInMillis = other.shardCommitQueueExpiryTimeoutInMillis;
this.transactionDebugContextEnabled = other.transactionDebugContextEnabled;
this.shardManagerPersistenceId = other.shardManagerPersistenceId;
setShardJournalRecoveryLogBatchSize(other.raftConfig.getJournalRecoveryLogBatchSize());
setSnapshotBatchCount(other.raftConfig.getSnapshotBatchCount());
setHeartbeatInterval(other.raftConfig.getHeartBeatInterval().toMillis());
setIsolatedLeaderCheckInterval(other.raftConfig.getIsolatedCheckIntervalInMillis());
setSnapshotDataThresholdPercentage(other.raftConfig.getSnapshotDataThresholdPercentage());
setElectionTimeoutFactor(other.raftConfig.getElectionTimeoutFactor());
setCustomRaftPolicyImplementation(other.raftConfig.getCustomRaftPolicyImplementationClass());
setShardSnapshotChunkSize(other.raftConfig.getSnapshotChunkSize());
setPeerAddressResolver(other.raftConfig.getPeerAddressResolver());
}
public static Builder newBuilder() {
return new Builder(new DatastoreContext());
}
public static Builder newBuilderFrom(DatastoreContext context) {
return new Builder(new DatastoreContext(context));
}
public InMemoryDOMDataStoreConfigProperties getDataStoreProperties() {
return dataStoreProperties;
}
public Duration getShardTransactionIdleTimeout() {
return shardTransactionIdleTimeout;
}
public String getDataStoreMXBeanType() {
return dataStoreMXBeanType;
}
public long getOperationTimeoutInMillis() {
return operationTimeoutInMillis;
}
public ConfigParams getShardRaftConfig() {
return raftConfig;
}
public int getShardTransactionCommitTimeoutInSeconds() {
return shardTransactionCommitTimeoutInSeconds;
}
public int getShardTransactionCommitQueueCapacity() {
return shardTransactionCommitQueueCapacity;
}
public Timeout getShardInitializationTimeout() {
return shardInitializationTimeout;
}
public Timeout getShardLeaderElectionTimeout() {
return shardLeaderElectionTimeout;
}
public boolean isPersistent() {
return persistent;
}
public AkkaConfigurationReader getConfigurationReader() {
return configurationReader;
}
public long getShardElectionTimeoutFactor(){
return raftConfig.getElectionTimeoutFactor();
}
public String getDataStoreName(){
return dataStoreName;
}
public LogicalDatastoreType getLogicalStoreType() {
return logicalStoreType;
}
public long getTransactionCreationInitialRateLimit() {
return transactionCreationInitialRateLimit;
}
public String getShardManagerPersistenceId() {
return shardManagerPersistenceId;
}
private void setPeerAddressResolver(PeerAddressResolver resolver) {
raftConfig.setPeerAddressResolver(resolver);
}
private void setHeartbeatInterval(long shardHeartbeatIntervalInMillis){
raftConfig.setHeartBeatInterval(new FiniteDuration(shardHeartbeatIntervalInMillis,
TimeUnit.MILLISECONDS));
}
private void setShardJournalRecoveryLogBatchSize(int shardJournalRecoveryLogBatchSize){
raftConfig.setJournalRecoveryLogBatchSize(shardJournalRecoveryLogBatchSize);
}
private void setIsolatedLeaderCheckInterval(long shardIsolatedLeaderCheckIntervalInMillis) {
raftConfig.setIsolatedLeaderCheckInterval(
new FiniteDuration(shardIsolatedLeaderCheckIntervalInMillis, TimeUnit.MILLISECONDS));
}
private void setElectionTimeoutFactor(long shardElectionTimeoutFactor) {
raftConfig.setElectionTimeoutFactor(shardElectionTimeoutFactor);
}
private void setCustomRaftPolicyImplementation(String customRaftPolicyImplementation) {
raftConfig.setCustomRaftPolicyImplementationClass(customRaftPolicyImplementation);
}
private void setSnapshotDataThresholdPercentage(int shardSnapshotDataThresholdPercentage) {
Preconditions.checkArgument(shardSnapshotDataThresholdPercentage >= 0
&& shardSnapshotDataThresholdPercentage <= 100);
raftConfig.setSnapshotDataThresholdPercentage(shardSnapshotDataThresholdPercentage);
}
private void setSnapshotBatchCount(long shardSnapshotBatchCount) {
raftConfig.setSnapshotBatchCount(shardSnapshotBatchCount);
}
private void setShardSnapshotChunkSize(int shardSnapshotChunkSize) {
raftConfig.setSnapshotChunkSize(shardSnapshotChunkSize);
}
public int getShardBatchedModificationCount() {
return shardBatchedModificationCount;
}
public boolean isWriteOnlyTransactionOptimizationsEnabled() {
return writeOnlyTransactionOptimizationsEnabled;
}
public long getShardCommitQueueExpiryTimeoutInMillis() {
return shardCommitQueueExpiryTimeoutInMillis;
}
public boolean isTransactionDebugContextEnabled() {
return transactionDebugContextEnabled;
}
public int getShardSnapshotChunkSize() {
return raftConfig.getSnapshotChunkSize();
}
public static class Builder {
private final DatastoreContext datastoreContext;
private int maxShardDataChangeExecutorPoolSize =
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_EXECUTOR_POOL_SIZE;
private int maxShardDataChangeExecutorQueueSize =
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_EXECUTOR_QUEUE_SIZE;
private int maxShardDataChangeListenerQueueSize =
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE;
private int maxShardDataStoreExecutorQueueSize =
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_STORE_EXECUTOR_QUEUE_SIZE;
private Builder(DatastoreContext datastoreContext) {
this.datastoreContext = datastoreContext;
if(datastoreContext.getDataStoreProperties() != null) {
maxShardDataChangeExecutorPoolSize =
datastoreContext.getDataStoreProperties().getMaxDataChangeExecutorPoolSize();
maxShardDataChangeExecutorQueueSize =
datastoreContext.getDataStoreProperties().getMaxDataChangeExecutorQueueSize();
maxShardDataChangeListenerQueueSize =
datastoreContext.getDataStoreProperties().getMaxDataChangeListenerQueueSize();
maxShardDataStoreExecutorQueueSize =
datastoreContext.getDataStoreProperties().getMaxDataStoreExecutorQueueSize();
}
}
public Builder boundedMailboxCapacity(int boundedMailboxCapacity) {
// TODO - this is defined in the yang DataStoreProperties but not currently used.
return this;
}
public Builder enableMetricCapture(boolean enableMetricCapture) {
// TODO - this is defined in the yang DataStoreProperties but not currently used.
return this;
}
public Builder shardTransactionIdleTimeout(long timeout, TimeUnit unit) {
datastoreContext.shardTransactionIdleTimeout = Duration.create(timeout, unit);
return this;
}
public Builder shardTransactionIdleTimeoutInMinutes(long timeout) {
return shardTransactionIdleTimeout(timeout, TimeUnit.MINUTES);
}
public Builder operationTimeoutInSeconds(int operationTimeoutInSeconds) {
datastoreContext.operationTimeoutInMillis = TimeUnit.SECONDS.toMillis(operationTimeoutInSeconds);
return this;
}
public Builder operationTimeoutInMillis(long operationTimeoutInMillis) {
datastoreContext.operationTimeoutInMillis = operationTimeoutInMillis;
return this;
}
public Builder dataStoreMXBeanType(String dataStoreMXBeanType) {
datastoreContext.dataStoreMXBeanType = dataStoreMXBeanType;
return this;
}
public Builder shardTransactionCommitTimeoutInSeconds(int shardTransactionCommitTimeoutInSeconds) {
datastoreContext.shardTransactionCommitTimeoutInSeconds = shardTransactionCommitTimeoutInSeconds;
return this;
}
public Builder shardJournalRecoveryLogBatchSize(int shardJournalRecoveryLogBatchSize) {
datastoreContext.setShardJournalRecoveryLogBatchSize(shardJournalRecoveryLogBatchSize);
return this;
}
public Builder shardSnapshotBatchCount(int shardSnapshotBatchCount) {
datastoreContext.setSnapshotBatchCount(shardSnapshotBatchCount);
return this;
}
public Builder shardSnapshotDataThresholdPercentage(int shardSnapshotDataThresholdPercentage) {
datastoreContext.setSnapshotDataThresholdPercentage(shardSnapshotDataThresholdPercentage);
return this;
}
public Builder shardHeartbeatIntervalInMillis(int shardHeartbeatIntervalInMillis) {
datastoreContext.setHeartbeatInterval(shardHeartbeatIntervalInMillis);
return this;
}
public Builder shardTransactionCommitQueueCapacity(int shardTransactionCommitQueueCapacity) {
datastoreContext.shardTransactionCommitQueueCapacity = shardTransactionCommitQueueCapacity;
return this;
}
public Builder shardInitializationTimeout(long timeout, TimeUnit unit) {
datastoreContext.shardInitializationTimeout = new Timeout(timeout, unit);
return this;
}
public Builder shardInitializationTimeoutInSeconds(long timeout) {
return shardInitializationTimeout(timeout, TimeUnit.SECONDS);
}
public Builder shardLeaderElectionTimeout(long timeout, TimeUnit unit) {
datastoreContext.shardLeaderElectionTimeout = new Timeout(timeout, unit);
return this;
}
public Builder shardLeaderElectionTimeoutInSeconds(long timeout) {
return shardLeaderElectionTimeout(timeout, TimeUnit.SECONDS);
}
public Builder configurationReader(AkkaConfigurationReader configurationReader){
datastoreContext.configurationReader = configurationReader;
return this;
}
public Builder persistent(boolean persistent){
datastoreContext.persistent = persistent;
return this;
}
public Builder shardIsolatedLeaderCheckIntervalInMillis(int shardIsolatedLeaderCheckIntervalInMillis) {
datastoreContext.setIsolatedLeaderCheckInterval(shardIsolatedLeaderCheckIntervalInMillis);
return this;
}
public Builder shardElectionTimeoutFactor(long shardElectionTimeoutFactor){
datastoreContext.setElectionTimeoutFactor(shardElectionTimeoutFactor);
return this;
}
public Builder transactionCreationInitialRateLimit(long initialRateLimit){
datastoreContext.transactionCreationInitialRateLimit = initialRateLimit;
return this;
}
public Builder logicalStoreType(LogicalDatastoreType logicalStoreType){
datastoreContext.logicalStoreType = Preconditions.checkNotNull(logicalStoreType);
// Retain compatible naming
switch (logicalStoreType) {
case CONFIGURATION:
dataStoreName("config");
break;
case OPERATIONAL:
dataStoreName("operational");
break;
default:
dataStoreName(logicalStoreType.name());
}
return this;
}
public Builder dataStoreName(String dataStoreName){
datastoreContext.dataStoreName = Preconditions.checkNotNull(dataStoreName);
datastoreContext.dataStoreMXBeanType = "Distributed" + WordUtils.capitalize(dataStoreName) + "Datastore";
return this;
}
public Builder shardBatchedModificationCount(int shardBatchedModificationCount) {
datastoreContext.shardBatchedModificationCount = shardBatchedModificationCount;
return this;
}
public Builder writeOnlyTransactionOptimizationsEnabled(boolean value) {
datastoreContext.writeOnlyTransactionOptimizationsEnabled = value;
return this;
}
public Builder shardCommitQueueExpiryTimeoutInMillis(long value) {
datastoreContext.shardCommitQueueExpiryTimeoutInMillis = value;
return this;
}
public Builder shardCommitQueueExpiryTimeoutInSeconds(long value) {
datastoreContext.shardCommitQueueExpiryTimeoutInMillis = TimeUnit.MILLISECONDS.convert(
value, TimeUnit.SECONDS);
return this;
}
public Builder transactionDebugContextEnabled(boolean value) {
datastoreContext.transactionDebugContextEnabled = value;
return this;
}
public Builder maxShardDataChangeExecutorPoolSize(int maxShardDataChangeExecutorPoolSize) {
this.maxShardDataChangeExecutorPoolSize = maxShardDataChangeExecutorPoolSize;
return this;
}
public Builder maxShardDataChangeExecutorQueueSize(int maxShardDataChangeExecutorQueueSize) {
this.maxShardDataChangeExecutorQueueSize = maxShardDataChangeExecutorQueueSize;
return this;
}
public Builder maxShardDataChangeListenerQueueSize(int maxShardDataChangeListenerQueueSize) {
this.maxShardDataChangeListenerQueueSize = maxShardDataChangeListenerQueueSize;
return this;
}
public Builder maxShardDataStoreExecutorQueueSize(int maxShardDataStoreExecutorQueueSize) {
this.maxShardDataStoreExecutorQueueSize = maxShardDataStoreExecutorQueueSize;
return this;
}
/**
* For unit tests only.
*/
@VisibleForTesting
public Builder shardManagerPersistenceId(String id) {
datastoreContext.shardManagerPersistenceId = id;
return this;
}
public DatastoreContext build() {
datastoreContext.dataStoreProperties = InMemoryDOMDataStoreConfigProperties.create(
maxShardDataChangeExecutorPoolSize, maxShardDataChangeExecutorQueueSize,
maxShardDataChangeListenerQueueSize, maxShardDataStoreExecutorQueueSize);
if(datastoreContext.dataStoreName != null) {
globalDatastoreNames.add(datastoreContext.dataStoreName);
}
return datastoreContext;
}
public Builder customRaftPolicyImplementation(String customRaftPolicyImplementation) {
datastoreContext.setCustomRaftPolicyImplementation(customRaftPolicyImplementation);
return this;
}
public Builder shardSnapshotChunkSize(int shardSnapshotChunkSize) {
datastoreContext.setShardSnapshotChunkSize(shardSnapshotChunkSize);
return this;
}
public Builder shardPeerAddressResolver(PeerAddressResolver resolver) {
datastoreContext.setPeerAddressResolver(resolver);
return this;
}
}
}
|
package org.springsource.ide.eclipse.commons.quicksearch.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.LegacyActionTools;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILazyContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.StyledString.Styler;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.search.internal.ui.text.EditorOpener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.ActiveShellExpression;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.SelectionStatusDialog;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.internal.IWorkbenchGraphicConstants;
import org.eclipse.ui.internal.WorkbenchImages;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.progress.UIJob;
import org.springsource.ide.eclipse.commons.quicksearch.core.LineItem;
import org.springsource.ide.eclipse.commons.quicksearch.core.QuickTextQuery;
import org.springsource.ide.eclipse.commons.quicksearch.core.QuickTextQuery.TextRange;
import org.springsource.ide.eclipse.commons.quicksearch.core.QuickTextSearchRequestor;
import org.springsource.ide.eclipse.commons.quicksearch.core.QuickTextSearcher;
import org.springsource.ide.eclipse.commons.quicksearch.core.pathmatch.ResourceMatchers;
import org.springsource.ide.eclipse.commons.quicksearch.util.DocumentFetcher;
import org.springsource.ide.eclipse.commons.quicksearch.util.TableResizeHelper;
/**
* Shows a list of items to the user with a text entry field for a string
* pattern used to filter the list of items.
*
* @since 3.3
*/
@SuppressWarnings({ "rawtypes", "restriction", "unchecked" })
public class QuickSearchDialog extends SelectionStatusDialog {
private static final int GO_BUTTON_ID = IDialogConstants.CLIENT_ID + 1;
private static final int REFRESH_BUTTON_ID = IDialogConstants.CLIENT_ID + 2;
public static final Styler HIGHLIGHT_STYLE = org.eclipse.search.internal.ui.text.DecoratingFileSearchLabelProvider.HIGHLIGHT_STYLE;
// public class ScrollListener implements SelectionListener {
// ScrollBar scrollbar;
// public ScrollListener(ScrollBar scrollbar) {
// this.scrollbar = scrollbar;
// scrollbar.addSelectionListener(this);
// @Override
// public void widgetDefaultSelected(SelectionEvent e) {
// processEvent(e);
// private int oldPercent = 0;
// private void processEvent(SelectionEvent e) {
// int min = scrollbar.getMinimum();
// int max = scrollbar.getMaximum();
// int val = scrollbar.getSelection();
// int thumb = scrollbar.getThumb();
// int total = max - min; //Total range of the scrollbar
// int end = val+thumb; //The bottom of visible region
// int belowEnd = max - end; //Size of area that is below the current visible area.
// int percent = (belowEnd*100)/total; // size in percentage of total area that is below visible area.
// System.out.println("min: "+min +" max: "+max);
// System.out.println("val: "+val +" thum: "+thumb);
// System.out.println("percent: "+percent);
// if (percent <= 10) {
// walker.requestMoreResults();
// if (Math.abs(percent-oldPercent)>50) {
// System.out.println("Big jump!");
// oldPercent = percent;
// @Override
// public void widgetSelected(SelectionEvent e) {
// processEvent(e);
private UIJob refreshJob = new UIJob("Refresh") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
refreshWidgets();
return Status.OK_STATUS;
}
};
protected void openSelection() {
try {
LineItem item = (LineItem) this.getFirstResult();
if (item!=null) {
QuickTextQuery q = this.getQuery();
TextRange range = q.findFirst(item.getText());
EditorOpener opener = new EditorOpener();
IWorkbenchPage page = window.getActivePage();
if (page!=null) {
opener.openAndSelect(page, item.getFile(), range.getOffset()+item.getOffset(),
range.getLength(), true);
}
}
} catch (PartInitException e) {
QuickSearchActivator.log(e);
}
}
/**
* Job that shows a simple busy indicator while a search is active.
* The job must be scheduled when a search starts/resumes.
*/
private UIJob progressJob = new UIJob("Refresh") {
int animate = 0; // number of dots to display.
protected String dots(int animate) {
char[] chars = new char[animate];
for (int i = 0; i < chars.length; i++) {
chars[i] = '.';
}
return new String(chars);
}
protected String currentFileInfo(IFile currentFile, int animate) {
if (currentFile!=null) {
String path = currentFile.getFullPath().toString();
if (path.length()<=30) {
return path;
}
return "..."+path.substring(path.length()-30);
}
return dots(animate);
}
@Override
public IStatus runInUIThread(IProgressMonitor mon) {
if (!mon.isCanceled() && progressLabel!=null && !progressLabel.isDisposed()) {
if (searcher==null || searcher.isDone()) {
progressLabel.setText("");
} else {
progressLabel.setText("Searching"+currentFileInfo(searcher.getCurrentFile(), animate));
animate = (animate+1)%4;
this.schedule(333);
}
}
return Status.OK_STATUS;
}
};
public final StyledCellLabelProvider LINE_NUMBER_LABEL_PROVIDER = new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
LineItem item = (LineItem) cell.getElement();
if (item!=null) {
cell.setText(""+item.getLineNumber());
} else {
cell.setText("?");
}
cell.setImage(getBlankImage());
};
};
private static final Color GREY = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY);
private final StyledCellLabelProvider LINE_TEXT_LABEL_PROVIDER = new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
LineItem item = (LineItem) cell.getElement();
if (item!=null) {
StyledString text = highlightMatches(item.getText());
cell.setText(text.getString());
cell.setStyleRanges(text.getStyleRanges());
} else {
cell.setText("");
cell.setStyleRanges(null);
}
cell.setImage(getBlankImage());
super.update(cell);
}
};
private Image blankImage;
private Image getBlankImage() {
if (blankImage==null) {
blankImage = new Image(Display.getDefault(), 1, 1);
// GC gc = new GC(blankImage);
// gc.fillRectangle(0, 0, 16, 16);
// gc.dispose();
}
return blankImage;
}
private final StyledCellLabelProvider LINE_FILE_LABEL_PROVIDER = new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
LineItem item = (LineItem) cell.getElement();
if (item!=null) {
IPath path = item.getFile().getFullPath();
String name = path.lastSegment();
String dir = path.removeLastSegments(1).toString();
cell.setText(name + " - "+dir);
StyleRange[] styleRanges = new StyleRange[] {
new StyleRange(name.length(), dir.length()+3, GREY, null)
};
cell.setStyleRanges(styleRanges);
} else {
cell.setText("");
cell.setStyleRanges(null);
}
cell.setImage(getBlankImage());
super.update(cell);
}
// public String getToolTipText(Object element) {
// LineItem item = (LineItem) element;
// if (item!=null) {
// return ""+item.getFile().getFullPath();
// return "";
// public String getText(Object _item) {
// if (_item!=null) {
// LineItem item = (LineItem) _item;
// return item.getFile().getName().toString();
// return "?";
};
private static final String DIALOG_SETTINGS = QuickSearchDialog.class.getName()+".DIALOG_SETTINGS";
private static final String DIALOG_BOUNDS_SETTINGS = "DialogBoundsSettings"; //$NON-NLS-1$
private static final String DIALOG_HEIGHT = "DIALOG_HEIGHT"; //$NON-NLS-1$
private static final String DIALOG_WIDTH = "DIALOG_WIDTH"; //$NON-NLS-1$
private static final String DIALOG_COLUMNS = "COLUMN_WIDTHS";
private static final String DIALOG_SASH_WEIGHTS = "SASH_WEIGHTS";
private static final String DIALOG_LAST_QUERY = "LAST_QUERY";
private static final String DIALOG_PATH_FILTER = "PATH_FILTER";
private static final String CASE_SENSITIVE = "CASE_SENSITIVE";
private static final boolean CASE_SENSITIVE_DEFAULT = true;
private static final String KEEP_OPEN = "KEEP_OPEN";
private static final boolean KEEP_OPEN_DEFAULT = false;
/**
* Represents an empty selection in the pattern input field (used only for
* initial pattern).
*/
public static final int NONE = 0;
/**
* Pattern input field selection where caret is at the beginning (used only
* for initial pattern).
*/
public static final int CARET_BEGINNING = 1;
/**
* Represents a full selection in the pattern input field (used only for
* initial pattern).
*/
public static final int FULL_SELECTION = 2;
private Text pattern;
private TableViewer list;
private MenuManager menuManager;
private MenuManager contextMenuManager;
private boolean multi;
private ToolBar toolBar;
private ToolItem toolItem;
private Label progressLabel;
private ContentProvider contentProvider;
private String initialPatternText;
private int selectionMode;
private static final String EMPTY_STRING = ""; //$NON-NLS-1$
private final int MAX_LINE_LEN;
private IHandlerActivation showViewHandler;
private QuickTextSearcher searcher;
private StyledText details;
private DocumentFetcher documents;
private ToggleCaseSensitiveAction toggleCaseSensitiveAction;
private ToggleKeepOpenAction toggleKeepOpenAction;
private QuickSearchContext context;
private SashForm sashForm;
private Label headerLabel;
private IWorkbenchWindow window;
private Text searchIn;
/**
* Creates a new instance of the class.
*
* @param window.getShell()
* shell to parent the dialog on
* @param multi
* indicates whether dialog allows to select more than one
* position in its list of items
*/
public QuickSearchDialog(IWorkbenchWindow window) {
super(window.getShell());
this.window = window;
setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE | SWT.RESIZE);
setBlockOnOpen(false);
this.setTitle("Quick Text Search");
this.context = new QuickSearchContext(window);
this.multi = false;
contentProvider = new ContentProvider();
selectionMode = NONE;
MAX_LINE_LEN = QuickSearchActivator.getDefault().getPreferences().getMaxLineLen();
}
// /**
// * Returns the label decorator for selected items in the list.
// *
// * @return the label decorator for selected items in the list
// */
// private ILabelDecorator getListSelectionLabelDecorator() {
// return getItemsListLabelProvider().getSelectionDecorator();
// /**
// * Sets the label decorator for selected items in the list.
// *
// * @param listSelectionLabelDecorator
// * the label decorator for selected items in the list
// */
// public void setListSelectionLabelDecorator(
// ILabelDecorator listSelectionLabelDecorator) {
// getItemsListLabelProvider().setSelectionDecorator(
// listSelectionLabelDecorator);
// /**
// * Returns the item list label provider.
// *
// * @return the item list label provider
// */
// private ItemsListLabelProvider getItemsListLabelProvider() {
// if (itemsListLabelProvider == null) {
// itemsListLabelProvider = new ItemsListLabelProvider(
// new LabelProvider(), null);
// return itemsListLabelProvider;
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#create()
*/
public void create() {
super.create();
pattern.setFocus();
}
/**
* Restores dialog using persisted settings.
*/
protected void restoreDialog(IDialogSettings settings) {
try {
if (initialPatternText==null) {
String lastSearch = settings.get(DIALOG_LAST_QUERY);
if (lastSearch==null) {
lastSearch = "";
}
pattern.setText(lastSearch);
pattern.setSelection(0, lastSearch.length());
}
if (settings.get(DIALOG_PATH_FILTER)!=null) {
String filter = settings.get(DIALOG_PATH_FILTER);
searchIn.setText(filter);
}
if (settings.getArray(DIALOG_COLUMNS)!=null) {
String[] columnWidths = settings.getArray(DIALOG_COLUMNS);
Table table = list.getTable();
int cols = table.getColumnCount();
for (int i = 0; i < cols; i++) {
TableColumn col = table.getColumn(i);
try {
if (col!=null) {
col.setWidth(Integer.valueOf(columnWidths[i]));
}
} catch (Throwable e) {
QuickSearchActivator.log(e);
}
}
}
if (settings.getArray(DIALOG_SASH_WEIGHTS)!=null) {
String[] _weights = settings.getArray(DIALOG_SASH_WEIGHTS);
int[] weights = new int[_weights.length];
for (int i = 0; i < weights.length; i++) {
weights[i] = Integer.valueOf(_weights[i]);
}
sashForm.setWeights(weights);
}
} catch (Throwable e) {
//None of this stuff is critical so shouldn't stop opening dialog if it fails!
QuickSearchActivator.log(e);
}
}
private class ToggleKeepOpenAction extends Action {
public ToggleKeepOpenAction(IDialogSettings settings) {
super(
"Keep Open",
IAction.AS_CHECK_BOX
);
if (settings.get(KEEP_OPEN)==null) {
setChecked(KEEP_OPEN_DEFAULT);
} else{
setChecked(settings.getBoolean(KEEP_OPEN));
}
}
public void run() {
//setChecked(!isChecked());
}
}
private class ToggleCaseSensitiveAction extends Action {
public ToggleCaseSensitiveAction(IDialogSettings settings) {
super(
"Case Sensitive",
IAction.AS_CHECK_BOX
);
if (settings.get(CASE_SENSITIVE)==null) {
setChecked(CASE_SENSITIVE_DEFAULT);
} else{
setChecked(settings.getBoolean(CASE_SENSITIVE));
}
}
public void run() {
//setChecked(!isChecked());
refreshHeaderLabel();
applyFilter(false);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#close()
*/
public boolean close() {
this.progressJob.cancel();
this.progressJob = null;
// this.refreshProgressMessageJob.cancel();
if (showViewHandler != null) {
IHandlerService service = (IHandlerService) PlatformUI
.getWorkbench().getService(IHandlerService.class);
service.deactivateHandler(showViewHandler);
showViewHandler.getHandler().dispose();
showViewHandler = null;
}
if (menuManager != null)
menuManager.dispose();
if (contextMenuManager != null)
contextMenuManager.dispose();
storeDialog(getDialogSettings());
if (searcher!=null) {
searcher.cancel();
}
return super.close();
}
/**
* Stores dialog settings.
*
* @param settings
* settings used to store dialog
*/
protected void storeDialog(IDialogSettings settings) {
String currentSearch = pattern.getText();
settings.put(DIALOG_LAST_QUERY, currentSearch);
settings.put(DIALOG_PATH_FILTER, searchIn.getText());
if (toggleCaseSensitiveAction!=null) {
settings.put(CASE_SENSITIVE, toggleCaseSensitiveAction.isChecked());
}
if (toggleKeepOpenAction!=null) {
settings.put(KEEP_OPEN, toggleKeepOpenAction.isChecked());
}
Table table = list.getTable();
if (table.getColumnCount()>0) {
String[] columnWidths = new String[table.getColumnCount()];
for (int i = 0; i < columnWidths.length; i++) {
columnWidths[i] = ""+table.getColumn(i).getWidth();
}
settings.put(DIALOG_COLUMNS, columnWidths);
}
if (sashForm.getWeights()!=null) {
int[] w = sashForm.getWeights();
String[] ws = new String[w.length];
for (int i = 0; i < ws.length; i++) {
ws[i] = ""+w[i];
}
settings.put(DIALOG_SASH_WEIGHTS, ws);
}
}
/**
* Create a new header which is labelled by headerLabel.
*
* @param parent
* @return Label the label of the header
*/
private Label createHeader(Composite parent) {
Composite header = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
header.setLayout(layout);
headerLabel = new Label(header, SWT.NONE);
headerLabel.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_MNEMONIC && e.doit) {
e.detail = SWT.TRAVERSE_NONE;
pattern.setFocus();
}
}
});
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
headerLabel.setLayoutData(gd);
createViewMenu(header);
header.setLayoutData(gd);
refreshHeaderLabel();
return headerLabel;
}
private void refreshHeaderLabel() {
String msg = toggleCaseSensitiveAction.isChecked() ? "Case SENSITIVE" : "Case INSENSITIVE";
msg += " Pattern (? = any character, * = any string)";
headerLabel.setText(msg);
}
/**
* Create the labels for the list and the progress. Return the list label.
*
* @param parent
* @return Label
*/
private Label createLabels(Composite parent) {
Composite labels = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = 0;
layout.marginHeight = 0;
labels.setLayout(layout);
Label listLabel = new Label(labels, SWT.NONE);
listLabel
.setText(WorkbenchMessages.FilteredItemsSelectionDialog_listLabel);
listLabel.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_MNEMONIC && e.doit) {
e.detail = SWT.TRAVERSE_NONE;
list.getTable().setFocus();
}
}
});
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
listLabel.setLayoutData(gd);
progressLabel = new Label(labels, SWT.RIGHT);
progressLabel.setLayoutData(gd);
labels.setLayoutData(gd);
return listLabel;
}
private void createViewMenu(Composite parent) {
toolBar = new ToolBar(parent, SWT.FLAT);
toolItem = new ToolItem(toolBar, SWT.PUSH, 0);
GridData data = new GridData();
data.horizontalAlignment = GridData.END;
toolBar.setLayoutData(data);
toolBar.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
showViewMenu();
}
});
toolItem.setImage(WorkbenchImages
.getImage(IWorkbenchGraphicConstants.IMG_LCL_VIEW_MENU));
toolItem
.setToolTipText(WorkbenchMessages.FilteredItemsSelectionDialog_menu);
toolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showViewMenu();
}
});
menuManager = new MenuManager();
fillViewMenu(menuManager);
IHandlerService service = (IHandlerService) PlatformUI.getWorkbench()
.getService(IHandlerService.class);
IHandler handler = new AbstractHandler() {
public Object execute(ExecutionEvent event) {
showViewMenu();
return null;
}
};
showViewHandler = service.activateHandler(
IWorkbenchCommandConstants.WINDOW_SHOW_VIEW_MENU, handler,
new ActiveShellExpression(getShell()));
}
/**
* Fills the menu of the dialog.
*
* @param menuManager
* the menu manager
*/
protected void fillViewMenu(IMenuManager menuManager) {
IDialogSettings settings = getDialogSettings();
toggleCaseSensitiveAction = new ToggleCaseSensitiveAction(settings);
menuManager.add(toggleCaseSensitiveAction);
toggleKeepOpenAction = new ToggleKeepOpenAction(settings);
menuManager.add(toggleKeepOpenAction);
}
private void showViewMenu() {
Menu menu = menuManager.createContextMenu(getShell());
Rectangle bounds = toolItem.getBounds();
Point topLeft = new Point(bounds.x, bounds.y + bounds.height);
topLeft = toolBar.toDisplay(topLeft);
menu.setLocation(topLeft.x, topLeft.y);
menu.setVisible(true);
}
/**
* Hook that allows to add actions to the context menu.
* <p>
* Subclasses may extend in order to add other actions.</p>
*
* @param menuManager the context menu manager
* @since 3.5
*/
protected void fillContextMenu(IMenuManager menuManager) {
// List selectedElements= ((StructuredSelection)list.getSelection()).toList();
// Object item= null;
// for (Iterator it= selectedElements.iterator(); it.hasNext();) {
// item= it.next();
// if (item instanceof ItemsListSeparator || !isHistoryElement(item)) {
// return;
// if (selectedElements.size() > 0) {
// removeHistoryItemAction.setText(WorkbenchMessages.FilteredItemsSelectionDialog_removeItemsFromHistoryAction);
// menuManager.add(removeHistoryActionContributionItem);
}
private void createPopupMenu() {
// removeHistoryItemAction = new RemoveHistoryItemAction();
// removeHistoryActionContributionItem = new ActionContributionItem(
// removeHistoryItemAction);
contextMenuManager = new MenuManager();
contextMenuManager.setRemoveAllWhenShown(true);
contextMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
fillContextMenu(manager);
}
});
final Table table = list.getTable();
Menu menu= contextMenuManager.createContextMenu(table);
table.setMenu(menu);
}
// /**
// * Creates an extra content area, which will be located above the details.
// *
// * @param parent
// * parent to create the dialog widgets in
// * @return an extra content area
// */
// protected abstract Control createExtendedContentArea(Composite parent);
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite dialogArea = (Composite) super.createDialogArea(parent);
dialogArea.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
QuickSearchDialog.this.dispose();
}
});
Composite content = createNestedComposite(dialogArea, 1, false);
GridData gd = new GridData(GridData.FILL_BOTH);
content.setLayoutData(gd);
final Label headerLabel = createHeader(content);
Composite inputRow = createNestedComposite(content, 10, true);
GridDataFactory.fillDefaults().grab(true, false).applyTo(inputRow);
pattern = new Text(inputRow, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.ICON_CANCEL);
pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
e.result = LegacyActionTools.removeMnemonics(headerLabel
.getText());
}
});
GridDataFactory.fillDefaults().span(6,1).grab(true, false).applyTo(pattern);
Composite searchInComposite = createNestedComposite(inputRow, 2, false);
GridDataFactory.fillDefaults().span(4,1).grab(true, false).applyTo(searchInComposite);
Label searchInLabel = new Label(searchInComposite, SWT.NONE);
searchInLabel.setText(" In: ");
searchIn = new Text(searchInComposite, SWT.SINGLE | SWT.BORDER | SWT.ICON_CANCEL);
searchIn.setToolTipText("Search in (comma-separated list of '.gitignore' style inclusion patterns)");
GridDataFactory.fillDefaults().grab(true, false).applyTo(searchIn);
final Label listLabel = createLabels(content);
sashForm = new SashForm(content, SWT.VERTICAL);
GridDataFactory.fillDefaults().grab(true, true).applyTo(sashForm);
list = new TableViewer(sashForm, (multi ? SWT.MULTI : SWT.SINGLE) |
SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL | SWT.VIRTUAL);
// ColumnViewerToolTipSupport.enableFor(list, ToolTip.NO_RECREATE);
list.getTable().setHeaderVisible(true);
list.getTable().setLinesVisible(true);
list.getTable().getAccessible().addAccessibleListener(
new AccessibleAdapter() {
public void getName(AccessibleEvent e) {
if (e.childID == ACC.CHILDID_SELF) {
e.result = LegacyActionTools
.removeMnemonics(listLabel.getText());
}
}
});
list.setContentProvider(contentProvider);
// new ScrollListener(list.getTable().getVerticalBar());
// new SelectionChangedListener(list);
TableViewerColumn col = new TableViewerColumn(list, SWT.RIGHT);
col.setLabelProvider(LINE_NUMBER_LABEL_PROVIDER);
col.getColumn().setText("Line");
col.getColumn().setWidth(40);
col = new TableViewerColumn(list, SWT.LEFT);
col.getColumn().setText("Text");
col.setLabelProvider(LINE_TEXT_LABEL_PROVIDER);
col.getColumn().setWidth(400);
col = new TableViewerColumn(list, SWT.LEFT);
col.getColumn().setText("Path");
col.setLabelProvider(LINE_FILE_LABEL_PROVIDER);
col.getColumn().setWidth(150);
new TableResizeHelper(list).enableResizing();
//list.setLabelProvider(getItemsListLabelProvider());
list.setInput(new Object[0]);
list.setItemCount(contentProvider.getNumberOfElements());
gd = new GridData(GridData.FILL_BOTH);
applyDialogFont(list.getTable());
gd.heightHint= list.getTable().getItemHeight() * 15;
list.getTable().setLayoutData(gd);
createPopupMenu();
pattern.addModifyListener(e -> {
applyFilter(false);
});
searchIn.addModifyListener(e -> {
applyPathMatcher();
});
pattern.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN) {
if (list.getTable().getItemCount() > 0) {
list.getTable().setFocus();
list.getTable().select(0);
//programatic selection may not fire selection events so...
refreshDetails();
}
}
}
});
list.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
StructuredSelection selection = (StructuredSelection) event
.getSelection();
handleSelected(selection);
}
});
list.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick();
}
});
list.getTable().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.SHIFT) == 0
&& (e.stateMask & SWT.CTRL) == 0) {
StructuredSelection selection = (StructuredSelection) list
.getSelection();
if (selection.size() == 1) {
Object element = selection.getFirstElement();
if (element.equals(list.getElementAt(0))) {
pattern.setFocus();
}
list.getTable().notifyListeners(SWT.Selection,
new Event());
}
}
if (e.keyCode == SWT.ARROW_DOWN
&& (e.stateMask & SWT.SHIFT) != 0
&& (e.stateMask & SWT.CTRL) != 0) {
list.getTable().notifyListeners(SWT.Selection, new Event());
}
}
});
createDetailsArea(sashForm);
sashForm.setWeights(new int[] {5,1});
applyDialogFont(content);
restoreDialog(getDialogSettings());
if (initialPatternText != null) {
pattern.setText(initialPatternText);
}
switch (selectionMode) {
case CARET_BEGINNING:
pattern.setSelection(0, 0);
break;
case FULL_SELECTION:
pattern.setSelection(0, initialPatternText.length());
break;
}
// apply filter even if pattern is empty (display history)
applyFilter(false);
return dialogArea;
}
private Composite createNestedComposite(Composite parent, int numRows, boolean equalRows) {
Composite nested = new Composite(parent, SWT.NONE);
{
GridLayout layout = new GridLayout(numRows, equalRows);
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.horizontalSpacing = 0;
nested.setLayout(layout);
}
GridDataFactory.fillDefaults().grab(true, false).applyTo(nested);
return nested;
}
protected void dispose() {
if (blankImage!=null) {
blankImage.dispose();
blankImage = null;
}
}
private void createDetailsArea(Composite parent) {
details = new StyledText(parent, SWT.MULTI+SWT.READ_ONLY+SWT.BORDER+SWT.H_SCROLL);
details.setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
// GridDataFactory.fillDefaults().grab(true, false).applyTo(details);
// details = new SourceViewer(parent, null, SWT.READ_ONLY+SWT.MULTI+SWT.BORDER);
// details.getTextWidget().setText("Line 1\nLine 2\nLine 3\nLine 4\nLine 5");
// details.setEditable(false);
// IPreferenceStore prefs = EditorsPlugin.getDefault().getPreferenceStore();
// TextSourceViewerConfiguration sourceViewerConf = new TextSourceViewerConfiguration(prefs);
// details.configure(sourceViewerConf);
// GridDataFactory.fillDefaults().grab(true, false).applyTo(details);
// Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
// details.getTextWidget().setFont(font);
list.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
refreshDetails();
}
});
details.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
refreshDetails();
}
});
}
// Dumber version just using the a 'raw' StyledText widget.
private void refreshDetails() {
if (details!=null && list!=null && !list.getTable().isDisposed()) {
if (documents==null) {
documents = new DocumentFetcher();
}
IStructuredSelection sel = (IStructuredSelection) list.getSelection();
if (sel==null || sel.isEmpty()) {
details.setText("");
} else {
//Not empty selection
int numLines = computeLines();
if (numLines > 0) {
LineItem item = (LineItem) sel.getFirstElement();
IDocument document = documents.getDocument(item.getFile());
try {
int line = item.getLineNumber()-1; //in document lines are 0 based. In search 1 based.
int start = document.getLineOffset(Math.max(line-(numLines-1)/2, 0));
int end = document.getLength();
try {
end = document.getLineOffset(start+numLines);
} catch (BadLocationException e) {
//Presumably line number is past the end of document.
//ignore.
}
StyledString styledString = highlightMatches(document.get(start, end-start));
details.setText(styledString.getString());
details.setStyleRanges(styledString.getStyleRanges());
return;
} catch (BadLocationException e) {
}
}
}
//empty selection or some error:
details.setText("");
}
}
/**
* Computes how much lines of text can be displayed in the details section based on
* its current height and font metrics.
*/
private int computeLines() {
if (details!=null && !details.isDisposed()) {
GC gc = new GC(details);
try {
FontMetrics fm = gc.getFontMetrics();
int itemH = fm.getHeight();
int areaH = details.getClientArea().height;
return (areaH+itemH-1) / itemH;
} finally {
gc.dispose();
}
}
return 0;
}
/**
* Helper function to highlight all the matches for the current query in a given piece
* of text.
*
* @return StyledString instance.
*/
private StyledString highlightMatches(String visibleText) {
StyledString styledText = new StyledString(visibleText);
List<TextRange> matches = getQuery().findAll(visibleText);
for (TextRange m : matches) {
styledText.setStyle(m.getOffset(), m.getLength(), HIGHLIGHT_STYLE);
}
return styledText;
}
// Version using sourceviewer
// private void refreshDetails() {
// if (details!=null && list!=null && !list.getTable().isDisposed()) {
// if (documents==null) {
// documents = new DocumentFetcher();
// IStructuredSelection sel = (IStructuredSelection) list.getSelection();
// if (sel!=null && !sel.isEmpty()) {
// //Not empty selection
// LineItem item = (LineItem) sel.getFirstElement();
// IDocument document = documents.getDocument(item.getFile());
// try {
// int line = item.getLineNumber()-1; //in document lines are 0 based. In search 1 based.
// int start = document.getLineOffset(Math.max(line-2, 0));
// int end = document.getLength();
// try {
// end = document.getLineOffset(line+3);
// } catch (BadLocationException e) {
// //Presumably line number is past the end of document.
// //ignore.
// details.setDocument(document, start, end-start);
// String visibleText = document.get(start, end-start);
// List<TextRange> matches = getQuery().findAll(visibleText);
// Region visibleRegion = new Region(start, end-start);
// TextPresentation presentation = new TextPresentation(visibleRegion, 20);
// presentation.setDefaultStyleRange(new StyleRange(0, document.getLength(), null, null));
// for (TextRange m : matches) {
// presentation.addStyleRange(new StyleRange(m.start+start, m.len, null, YELLOW));
// details.changeTextPresentation(presentation, true);
// return;
// } catch (BadLocationException e) {
// details.setDocument(null);
/**
* Handle selection in the items list by updating labels of selected and
* unselected items and refresh the details field using the selection.
*
* @param selection
* the new selection
*/
protected void handleSelected(StructuredSelection selection) {
IStatus status = new Status(IStatus.OK, PlatformUI.PLUGIN_ID,
IStatus.OK, EMPTY_STRING, null);
updateStatus(status);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Dialog#getDialogBoundsSettings()
*/
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = getDialogSettings();
IDialogSettings section = settings.getSection(DIALOG_BOUNDS_SETTINGS);
if (section == null) {
section = settings.addNewSection(DIALOG_BOUNDS_SETTINGS);
section.put(DIALOG_HEIGHT, 500);
section.put(DIALOG_WIDTH, 600);
}
return section;
}
/**
* Returns the dialog settings. Returned object can't be null.
*
* @return return dialog settings for this dialog
*/
protected IDialogSettings getDialogSettings() {
IDialogSettings settings = IDEWorkbenchPlugin.getDefault()
.getDialogSettings().getSection(DIALOG_SETTINGS);
if (settings == null) {
settings = IDEWorkbenchPlugin.getDefault().getDialogSettings()
.addNewSection(DIALOG_SETTINGS);
}
return settings;
}
/**
* Has to be called in UI thread.
*/
public void refreshWidgets() {
if (list != null && !list.getTable().isDisposed()) {
// ScrollBar sb = list.getTable().getVerticalBar();
// int oldScroll = sb.getSelection();
int itemCount = contentProvider.getNumberOfElements();
list.setItemCount(itemCount);
list.refresh(true, false);
Button goButton = getButton(GO_BUTTON_ID);
if (goButton!=null && !goButton.isDisposed()) {
//Even if no element is selected. The dialog should be have as if the first
//element in the list is selected. So the button is enabled if any
//element is available in the list.
goButton.setEnabled(itemCount>0);
}
// int newScroll = sb.getSelection();
// if (oldScroll!=newScroll) {
// System.out.println("Scroll moved in refresh: "+oldScroll+ " => " + newScroll);
//sb.setSelection((int) Math.floor(oldScroll*sb.getMaximum()));
}
// The code below attempts to preserve selection, but it also messes up the
// scroll position (reset to 0) in the common case where selection is first element
// and more elements are getting added as I scroll down to bottom of list.
// list.getTable().deselectAll();
// list.setItemCount(contentProvider.getNumberOfElements());
// list.refresh(/*updateLabels*/true, /*reveal*/false);
// if (list.getTable().getItemCount() > 0) {
// // preserve previous selection
// if (lastRefreshSelection != null) {
// if (lastRefreshSelection.size() > 0) {
// list.setSelection(new StructuredSelection(lastRefreshSelection), false);
// } else {
// list.setSelection(StructuredSelection.EMPTY, false);
// } else {
// list.setSelection(StructuredSelection.EMPTY);
}
/**
* Schedule refresh job.
*/
public void scheduleRefresh() {
refreshJob.schedule();
// list.re
// refreshCacheJob.cancelAll();
// refreshCacheJob.schedule();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult()
*/
protected void computeResult() {
List objectsToReturn = ((StructuredSelection) list.getSelection())
.toList();
if (objectsToReturn.isEmpty()) {
//Pretend that the first element is selected.
Object first = list.getElementAt(0);
if (first!=null) {
objectsToReturn = Arrays.asList(first);
}
}
setResult(objectsToReturn);
}
/**
* Handles double-click of items, but *also* by pressing the 'enter' key.
*/
protected void handleDoubleClick() {
goButtonPressed();
}
protected void refreshButtonPressed() {
applyFilter(true);
}
/**
* Handles directly clicking the 'go' button.
*/
protected void goButtonPressed() {
computeResult();
openSelection();
if (!toggleKeepOpenAction.isChecked()) {
close();
}
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
SelectionListener listener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int buttonId = (int) ((Button)e.widget).getData();
if (buttonId==GO_BUTTON_ID) {
goButtonPressed();
} else if (buttonId==REFRESH_BUTTON_ID) {
refreshButtonPressed();
}
}
};
createButton(parent, GO_BUTTON_ID, "Go!", false).addSelectionListener(listener);
createButton(parent, REFRESH_BUTTON_ID, "Refresh", false).addSelectionListener(listener);
refreshWidgets();
}
/**
* Sets the initial pattern used by the filter. This text is copied into the
* selection input on the dialog. A full selection is used in the pattern
* input field.
*
* @param text
* initial pattern for the filter
* @see QuickSearchDialog#FULL_SELECTION
*/
public void setInitialPattern(String text) {
setInitialPattern(text, FULL_SELECTION);
}
/**
* Sets the initial pattern used by the filter. This text is copied into the
* selection input on the dialog. The <code>selectionMode</code> is used
* to choose selection type for the input field.
*
* @param text
* initial pattern for the filter
* @param selectionMode
* one of: {@link QuickSearchDialog#NONE},
* {@link QuickSearchDialog#CARET_BEGINNING},
* {@link QuickSearchDialog#FULL_SELECTION}
*/
public void setInitialPattern(String text, int selectionMode) {
this.initialPatternText = text;
this.selectionMode = selectionMode;
}
/**
* Gets initial pattern.
*
* @return initial pattern, or <code>null</code> if initial pattern is not
* set
*/
protected String getInitialPattern() {
return this.initialPatternText;
}
/**
* Returns the current selection.
*
* @return the current selection
*/
protected StructuredSelection getSelectedItems() {
StructuredSelection selection = (StructuredSelection) list
.getSelection();
List selectedItems = selection.toList();
return new StructuredSelection(selectedItems);
}
/**
* Validates the item. When items on the items list are selected or
* deselected, it validates each item in the selection and the dialog status
* depends on all validations.
*
* @param item
* an item to be checked
* @return status of the dialog to be set
*/
protected IStatus validateItem(Object item) {
return new Status(IStatus.OK, QuickSearchActivator.PLUGIN_ID, "fine");
}
/**
* Creates an instance of a filter.
*
* @return a filter for items on the items list. Can be <code>null</code>,
* no filtering will be applied then, causing no item to be shown in
* the list.
*/
protected QuickTextQuery createFilter() {
return new QuickTextQuery(pattern.getText(), toggleCaseSensitiveAction.isChecked());
}
protected void applyFilter(boolean force) {
QuickTextQuery newFilter = createFilter();
if (this.searcher==null) {
if (!newFilter.isTrivial()) {
//Create the QuickTextSearcher with the inital query.
this.searcher = new QuickTextSearcher(newFilter, context.createPriorityFun(), MAX_LINE_LEN, new QuickTextSearchRequestor() {
@Override
public void add(LineItem match) {
contentProvider.add(match);
contentProvider.refresh();
}
@Override
public void clear() {
contentProvider.reset();
contentProvider.refresh();
}
@Override
public void revoke(LineItem match) {
contentProvider.remove(match);
contentProvider.refresh();
}
@Override
public void update(LineItem match) {
contentProvider.refresh();
}
});
applyPathMatcher();
refreshWidgets();
}
// this.list.setInput(input)
} else {
//The QuickTextSearcher is already active update the query
this.searcher.setQuery(newFilter, force);
}
if (progressJob!=null) {
progressJob.schedule();
}
}
private void applyPathMatcher() {
if (this.searcher!=null) {
this.searcher.setPathMatcher(ResourceMatchers.commaSeparatedPaths(searchIn.getText()));
}
}
/**
* Returns name for then given object.
*
* @param item
* an object from the content provider. Subclasses should pay
* attention to the passed argument. They should either only pass
* objects of a known type (one used in content provider) or make
* sure that passed parameter is the expected one (by type
* checking like <code>instanceof</code> inside the method).
* @return name of the given item
*/
public String getElementName(Object item) {
return ""+item;
// return (String)item; // Assuming the items are strings for now
}
/**
* Collects filtered elements. Contains one synchronized, sorted set for
* collecting filtered elements.
* Implementation of <code>ItemsFilter</code> is used to filter elements.
* The key function of filter used in to filtering is
* <code>matchElement(Object item)</code>.
* <p>
* The <code>ContentProvider</code> class also provides item filtering
* methods. The filtering has been moved from the standard TableView
* <code>getFilteredItems()</code> method to content provider, because
* <code>ILazyContentProvider</code> and virtual tables are used. This
* class is responsible for adding a separator below history items and
* marking each items as duplicate if its name repeats more than once on the
* filtered list.
*/
private class ContentProvider implements IStructuredContentProvider, ILazyContentProvider {
private List items;
/**
* Creates new instance of <code>ContentProvider</code>.
*/
public ContentProvider() {
this.items = Collections.synchronizedList(new ArrayList(2048));
// this.duplicates = Collections.synchronizedSet(new HashSet(256));
// this.lastSortedItems = Collections.synchronizedList(new ArrayList(
// 2048));
}
public void remove(LineItem match) {
this.items.remove(match);
}
/**
* Removes all content items and resets progress message.
*/
public void reset() {
this.items.clear();
}
/**
* Adds filtered item.
*
* @param match
*/
public void add(LineItem match) {
this.items.add(match);
}
/**
* Refresh dialog.
*/
public void refresh() {
scheduleRefresh();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return items.toArray();
}
public int getNumberOfElements() {
return items.size();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ILazyContentProvider#updateElement(int)
*/
public void updateElement(int index) {
QuickSearchDialog.this.list.replace((items
.size() > index) ? items.get(index) : null,
index);
}
}
/**
* Get the control where the search pattern is entered. Any filtering should
* be done using an {@link ItemsFilter}. This control should only be
* accessed for listeners that wish to handle events that do not affect
* filtering such as custom traversal.
*
* @return Control or <code>null</code> if the pattern control has not
* been created.
*/
public Control getPatternControl() {
return pattern;
}
public QuickTextQuery getQuery() {
return searcher.getQuery();
}
}
|
package org.csstudio.utility.ldapUpdater;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.csstudio.platform.service.osgi.OsgiServiceUnavailableException;
import org.csstudio.utility.ldap.service.ILdapService;
import org.csstudio.utility.ldap.service.LdapServiceTracker;
import org.csstudio.utility.ldapUpdater.service.ILdapServiceProvider;
import org.csstudio.utility.ldapUpdater.service.ILdapUpdaterService;
import org.csstudio.utility.ldapUpdater.service.impl.LdapUpdaterServiceImpl;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
import org.remotercp.common.tracker.GenericServiceTracker;
import org.remotercp.common.tracker.IGenericServiceListener;
import org.remotercp.service.connection.session.ISessionService;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* The activator class controls the plug-in life cycle
*/
public class LdapUpdaterActivator implements BundleActivator {
/**
* The id of this Java plug-in (value <code>{@value}</code> as defined in MANIFEST.MF.
*/
public static final String PLUGIN_ID = "org.csstudio.utility.ldapUpdater";
/**
* The shared instance
*/
private static LdapUpdaterActivator INSTANCE;
private ServiceTracker _ldapServiceTracker;
private GenericServiceTracker<ISessionService> _genericServiceTracker;
private LdapUpdaterServiceImpl _ldapUpdaterService;
/**
* Don't instantiate.
* Called by framework.
*/
public LdapUpdaterActivator() {
if (INSTANCE != null) {
throw new IllegalStateException("Activator " + PLUGIN_ID + " does already exist.");
}
INSTANCE = this; // Antipattern is required by the framework!
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
@Nonnull
public static LdapUpdaterActivator getDefault() {
return INSTANCE;
}
/**
* {@inheritDoc}
*/
@Override
public void start(@Nullable final BundleContext context) throws Exception {
_ldapServiceTracker = new LdapServiceTracker(context);
_ldapServiceTracker.open();
_genericServiceTracker =
new GenericServiceTracker<ISessionService>(context, ISessionService.class);
_genericServiceTracker.open();
final ILdapServiceProvider provider =
new ILdapServiceProvider() {
@Override
@Nonnull
public ILdapService getLdapService() throws OsgiServiceUnavailableException {
@SuppressWarnings("synthetic-access")
final ILdapService service = (ILdapService) _ldapServiceTracker.getService();
if (service == null) {
throw new OsgiServiceUnavailableException("LDAP service could not be retrieved. Please try again later or check LDAP connection.");
}
return service;
}
};
final Injector injector = Guice.createInjector(new LdapUpdaterModule(provider));
_ldapUpdaterService = injector.getInstance(LdapUpdaterServiceImpl.class);
}
/**
* {@inheritDoc}
*/
@Override
public void stop(@Nullable final BundleContext context) throws Exception {
_ldapServiceTracker.close();
}
@Nonnull
public static String getPluginId() {
return PLUGIN_ID;
}
public void addSessionServiceListener(@Nonnull final IGenericServiceListener<ISessionService> sessionServiceListener) {
_genericServiceTracker.addServiceListener(sessionServiceListener);
}
/**
* ANTI-PATTERN due to extension points. Cannot inject services in extension point classes.
*/
@Nonnull
public ILdapUpdaterService getLdapUpdaterService() throws OsgiServiceUnavailableException {
if (_ldapUpdaterService == null) {
throw new OsgiServiceUnavailableException("Service field has not been set. Hasnt' the framework called Activator.start before?");
}
return _ldapUpdaterService;
}
}
|
package com.opengamma.analytics.financial.model.volatility.smile.fitting.demo;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.testng.annotations.Test;
import cern.jet.random.engine.MersenneTwister;
import cern.jet.random.engine.RandomEngine;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.HestonModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.MixedLogNormalModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SABRModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SVIModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.SmileModelFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.BenaimDodgsonKainthExtrapolationFunctionProvider;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.GeneralSmileInterpolator;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.ShiftedLogNormalTailExtrapolation;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.ShiftedLogNormalTailExtrapolationFitter;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolatorSABR;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolatorSpline;
import com.opengamma.analytics.financial.model.volatility.smile.function.HestonVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.MixedLogNormalVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SABRFormulaData;
import com.opengamma.analytics.financial.model.volatility.smile.function.SABRHaganVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SVIVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.smile.function.SmileModelData;
import com.opengamma.analytics.financial.model.volatility.smile.function.VolatilityFunctionProvider;
import com.opengamma.analytics.math.differentiation.ScalarFirstOrderDifferentiator;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.BasisFunctionGenerator;
import com.opengamma.analytics.math.interpolation.BasisFunctionKnots;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.statistics.leastsquare.GeneralizedLeastSquare;
import com.opengamma.analytics.math.statistics.leastsquare.GeneralizedLeastSquareResults;
import com.opengamma.analytics.math.statistics.leastsquare.LeastSquareResultsWithTransform;
/**
* This uses Dec-2014 options on the S&P 500 index. The trade date is 20-Oct-2014 09:40 and the expiry is 19-Dec-2014 21:15
* (nominal expiry is 20-Dec-2014, which is a Saturday)
*/
public class SmileFittingDemo {
private static RandomEngine RANDOM = new MersenneTwister();
private static final double fwd = 1879.52;
private static final double r = 0.00231;
private static final double t = 60.49514 / 365.;
private static final double[] strikes = new double[] {1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2150, 2250 };
private static final double[] iv = new double[] {0.25907, 0.23819, 0.21715, 0.19517, 0.17684, 0.15383, 0.13577, 0.12505, 0.1564, 0.17344 };
private static VolatilityFunctionProvider<SABRFormulaData> SABR = new SABRHaganVolatilityFunction();
private static double[] errors;
private static final GeneralSmileInterpolator SABR_INTERPOLATOR = new SmileInterpolatorSABR();
private static final int NUM_SAMPLES = 101;
private static final double LOWER_STRIKE = 1500.0;
private static final double UPPER_STRIKE = 2500.0;
static {
int n = iv.length;
errors = new double[n];
Arrays.fill(errors, 1e-3); // 10bps
}
/**
* Global fitters: These fit a smile model to market data in a least squares sense. Extrapolation just involves
* using the calibrated parameters with the model for strikes outside the fitted range.
*/
/**
* Fit the SABR model to market implied volatilities. The parameter beta is fixed at 1, so a three parameter fit is
* made.
*/
@Test(description = "Demo")
public void globalSabrFitDemo() {
// SABR starting parameters
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(fwd, 1 - beta);
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SmileModelFitter<SABRFormulaData> sabrFitter = new SABRModelFitter(fwd, strikes, t, iv, errors, SABR);
fitAndPrintSmile(sabrFitter, start, fixed);
}
/**
* Fit the SABR model to market implied volatilities. The parameter beta is fixed at 1, so a three parameter fit is
* made. This differs from the example above in that outside the range of market strikes a shifted log-normal is
* use to extrapolate the smile.
*/
@Test(description = "Demo")
public void globalSabrFitWithExtrapolationDemo() {
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(fwd, 1 - beta);
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SmileModelFitter<SABRFormulaData> sabrFitter = new SABRModelFitter(fwd, strikes, t, iv, errors, SABR);
fitAndPrintSmile(sabrFitter, start, fixed, strikes[0], strikes[strikes.length-1]);
}
/**
* Again fit global SABR, but now use Benaim-Dodgson-Kainth extrapolation
*/
@Test(description = "Demo")
public void globalSabrFitWithBDKExtrapolationDemo() {
BitSet fixed = new BitSet();
fixed.set(1);
double atmVol = 0.18;
double beta = 1.0;
double rho = -0.9;
double nu = 1.8;
double alpha = atmVol * Math.pow(fwd, 1 - beta);
double muLow = 4.0;
double muHigh = 0.6;
DoubleMatrix1D start = new DoubleMatrix1D(alpha, beta, rho, nu);
SABRModelFitter sabrFitter = new SABRModelFitter(fwd, strikes, t, iv, errors, SABR);
fitAndPrintSmile(sabrFitter, start, fixed, strikes[0], strikes[strikes.length-1],muLow,muHigh);
}
/**
* Fit the SVI model to market implied volatilities
* <p>
* The model has 5 parameters $a,b,\rho,\nu$ and $m$, and the variance is given by $\sigma^2 = a+b(\rho d + \sqrt{d^2+\nu^2})$ where $d= \ln\left(\frac{k}{f}\right)-m$ With $m=0$, the ATMF vol is
* given by $\sigma = \sqrt{a+b\nu}$
* <p>
* Note: the solution is sensitive to the starting position (many 'sensible' starting points give a local minimum)
*/
@Test(description = "Demo")
public void globalSVIFitDemo() {
SVIVolatilityFunction model = new SVIVolatilityFunction();
SVIModelFitter sviFitter = new SVIModelFitter(fwd, strikes, t, iv, errors, model);
DoubleMatrix1D start = new DoubleMatrix1D(0.015, 0.1, -0.3, 0.3, 0.0);
BitSet fixed = new BitSet();
fitAndPrintSmile(sviFitter, start, fixed);
}
/**
* Fit the Heston model market implied volatilities.
* <p>
* Parameters of the Heston model are:
* <ul>
* <li>kappa mean-reverting speed
* <li>theta mean-reverting level
* <li>vol0 starting value of volatility
* <li>omega volatility-of-volatility
* <li>rho correlation between the spot process and the volatility process
* </ul>
* <p>
* Note: the solution is sensitive to the starting position (many 'sensible' starting points give a local minimum)
*/
@Test(description = "Demo")
public void globalHestonFitDemo() {
HestonVolatilityFunction model = new HestonVolatilityFunction();
HestonModelFitter fitter = new HestonModelFitter(fwd, strikes, t, iv, errors, model);
DoubleMatrix1D start = new DoubleMatrix1D(0.1, 0.02, 0.02, 0.4, -0.5);
BitSet fixed = new BitSet();
fitAndPrintSmile(fitter, start, fixed);
}
/**
* Fit a mixed log-normal model to market implied volatilities. This example uses 2 normals which are
* allowed to have different means, so there are 4 (2*3-2) degrees of freedom. In principle 3 normals (7=3*3-2 DoF)
* will give a better fit, but the plethora of local minima massively hampers this.
*/
@Test(description = "Demo")
void mixedLogNormalFitDemo() {
int nNorms = 2;
boolean useShiftedMeans = true;
MixedLogNormalVolatilityFunction model = MixedLogNormalVolatilityFunction.getInstance();
MixedLogNormalModelFitter fitter = new MixedLogNormalModelFitter(fwd, strikes, t, iv, errors, model, nNorms, useShiftedMeans);
DoubleMatrix1D start = new DoubleMatrix1D(0.1, 0.2, 1.5, 1.5);
BitSet fixed = new BitSet();
fitAndPrintSmile(fitter, start, fixed);
}
/**
* Fit a smile model to the data set, and print the resultant smile between LOWER_STRIKE and UPPER_STRIKE
* @param fitter the smile fitter
* @param start this initial starting point of the model parameters
* @param fixed map of any fixed parameters
*/
private void fitAndPrintSmile(SmileModelFitter<? extends SmileModelData> fitter, DoubleMatrix1D start, BitSet fixed) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<?> model = fitter.getModel();
SmileModelData data = fitter.toSmileModelData(res.getModelParameters());
Function1D<Double, Double> smile = toSmileFunction(fwd, t, data, model);
printSmile(smile);
}
private void fitAndPrintSmile(SmileModelFitter<? extends SmileModelData> fitter, DoubleMatrix1D start, BitSet fixed,
double lowerStrike, double upperStrike) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<?> model = fitter.getModel();
SmileModelData data = fitter.toSmileModelData(res.getModelParameters());
Function1D<Double, Double> smile = toSmileFunction(fwd, t, data, model);
Function1D<Double, Double> extrapSmile = fitShiftedLogNormalTails(fwd, t, smile, lowerStrike, upperStrike);
printSmile(extrapSmile);
}
private void fitAndPrintSmile(SABRModelFitter fitter, DoubleMatrix1D start, BitSet fixed,
final double lowerStrike, final double upperStrike, double lowerMu, double upperMu) {
LeastSquareResultsWithTransform res = fitter.solve(start, fixed);
System.out.println("chi-Square: " + res.getChiSq());
VolatilityFunctionProvider<SABRFormulaData> model = fitter.getModel();
SABRFormulaData data = fitter.toSmileModelData(res.getModelParameters());
final Function1D<Double, Double> smile = toSmileFunction(fwd, t, data, model);
BenaimDodgsonKainthExtrapolationFunctionProvider tailPro = new BenaimDodgsonKainthExtrapolationFunctionProvider(lowerMu, upperMu);
final Function1D<Double, Double> extrapFunc = tailPro.getExtrapolationFunction(data,data,model,fwd,t,lowerStrike,upperStrike);
Function1D<Double, Double> smileWithExtrap = new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
if(k < lowerStrike || k > upperStrike) {
return extrapFunc.evaluate(k);
}
return smile.evaluate(k);
}
};
printSmile(smileWithExtrap);
}
private void printSmile( Function1D<Double, Double> smile) {
System.out.println("Strike\tImplied Volatility");
double range = (UPPER_STRIKE - LOWER_STRIKE) / (NUM_SAMPLES - 1.0);
for (int i = 0; i < NUM_SAMPLES; i++) {
double k = LOWER_STRIKE + i * range;
double vol = smile.evaluate(k);
System.out.println(k + "\t" + vol);
}
}
@Test
void golbalSABRwithShiftedLogNormalExtrapolation() {
ShiftedLogNormalTailExtrapolationFitter tailfitter = new ShiftedLogNormalTailExtrapolationFitter();
}
/**
* Extrapolate a volatility smile to low and high strikes by fitting (separately) a shifted-log-normal model at
* the low and high strike cutoffs
* @param forward the forward
* @param expiry the expiry
* @param volSmileFunc a function describing the smile (Black vol as a function of strike)
* @param lowerStrike the lower strike
* @param upperStrike the upper strike
* @return a volatility smile (Black vol as a function of strike) that is valid for strikes from zero to infinity
*/
private Function1D<Double, Double> fitShiftedLogNormalTails(final double forward, final double expiry, final Function1D<Double, Double> volSmileFunc, final double lowerStrike,
final double upperStrike) {
ScalarFirstOrderDifferentiator diff = new ScalarFirstOrderDifferentiator();
Function1D<Double, Double> dVolDkFunc = diff.differentiate(volSmileFunc);
return fitShiftedLogNormalTails(forward, expiry, volSmileFunc, dVolDkFunc, lowerStrike, upperStrike);
}
/**
* Extrapolate a volatility smile to low and high strikes by fitting (separately) a shifted-log-normal model at
* the low and high strike cutoffs.
* @param forward the forward
* @param expiry the expiry
* @param volSmileFunc a function describing the smile (Black vol as a function of strike)
* @param dVolDkFunc the gradient of the smile as a function of strike
* @param lowerStrike the lower strike
* @param upperStrike the upper strike
* @return a volatility smile (Black vol as a function of strike) that is valid for strikes from zero to infinity
*/
private Function1D<Double, Double> fitShiftedLogNormalTails(final double forward, final double expiry, final Function1D<Double, Double> volSmileFunc, final Function1D<Double, Double> dVolDkFunc,
final double lowerStrike, final double upperStrike) {
ShiftedLogNormalTailExtrapolationFitter tailFitter = new ShiftedLogNormalTailExtrapolationFitter();
double vol = volSmileFunc.evaluate(lowerStrike);
double volGrad = dVolDkFunc.evaluate(lowerStrike);
final double[] lowerParms = tailFitter.fitVolatilityAndGrad(forward, lowerStrike, vol, volGrad, expiry);
vol = volSmileFunc.evaluate(upperStrike);
volGrad = dVolDkFunc.evaluate(upperStrike);
final double[] upperParms = tailFitter.fitVolatilityAndGrad(forward, upperStrike, vol, volGrad, expiry);
return new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
if (k >= lowerStrike && k <= upperStrike) {
return volSmileFunc.evaluate(k);
}
if (k < lowerStrike) {
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, lowerParms[0], lowerParms[1]);
}
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, upperParms[0], upperParms[1]);
}
};
}
/**
* gets a smile function (Black vol as a function of strike) from a VolatilityFunctionProvider and SmileModelData
* @param fwd the forward
* @param expiry the expiry
* @param data parameters of the smile model (e.g. for SABR these would be alpha, beta, rho and nu)
* @param volModel the volatility model
* @return the smile function
*/
private Function1D<Double, Double> toSmileFunction(final double fwd, final double expiry, final SmileModelData data, final VolatilityFunctionProvider<? extends SmileModelData> volModel) {
return new Function1D<Double, Double>() {
@Override
public Double evaluate(Double k) {
boolean isCall = k >= fwd;
EuropeanVanillaOption option = new EuropeanVanillaOption(k, expiry, isCall);
@SuppressWarnings("unchecked")
Function1D<SmileModelData, Double> func = (Function1D<SmileModelData, Double>) volModel.getVolatilityFunction(option, fwd);
return func.evaluate(data);
}
};
}
@Test
void sabrInterpolationTest() {
Function1D<Double, Double> func = SABR_INTERPOLATOR.getVolatilityFunction(fwd, strikes, t, iv);
int nSamples = 100;
System.out.println("Strike\tImplied Volatility");
for (int i = 0; i < nSamples; i++) {
double k = 1500 + 1000. * i / (nSamples - 1.0);
double vol = func.evaluate(k);
System.out.println(k + "\t" + vol);
}
}
@Test
void splineInterpolatorTest() {
GeneralSmileInterpolator spline = new SmileInterpolatorSpline();
Function1D<Double, Double> func = spline.getVolatilityFunction(fwd, strikes, t, iv);
int nSamples = 100;
System.out.println("Strike\tImplied Volatility");
for (int i = 0; i < nSamples; i++) {
double k = 1500 + 1000. * i / (nSamples - 1.0);
double vol = func.evaluate(k);
System.out.println(k + "\t" + vol);
}
}
@Test
void pSplineTest() {
BasisFunctionGenerator gen = new BasisFunctionGenerator();
BasisFunctionKnots knots = BasisFunctionKnots.fromUniform(1500, 2500, 20, 3);
List<Function1D<Double, Double>> set = gen.generateSet(knots);
GeneralizedLeastSquare gls = new GeneralizedLeastSquare();
int n = iv.length;
double[] var = new double[n];
for (int i = 0; i < n; i++) {
var[i] = iv[i] * iv[i];
}
double log10Lambda = 6;
double lambda = Math.pow(10.0, log10Lambda);
GeneralizedLeastSquareResults<Double> res = gls.solve(ArrayUtils.toObject(strikes), var, errors, set, lambda, 2);
// System.out.println(res);
Function1D<Double, Double> func = res.getFunction();
int nSamples = 100;
System.out.println("Strike\tImplied Volatility");
for (int i = 0; i < nSamples; i++) {
double k = 1500 + 1000. * i / (nSamples - 1.0);
double vol = Math.sqrt(func.evaluate(k));
System.out.println(k + "\t" + vol);
}
}
}
|
package org.hbird.transport.payloadcodec.codecparameters.string;
import java.util.BitSet;
import org.hbird.core.commons.tmtc.Parameter;
import org.hbird.core.commons.util.BitSetUtility;
import org.hbird.core.spacesystemmodel.encoding.Encoding;
import org.hbird.transport.payloadcodec.codecparameters.CodecParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
/**
* @author Mark Doyle
*
*/
public class Uft8StringCodecParameter extends CodecParameter<String> {
private static final long serialVersionUID = -2533245564627019039L;
private final static Logger LOG = LoggerFactory.getLogger(Uft8StringCodecParameter.class);
public Uft8StringCodecParameter(final Parameter<String> hostParameter, final Encoding encoding) {
super(hostParameter, encoding);
}
@Override
public void decode(final byte[] inBytes, final int offset) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
@Override
public void decode(final BitSet inBitset, final int offset) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
@Override
public byte[] encodeToByteArray(final byte[] targetBytes, final int offset) {
if (LOG.isDebugEnabled()) {
LOG.debug("Encoding value: " + getValue() + " to byte array at offset " + offset);
}
final byte[] bytes = this.getValue().getBytes(Charsets.UTF_8);
System.arraycopy(bytes, 0, targetBytes, offset, encoding.getSizeInBits() / Byte.SIZE);
return targetBytes;
}
@Override
public BitSet encodeToBitSet(final BitSet targetBitSet, final int offset) {
if (LOG.isDebugEnabled()) {
LOG.debug("Encoding value: " + getValue() + " to BitSet at offset " + offset);
}
final byte[] bytes = this.getValue().getBytes(Charsets.UTF_8);
final BitSet srcBitSet = BitSetUtility.fromByteArray(bytes);
// setting all bits to zero
targetBitSet.clear(offset, offset + encoding.getSizeInBits() - 1);
for (int i = offset; i < encoding.getSizeInBits(); i++) {
if (srcBitSet.get(i)) {
targetBitSet.set(i);
}
else {
targetBitSet.clear(i);
}
}
return targetBitSet;
}
}
|
package stroom.authentication.oauth2;
import stroom.authentication.api.OAuth2Client;
import stroom.authentication.api.OpenIdClientDetailsFactory;
import stroom.authentication.config.AuthenticationConfig;
import stroom.util.authentication.DefaultOpenIdCredentials;
import stroom.util.logging.LogUtil;
import javax.inject.Inject;
import java.security.SecureRandom;
import java.util.Objects;
public class OpenIdClientDetailsFactoryImpl implements OpenIdClientDetailsFactory {
private static final String INTERNAL_STROOM_CLIENT = "Stroom Client Internal";
private static final String CLIENT_ID_SUFFIX = ".client-id.apps.stroom-idp";
private static final String CLIENT_SECRET_SUFFIX = ".client-secret.apps.stroom-idp";
private static final char[] ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGJKLMNPRSTUVWXYZ0123456789"
.toCharArray();
private static final int ALLOWED_CHARS_COUNT = ALLOWED_CHARS.length;
private final DefaultOpenIdCredentials defaultOpenIdCredentials;
private final OAuth2Client oAuth2Client;
@Inject
public OpenIdClientDetailsFactoryImpl(final OAuth2ClientDao dao,
final AuthenticationConfig authenticationConfig,
final DefaultOpenIdCredentials defaultOpenIdCredentials) {
this.defaultOpenIdCredentials = defaultOpenIdCredentials;
// TODO The way this is implemented means we are limited to a single client when using our
// internal auth provider. Not sure this is what we want when we have stroom-stats in the
// mix. However to manage multiple client IDs we would probably need UI pages to do the CRUD on them.
final OAuth2Client oAuth2Client;
if (authenticationConfig.isUseDefaultOpenIdCredentials()) {
oAuth2Client = createDefaultOAuthClient();
} else {
oAuth2Client = dao.getClientByName(INTERNAL_STROOM_CLIENT)
.or(() -> {
// Generate new randomised client details and persist them
final OAuth2Client newOAuth2Client = createRandomisedOAuth2Client(INTERNAL_STROOM_CLIENT);
dao.create(newOAuth2Client);
return dao.getClientByName(INTERNAL_STROOM_CLIENT);
})
.orElseThrow(() ->
new NullPointerException("Unable to get or create internal client details"));
}
this.oAuth2Client = oAuth2Client;
}
public OAuth2Client getOAuth2Client() {
return oAuth2Client;
}
public OAuth2Client getOAuth2Client(final String clientId) {
// TODO currently only support one client ID so just have to throw if the client id is wrong
if (!Objects.requireNonNull(clientId).equals(oAuth2Client.getClientId())) {
throw new RuntimeException(LogUtil.message(
"Unexpected client ID: {}, expecting {}", clientId, oAuth2Client.getClientId()));
}
return oAuth2Client;
}
private OAuth2Client createDefaultOAuthClient() {
return new OAuth2Client(
defaultOpenIdCredentials.getOauth2ClientName(),
defaultOpenIdCredentials.getOauth2ClientId(),
defaultOpenIdCredentials.getOauth2ClientSecret(),
defaultOpenIdCredentials.getOauth2ClientUriPattern());
}
static OAuth2Client createRandomisedOAuth2Client(final String name) {
return new OAuth2Client(
name,
createRandomCode(40) + CLIENT_ID_SUFFIX,
createRandomCode(40) + CLIENT_SECRET_SUFFIX,
".*");
}
private static String createRandomCode(final int length) {
final SecureRandom secureRandom = new SecureRandom();
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(ALLOWED_CHARS[secureRandom.nextInt(ALLOWED_CHARS_COUNT)]);
}
return stringBuilder.toString();
}
}
|
package ttworkbench.play.parameters.ipv6.widgets.tableviewer;
import java.util.HashSet;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import ttworkbench.play.parameters.ipv6.common.ParameterValueUtil;
import com.testingtech.ttworkbench.ttman.parameters.api.IParameter;
import com.testingtech.ttworkbench.ttman.parameters.api.IParameterEditor;
import com.testingtech.ttworkbench.ttman.parameters.impl.ParameterChangedListener;
public class WidgetTableViewerAdvancedControl extends WidgetTableViewerControl {
private HashSet<IParameterEditor<?>> registeredListeners = new HashSet<IParameterEditor<?>>();
public WidgetTableViewerAdvancedControl(Composite parent) {
super(parent);
}
@Override
protected TableColumn createTableViewerColumn(final ColumnDefinition coldef) {
TableColumn tc = super.createTableViewerColumn( coldef);
final TableViewerColumn tvc = new TableViewerColumn( getTableViewer(), tc);
tvc.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
Object obj = cell.getElement();
if(obj instanceof IParameterEditor<?>) {
IParameterEditor<?> editor = (IParameterEditor<?>) obj;
checkCellListener(editor);
cell.setText( String.valueOf( coldef.columnType.valueOf( editor)));
}
}
});
if(coldef.columnType == ParameterEditorColumnType.COLUMN_PARAMETER_VALUE) {
tvc.setEditingSupport( new EditingSupport(getTableViewer()) {
@Override
protected void setValue(Object entity, Object value) {
if(entity instanceof IParameterEditor<?>) {
IParameterEditor<?> editor = (IParameterEditor<?>) entity;
Object currValue = editor.getParameter().getValue();
if(!currValue.equals( value)) {
ParameterValueUtil.setValue( editor.getParameter(), String.valueOf( value));
}
}
getTableViewer().refresh();
}
@Override
protected Object getValue(Object obj) {
Object out = null;
if(obj instanceof IParameterEditor<?>) {
IParameterEditor<?> editor = (IParameterEditor<?>) obj;
out = coldef.columnType.valueOf(editor);
}
return out;
}
@Override
protected CellEditor getCellEditor(final Object obj) {
Table table = getTableViewer().getTable();
if(obj instanceof IParameterEditor) {
return new CellParameterEditor(table) {
@SuppressWarnings("unchecked")
public IParameterEditor<Object> getEditor() {
return (IParameterEditor<Object>) obj;
}
};
}
return new TextCellEditor(table);
}
@Override
protected boolean canEdit(Object obj) {
boolean canEdit = obj instanceof IParameterEditor<?>; // && ((IParameterEditor<?>) obj).isEnabled();
return canEdit;
}
});
}
return tc;
}
protected <T> void checkCellListener(IParameterEditor<T> editor) {
if(registeredListeners.add( editor)) {
IParameter<T> parameter = editor.getParameter();
parameter.addParameterChangedListener( new ParameterChangedListener<T>() {
@Override
public void parameterChanged(IParameter<T> theTheParameter) {
getTableViewer().refresh();
}
});
}
}
}
|
package org.opendaylight.netvirt.natservice.internal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MatchInfo;
import org.opendaylight.genius.mdsalutil.MatchInfoBase;
import org.opendaylight.genius.mdsalutil.MetaDataUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadInPort;
import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadMetadata;
import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchCtState;
import org.opendaylight.netvirt.vpnmanager.api.IVpnManager;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.routers.ExternalIps;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.types.rev160517.IpPrefixOrAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.NxActionNatFlags;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowjava.nx.action.rev140421.NxActionNatRangePresent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConntrackBasedSnatService extends AbstractSnatService {
protected final int trackedNewCtState = 0x21;
protected final int trackedNewCtMask = 0x21;
protected final int snatCtState = 0x40;
protected final int snatCtStateMask = 0x40;
protected final int dnatCtState = 0x80;
protected final int dnatCtStateMask = 0x80;
private static final Logger LOG = LoggerFactory.getLogger(ConntrackBasedSnatService.class);
public ConntrackBasedSnatService(DataBroker dataBroker, IMdsalApiManager mdsalManager, ItmRpcService itmManager,
OdlInterfaceRpcService interfaceManager, IdManagerService idManager, NaptManager naptManager,
NAPTSwitchSelector naptSwitchSelector, IVpnManager vpnManager) {
super(dataBroker, mdsalManager, itmManager, interfaceManager, idManager, naptManager, naptSwitchSelector,
vpnManager);
}
@Override
protected void installSnatSpecificEntriesForNaptSwitch(Routers routers, BigInteger dpnId, int addOrRemove) {
LOG.info("ConntrackBasedSnatService: installSnatSpecificEntriesForNaptSwitch for router {}",
routers.getRouterName());
String routerName = routers.getRouterName();
Long routerId = NatUtil.getVpnId(dataBroker, routerName);
int elanId = NatUtil.getElanInstanceByName(routers.getNetworkId().getValue(), dataBroker)
.getElanTag().intValue();
/* Install Outbound NAT entries */
installSnatMissEntryForPrimrySwch(dpnId, routerId, elanId, addOrRemove);
installTerminatingServiceTblEntry(dpnId, routerId, elanId, addOrRemove);
List<ExternalIps> externalIps = routers.getExternalIps();
String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
createOutboundTblTrackEntry(dpnId, routerId, externalIps, extGwMacAddress, addOrRemove);
createOutboundTblEntry(dpnId, routerId, externalIps, elanId, extGwMacAddress, addOrRemove);
installNaptPfibFlow(routers, dpnId, externalIps, routerName, addOrRemove);
//Install Inbound NAT entries
Long extNetId = NatUtil.getVpnId(dataBroker, routers.getNetworkId().getValue());
installInboundEntry(dpnId, routerId, extNetId, externalIps, elanId, addOrRemove);
installNaptPfibEntry(dpnId, routerId, addOrRemove);
}
@Override
protected void installSnatSpecificEntriesForNonNaptSwitch(Routers routers, BigInteger dpnId, int addOrRemove) {
// Nothing to to do here.
}
protected void installSnatMissEntryForPrimrySwch(BigInteger dpnId, Long routerId, int elanId, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : installSnatMissEntryForPrimrySwch for for the primary"
+ " NAPT switch dpnId {} ", dpnId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
List<InstructionInfo> instructions = new ArrayList<>();
List<ActionInfo> actionsInfos = new ArrayList<>();
List<NxCtAction> ctActionsList = new ArrayList<>();
NxCtAction nxCtAction = new ActionNxConntrack.NxNat(0, 0, 0,null, null,0, 0);
ctActionsList.add(nxCtAction);
ActionNxConntrack actionNxConntrack = new ActionNxConntrack(0, 0, elanId,
NwConstants.OUTBOUND_NAPT_TABLE,ctActionsList);
actionsInfos.add(actionNxConntrack);
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRef(dpnId, NwConstants.PSNAT_TABLE, routerId);
syncFlow(dpnId, NwConstants.PSNAT_TABLE, flowRef, NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions, addOrRemove);
}
protected void installTerminatingServiceTblEntry(BigInteger dpnId, Long routerId, int elanId, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : creating entry for Terminating Service Table for switch {}, routerId {}",
dpnId, routerId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchTunnelId(BigInteger.valueOf(routerId)));
List<ActionInfo> actionsInfos = new ArrayList<>();
List<NxCtAction> ctActionsList = new ArrayList<>();
NxCtAction nxCtAction = new ActionNxConntrack.NxNat(0, 0, 0,null, null,0, 0);
ctActionsList.add(nxCtAction);
ActionNxConntrack actionNxConntrack = new ActionNxConntrack(0, 0, elanId, NwConstants
.OUTBOUND_NAPT_TABLE,ctActionsList);
ActionNxLoadMetadata actionLoadMeta = new ActionNxLoadMetadata(BigInteger.valueOf(routerId));
actionsInfos.add(actionLoadMeta);
actionsInfos.add(actionNxConntrack);
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRef(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, routerId.longValue());
syncFlow(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, flowRef, NatConstants.DEFAULT_TS_FLOW_PRIORITY, flowRef,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions, addOrRemove);
}
protected void createOutboundTblTrackEntry(BigInteger dpnId, Long routerId,
List<ExternalIps> externalIps, String extGwMacAddress, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : createOutboundTblTrackEntry for switch {}, routerId {}",
dpnId, routerId);
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new NxMatchCtState(snatCtState, snatCtStateMask));
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
if (externalIps.isEmpty()) {
LOG.error("ConntrackBasedSnatService : createOutboundTblTrackEntry no externalIP present for routerId {}",
routerId);
return;
}
//The logic now handle only one external IP per router, others if present will be ignored.
String externalIp = externalIps.get(0).getIpAddress();
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
String routerName = NatUtil.getRouterName(dataBroker, routerId);
if (addOrRemove == NwConstants.ADD_FLOW) {
long extSubnetId = NatUtil.getVpnIdFromExternalSubnet(dataBroker, routerName, externalIp);
if (extSubnetId == NatConstants.INVALID_ID) {
LOG.error("ConntrackBasedSnatService : createOutboundTblTrackEntry : external subnet id is invalid.");
return;
}
ActionNxLoadMetadata actionLoadMeta = new ActionNxLoadMetadata(BigInteger.valueOf(extSubnetId));
listActionInfo.add(actionLoadMeta);
listActionInfo.add(new ActionSetFieldEthernetSource(new MacAddress(extGwMacAddress)));
}
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
listActionInfo.add(new ActionNxResubmit(NwConstants.NAPT_PFIB_TABLE));
instructionInfo.add(new InstructionApplyActions(listActionInfo));
String flowRef = getFlowRef(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId);
flowRef += "trkest";
syncFlow(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, flowRef, NatConstants.SNAT_TRK_FLOW_PRIORITY, flowRef,
NwConstants.COOKIE_SNAT_TABLE, matches, instructionInfo, addOrRemove);
}
protected void createOutboundTblEntry(BigInteger dpnId, long routerId, List<ExternalIps> externalIps,
int elanId, String extGwMacAddress, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : createOutboundTblEntry dpId {} and routerId {}",
dpnId, routerId);
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new NxMatchCtState(trackedNewCtState, trackedNewCtMask));
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
if (externalIps.isEmpty()) {
LOG.error("ConntrackBasedSnatService : createOutboundTblEntry no externalIP present for routerId {}",
routerId);
return;
}
//The logic now handle only one external IP per router, others if present will be ignored.
String externalIp = externalIps.get(0).getIpAddress();
List<ActionInfo> actionsInfos = new ArrayList<>();
String routerName = NatUtil.getRouterName(dataBroker, routerId);
if (addOrRemove == NwConstants.ADD_FLOW) {
long extSubnetId = NatUtil.getVpnIdFromExternalSubnet(dataBroker, routerName, externalIp);
if (extSubnetId == NatConstants.INVALID_ID) {
LOG.error("ConntrackBasedSnatService : createOutboundTblEntry : external subnet id is invalid.");
return;
}
ActionNxLoadMetadata actionLoadMeta = new ActionNxLoadMetadata(BigInteger.valueOf(extSubnetId));
actionsInfos.add(actionLoadMeta);
actionsInfos.add(new ActionSetFieldEthernetSource(new MacAddress(extGwMacAddress)));
}
List<NxCtAction> ctActionsListCommit = new ArrayList<>();
int rangePresent = NxActionNatRangePresent.NXNATRANGEIPV4MIN.getIntValue();
int flags = NxActionNatFlags.NXNATFSRC.getIntValue();
NxCtAction nxCtActionCommit = new ActionNxConntrack.NxNat(0, flags, rangePresent,
new IpPrefixOrAddress(externalIp.toCharArray()).getIpAddress(),
null,0, 0);
ctActionsListCommit.add(nxCtActionCommit);
int ctCommitFlag = 1;
ActionNxConntrack actionNxConntrackSubmit = new ActionNxConntrack(ctCommitFlag, 0, elanId,
NwConstants.NAPT_PFIB_TABLE, ctActionsListCommit);
actionsInfos.add(actionNxConntrackSubmit);
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRef(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId);
syncFlow(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, flowRef, NatConstants.SNAT_NEW_FLOW_PRIORITY,
flowRef, NwConstants.COOKIE_SNAT_TABLE, matches, instructions, addOrRemove);
}
protected void installNaptPfibFlow(Routers routers, BigInteger dpnId, List<ExternalIps> externalIps,
String routerName, int addOrRemove) {
Long extNetId = NatUtil.getVpnId(dataBroker, routers.getNetworkId().getValue());
LOG.info("ConntrackBasedSnatService : buildPostSnatFlowEntity dpId {}, extNetId {}, srcIp {}",
dpnId, extNetId, externalIps);
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
if (addOrRemove == NwConstants.ADD_FLOW) {
//The logic now handle only one external IP per router, others if present will be ignored.
String externalIp = externalIps.get(0).getIpAddress();
long extSubnetId = NatUtil.getVpnIdFromExternalSubnet(dataBroker, routerName, externalIp);
if (extSubnetId == NatConstants.INVALID_ID) {
LOG.error("ConntrackBasedSnatService : installNaptPfibFlow : external subnet id is invalid.");
return;
}
LOG.debug("NAT Service : Calling externalRouterListener installNaptPfibEntry for dpnId {} "
+ "and vpnId {}", dpnId, extSubnetId);
BigInteger subnetMetadata = MetaDataUtil.getVpnIdMetadata(extSubnetId);
matches.add(new MatchMetadata(subnetMetadata, MetaDataUtil.METADATA_MASK_VRFID));
}
if (externalIps.isEmpty()) {
LOG.error("ConntrackBasedSnatService : installNaptPfibExternalOutputFlow no externalIP present for "
+ "routerId {}", routers.getRouterName());
return;
}
//The logic now handle only one external IP per router, others if present will be ignored.
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructions = new ArrayList<>();
listActionInfo.add(new ActionNxLoadInPort(BigInteger.ZERO));
listActionInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
instructions.add(new InstructionApplyActions(listActionInfo));
String flowRef = getFlowRef(dpnId, NwConstants.NAPT_PFIB_TABLE, extNetId);
syncFlow(dpnId, NwConstants.NAPT_PFIB_TABLE, flowRef, NatConstants.SNAT_TRK_FLOW_PRIORITY,
flowRef, NwConstants.COOKIE_SNAT_TABLE, matches, instructions, addOrRemove);
}
protected void installInboundEntry(BigInteger dpnId, long routerId, Long extNetId, List<ExternalIps> externalIps,
int elanId, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : installInboundEntry dpId {} and routerId {}",
dpnId, routerId);
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
if (externalIps.isEmpty()) {
LOG.error("ConntrackBasedSnatService : createOutboundTblEntry no externalIP present for routerId {}",
routerId);
return;
}
String externalIp = externalIps.get(0).getIpAddress();
matches.add(new MatchIpv4Destination(externalIp,"32"));
String routerName = NatUtil.getRouterName(dataBroker, routerId);
if (addOrRemove == NwConstants.ADD_FLOW) {
long extSubnetId = NatUtil.getVpnIdFromExternalSubnet(dataBroker, routerName, externalIp);
if (extSubnetId == NatConstants.INVALID_ID) {
LOG.error("ConntrackBasedSnatService : installInboundEntry : external subnet id is invalid.");
return;
}
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(extSubnetId),
MetaDataUtil.METADATA_MASK_VRFID));
}
List<ActionInfo> actionsInfos = new ArrayList<>();
List<NxCtAction> ctActionsList = new ArrayList<>();
NxCtAction nxCtAction = new ActionNxConntrack.NxNat(0, 0, 0,null, null,0, 0);
ActionNxLoadMetadata actionLoadMeta = new ActionNxLoadMetadata(BigInteger.valueOf(routerId));
actionsInfos.add(actionLoadMeta);
ctActionsList.add(nxCtAction);
ActionNxConntrack actionNxConntrack = new ActionNxConntrack(0, 0, elanId, NwConstants
.NAPT_PFIB_TABLE,ctActionsList);
actionsInfos.add(actionNxConntrack);
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRef(dpnId, NwConstants.INBOUND_NAPT_TABLE, routerId);
syncFlow(dpnId, NwConstants.INBOUND_NAPT_TABLE, flowRef, NatConstants.DEFAULT_TS_FLOW_PRIORITY, flowRef,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions, addOrRemove);
}
protected void installNaptPfibEntry(BigInteger dpnId, long routerId, int addOrRemove) {
LOG.info("ConntrackBasedSnatService : installNaptPfibEntry called for dpnId {} and routerId {} ",
dpnId, routerId);
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new NxMatchCtState(dnatCtState, dnatCtStateMask));
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
listActionInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
instructionInfo.add(new InstructionApplyActions(listActionInfo));
String flowRef = getFlowRef(dpnId, NwConstants.NAPT_PFIB_TABLE, routerId);
syncFlow(dpnId, NwConstants.NAPT_PFIB_TABLE, flowRef, NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef,
NwConstants.COOKIE_SNAT_TABLE, matches, instructionInfo, addOrRemove);
}
}
|
package gov.hhs.fha.nhinc.docquery.entity;
import static org.junit.Assert.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.AdhocQueryType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.IdentifiableType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryObjectListType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryObjectType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryError;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryErrorList;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.gateway.aggregator.document.DocumentConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.orchestration.OutboundDelegate;
import gov.hhs.fha.nhinc.orchestration.OutboundOrchestratableMessage;
import gov.hhs.fha.nhinc.orchestration.OutboundResponseProcessor;
/**
* @author achidamb
*
*/
/* This method tests only AdhocQueryId supplied is not in the defined list and checks the ErrorCode * */
public class OutboundDocQueryProcessorTest {
private static Log log = LogFactory.getLog(OutboundDocQueryProcessorTest.class);
OutboundOrchestratableMessage individual = null;
OutboundOrchestratableMessage cumulative = null;
OutboundDocQueryProcessor processor = new OutboundDocQueryProcessor();
@Test
public void testPartialSuccess() {
assertTrue(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS));
assertTrue(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS));
assertTrue(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS));
}
@Test
public void testNotPartialSuccess() {
assertFalse(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
assertFalse(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
assertFalse(processor.isEitherParitalSuccess(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
}
@Test
public void testAreTheyDifferent() {
assertFalse(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
assertFalse(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
assertFalse(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS));
assertTrue(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
assertTrue(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS));
assertTrue(processor.areTheStatusesDifferent(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
}
@Test
public void testCasesForPartialSuccess() {
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
processor.determineCollectedStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS, null));
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS, processor.determineCollectedStatus(
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS, processor.determineCollectedStatus(
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_PARTIAL_SUCCESS, processor.determineCollectedStatus(
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
}
@Test
public void testCasesForSuccess() {
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
processor.determineCollectedStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS, null));
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS, processor.determineCollectedStatus(
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_SUCCESS));
}
@Test
public void testCasesForFailure() {
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
processor.determineCollectedStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE, null));
assertEquals(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE, processor.determineCollectedStatus(
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE,
DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE));
}
@Test
public void testRegistryCollection() {
AdhocQueryResponse aggregatedResponse = new AdhocQueryResponse();
List<JAXBElement<? extends IdentifiableType>> identifiableList = new ArrayList<JAXBElement<? extends IdentifiableType>>();
RegistryObjectType ro = new RegistryObjectType();
JAXBElement<RegistryObjectType> i = new JAXBElement<RegistryObjectType>(new QName(
"urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, ro);
identifiableList.add(i);
processor.collectRegistryObjectResponses(identifiableList, aggregatedResponse);
assertEquals(1, aggregatedResponse.getRegistryObjectList().getIdentifiable().size());
processor.collectRegistryObjectResponses(identifiableList, aggregatedResponse);
assertEquals(2, aggregatedResponse.getRegistryObjectList().getIdentifiable().size());
identifiableList.add(i);
processor.collectRegistryObjectResponses(identifiableList, aggregatedResponse);
assertEquals(4, aggregatedResponse.getRegistryObjectList().getIdentifiable().size());
}
@Test
public void testAggregateRegistryCollection() {
AdhocQueryResponse aggregatedResponse = new AdhocQueryResponse();
AdhocQueryResponse individualResponse = new AdhocQueryResponse();
processor.aggregateRegistryObjectList(individualResponse, aggregatedResponse);
assertNull(aggregatedResponse.getRegistryObjectList());
RegistryObjectType ro = new RegistryObjectType();
JAXBElement<RegistryObjectType> i = new JAXBElement<RegistryObjectType>(new QName(
"urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, ro);
individualResponse.setRegistryObjectList(new RegistryObjectListType());
individualResponse.getRegistryObjectList().getIdentifiable().add(i);
processor.aggregateRegistryObjectList(individualResponse, aggregatedResponse);
assertEquals(1, aggregatedResponse.getRegistryObjectList().getIdentifiable().size());
}
@Test
public void testProcessNhinResponse() {
OutboundDocQueryProcessor processor = new OutboundDocQueryProcessor() {
@Override
protected OutboundOrchestratableMessage getCumulativeResponseBasedGLEVEL(
OutboundOrchestratableMessage cumulativeResponse, OutboundOrchestratableMessage individual) {
cumulativeResponse = createCumulativeResponse(individual);
return cumulativeResponse;
}
@Override
public OutboundOrchestratableMessage aggregateResponse(OutboundDocQueryOrchestratable individual,
OutboundOrchestratableMessage cumulative) {
OutboundDocQueryOrchestratable_a0 cumulativeResponse = (OutboundDocQueryOrchestratable_a0) createCumulativeResponse(individual);
OutboundDocQueryOrchestratable_a0 individualResponse = (OutboundDocQueryOrchestratable_a0) individualResponse(individual);
try {
aggregateResponse_a0(individualResponse, cumulativeResponse);
cumulativeResponse.setResponse(cumulativeResponse.getCumulativeResponse());
} catch (Exception e) {
log.debug("Error while aggregating");
e.printStackTrace();
}
return cumulativeResponse;
}
};
OutboundDocQueryOrchestratable_a0 response = null;
response = (OutboundDocQueryOrchestratable_a0) processor.processNhinResponse(
individualResponse(getIndividualResponse()), cumulative);
assertSame(NhincConstants.DOC_QUERY_SERVICE_NAME, response.getServiceName());
assertEquals(response.getResponse().getRegistryErrorList().getRegistryError().get(0).getErrorCode(),
"XDSUnknownStoredQuery");
}
private OutboundDocQueryOrchestratable_a0 createCumulativeResponse(OutboundOrchestratableMessage individual) {
AssertionType assertion = new AssertionType();
OutboundDocQueryOrchestratable_a0 cumulativeResponse = new OutboundDocQueryOrchestratable_a0(null, null, null,
null, assertion, NhincConstants.DOC_QUERY_SERVICE_NAME, createNhinTargetSystem(), createCloneRequest());
NhinTargetSystemType target = new NhinTargetSystemType();
HomeCommunityType targetCommunity = new HomeCommunityType();
targetCommunity.setHomeCommunityId("2.2");
target.setHomeCommunity(targetCommunity);
cumulativeResponse.setTarget(createNhinTargetSystem());
cumulativeResponse.setRequest(createCloneRequest());
AdhocQueryResponse newResponse = new AdhocQueryResponse();
newResponse.setStartIndex(BigInteger.ZERO);
newResponse.setTotalResultCount(BigInteger.ZERO);
cumulativeResponse.setCumulativeResponse(newResponse);
return cumulativeResponse;
}
private OutboundDocQueryOrchestratable_a0 individualResponse(OutboundOrchestratableMessage individual) {
AdhocQueryResponse newResponse = new AdhocQueryResponse();
RegistryErrorList regErrList = new RegistryErrorList();
newResponse.setRegistryErrorList(regErrList);
newResponse.setStatus(DocumentConstants.XDS_QUERY_RESPONSE_STATUS_FAILURE);
OutboundDocQueryOrchestratable_a0 individualResponse = (OutboundDocQueryOrchestratable_a0) individual;
RegistryError regErr = new RegistryError();
regErr.setCodeContext("Unknown Stored Query query id" + "9a74-a90016b0af0d");
regErr.setErrorCode("XDSUnknownStoredQuery");
regErr.setSeverity(NhincConstants.XDS_REGISTRY_ERROR_SEVERITY_ERROR);
regErrList.getRegistryError().add(regErr);
individualResponse.setResponse(newResponse);
return individualResponse;
}
private OutboundOrchestratableMessage getIndividualResponse() {
AssertionType assertion = new AssertionType();
OutboundDelegate nd = new OutboundDocQueryDelegate();
OutboundResponseProcessor np = null;
OutboundDocQueryOrchestratable_a0 individualResp = new OutboundDocQueryOrchestratable_a0(nd, np, null, null,
assertion, NhincConstants.DOC_QUERY_SERVICE_NAME, createNhinTargetSystem(), createCloneRequest());
return individualResp;
}
private AdhocQueryRequest createCloneRequest() {
AdhocQueryRequest clonedRequest = new AdhocQueryRequest();
AdhocQueryType adhocQuery = new AdhocQueryType();
clonedRequest.setAdhocQuery(adhocQuery);
adhocQuery.setHome("urn:oid:2.2");
SlotType1 patientIdSlot = new SlotType1();
adhocQuery.getSlot().add(patientIdSlot);
patientIdSlot.setName("$XDSDocumentEntryPatientId");
ValueListType valueList = new ValueListType();
patientIdSlot.setValueList(valueList);
valueList.getValue().add("'500000000^^^&1.1&ISO'");
clonedRequest.setAdhocQuery(adhocQuery);
return clonedRequest;
}
private NhinTargetSystemType createNhinTargetSystem() {
NhinTargetSystemType target = new NhinTargetSystemType();
HomeCommunityType targetCommunity = new HomeCommunityType();
targetCommunity.setHomeCommunityId("2.2");
target.setHomeCommunity(targetCommunity);
return target;
}
}
|
package ru.liahim.saltmod.common;
import java.io.File;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.IIcon;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import ru.liahim.saltmod.SaltMod;
import ru.liahim.saltmod.api.ExtractRegistry;
import ru.liahim.saltmod.client.ClientProxy;
import ru.liahim.saltmod.extractor.ExtractorButtonMessage;
import ru.liahim.saltmod.extractor.GuiExtractorHandler;
import ru.liahim.saltmod.extractor.TileEntityExtractor;
import ru.liahim.saltmod.item.SaltFood;
import ru.liahim.saltmod.world.SaltCrystalGenerator;
import ru.liahim.saltmod.world.SaltLakeGenerator;
import ru.liahim.saltmod.world.SaltOreGenerator;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class CommonProxy {
public static CreativeTabs saltTab = new SaltTab("saltTab");
public static SaltOreGenerator saltOreGenerator = new SaltOreGenerator();
public static SaltCrystalGenerator saltCrystalGenerator = new SaltCrystalGenerator();
public static SaltLakeGenerator saltLakeGenerator = new SaltLakeGenerator();
public static int saltOreFrequency;
public static int saltOreSize;
public static int saltLakeGroupRarity;
public static int saltLakeQuantity;
public static int saltLakeDistance;
public static int saltLakeRadius;
public static int saltCrystalGrowSpeed;
public static int saltWortGrowSpeed;
public static boolean mudArmorWaterDam;
public static int mudRegenSpeed;
public static int extractorVolume;
public static int TFDim;
public static boolean TFOreGen;
public static Item saltVenisonCooked = new SaltFood("saltVenisonCooked", 9, 9.0F).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltVenisonCooked");
public static Item saltMeefSteak = new SaltFood("saltMeefSteak", 7, 7.0F).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltMeefSteak");
public static Item saltMeefStroganoff = new SaltFood("saltMeefStroganoff", 9, 1.0F, Items.bowl).setMaxStackSize(1).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltMeefStroganoff");
public static Item saltHydraChop = new SaltFood("saltHydraChop", 19, 20.0F).setPotionEffect(10, 5, 0, 1.0F).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltHydraChop");
public static Item pickledMushgloom = new SaltFood("pickledMushgloom", 4, 4.8F, Items.glass_bottle, new PotionEffect(Potion.nightVision.id, 1200, 0), new PotionEffect(Potion.moveSlowdown.id, 100, 0)).setAlwaysEdible().setMaxStackSize(1).setCreativeTab(saltTab).setTextureName("saltmod:TF_PickledMushgloom");
public static Item saltWortVenison = new SaltFood("saltWortVenison", 10, 9.2F, Items.bowl, new PotionEffect(Potion.regeneration.id, 100, 0)).setMaxStackSize(1).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltWortVenison");
public static Item saltWortMeefSteak = new SaltFood("saltWortMeefSteak", 8, 7.2F, Items.bowl, new PotionEffect(Potion.regeneration.id, 100, 0)).setMaxStackSize(1).setCreativeTab(saltTab).setTextureName("saltmod:TF_SaltWortMeefSteak");
public static ArmorMaterial mudMaterial = EnumHelper.addArmorMaterial("mudMaterial", 4, new int[] {1, 1, 1, 1}, 15);
//Milk
@SideOnly(Side.CLIENT)
public static IIcon milkIcon;
public static Fluid milk;
public static SimpleNetworkWrapper network;
public void preInit(FMLPreInitializationEvent event)
{
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
saltOreFrequency = config.getInt("SaltOreFrequency", "World", 4, 1, 10, "Salt ore frequency");
saltOreSize = config.getInt("SaltOreSize", "World", 5, 1, 10, "Salt ore size");
saltLakeGroupRarity = config.getInt("SaltLakeGroupRarity", "World", 500, 1, 1000, "Rarity of the salt lake groups");
saltLakeQuantity = config.getInt("SaltLakeQuantity", "World", 5, 1, 10, "The maximum quantity of the salt lakes in the salt lake groups");
saltLakeDistance = config.getInt("SaltLakeDistance", "World", 30, 10, 50, "The maximum distance between the salt lakes in the salt lake groups");
saltLakeRadius = config.getInt("SaltLakeRadius", "World", 20, 5, 50, "The maximum radius of the salt lake");
saltCrystalGrowSpeed = config.getInt("SaltCrystalGrowRate", "Farm", 14, 1, 20, "The salt crystals growth rate (1 - fastly, 20 - slowly)");
saltWortGrowSpeed = config.getInt("SaltWortGrowRate", "Farm", 7, 1, 20, "The saltwort growth rate (1 - fastly, 20 - slowly)");
extractorVolume = config.getInt("SaltExtractorVolume", "Extractor", 1, 1, 3, "The number of buckets in the salt extractor");
mudArmorWaterDam = config.getBoolean("MudArmorWaterDamage", "Armor", true, "Mud Armor water damage");
mudRegenSpeed = config.getInt("MudRegenSpeed", "Armor", 100, 10, 100, "Speed of Mud Armor & Block regeneration effect (10 - fastly, 100 - slowly)");
TFOreGen = config.getBoolean("TFOreGen", "TwilightForest", true, "Salt ore generation in the Twilight Forest dimention");
config.save();
SaltModEvent sEvent = new SaltModEvent();
FMLCommonHandler.instance().bus().register(sEvent);
MinecraftForge.EVENT_BUS.register(sEvent);
NetworkRegistry.INSTANCE.registerGuiHandler(SaltMod.instance, new GuiExtractorHandler());
network = NetworkRegistry.INSTANCE.newSimpleChannel("ExtractorChannel");
network.registerMessage(ExtractorButtonMessage.Handler.class, ExtractorButtonMessage.class, 0, Side.SERVER);
}
public void init(FMLInitializationEvent event)
{
ModItems.init();
ModBlocks.init();
AchievSalt.init();
Configuration configTF = new Configuration(new File("./config", "TwilightForest.cfg"));
configTF.load();
TFDim = configTF.get("dimension", "dimensionID", 7).getInt();
ClientProxy.setCustomRenderers();
GameRegistry.registerTileEntity(TileEntityExtractor.class, "tileEntityExtractor");
GameRegistry.registerWorldGenerator(saltOreGenerator, 0);
GameRegistry.registerWorldGenerator(saltCrystalGenerator, 10);
GameRegistry.registerWorldGenerator(saltLakeGenerator, 15);
//Recipe
ExtractRegistry.instance().addExtracting(FluidRegistry.WATER, ModItems.saltPinch, 1000, 0.0F);
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 9), new ItemStack(ModItems.salt));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 6));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 7));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 8));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 9));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltLamp));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBrickStair));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch), new ItemStack(ModBlocks.saltCrystal));
GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.saltDirt), new ItemStack(ModItems.salt), new ItemStack(Blocks.dirt));
GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.saltDirt), new ItemStack(ModBlocks.saltDirtLite), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(Items.dye, 1, 2), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fizzyDrink), new ItemStack(ModItems.soda), new ItemStack(Items.potionitem));
GameRegistry.addShapelessRecipe(new ItemStack(Items.potionitem), new ItemStack(Items.glass_bottle), new ItemStack(Items.snowball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud), new ItemStack(ModItems.soda), new ItemStack(ModItems.salt), new ItemStack(Items.coal), new ItemStack(Items.clay_ball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud), new ItemStack(ModItems.soda), new ItemStack(ModItems.salt), new ItemStack(Items.coal, 1, 1), new ItemStack(Items.clay_ball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud, 4), new ItemStack(ModBlocks.mudBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltBeefCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_beef));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPorkchopCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_porkchop));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoBaked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.baked_potato));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltChickenCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_chicken));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishCod), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishCodCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_fished));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmon), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_fished, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishClownfish), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltMushroomStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.mushroom_stew));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltMushroomStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltBread), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bread));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltEgg), new ItemStack(ModItems.saltPinch), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pumpkinPorridge), new ItemStack(Items.bowl), new ItemStack(Blocks.pumpkin));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.vegetableStew), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.vegetableStew), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.vegetableStew));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoMushroom), new ItemStack(Items.bowl), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoMushroom), new ItemStack(Items.bowl), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(ModItems.potatoMushroom), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(ModItems.potatoMushroom), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSoup), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSoup), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSoup), new ItemStack(ModItems.fishSoup), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSalmonSoup), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonSoup), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonSoup), new ItemStack(ModItems.fishSalmonSoup), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortBeef), new ItemStack(Items.bowl), new ItemStack(Items.cooked_beef), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortPorkchop), new ItemStack(Items.bowl), new ItemStack(Items.cooked_porkchop), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.dandelionSalad), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.yellow_flower), new ItemStack(Blocks.red_flower, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltDandelionSalad), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.yellow_flower), new ItemStack(Blocks.red_flower, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltDandelionSalad), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.dandelionSalad));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.wheatSprouts), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWheatSprouts), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWheatSprouts), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.wheatSprouts));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fruitSalad), new ItemStack(Items.bowl), new ItemStack(Items.apple), new ItemStack(Items.carrot), new ItemStack(Items.melon));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.gratedCarrot), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.carrot), new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.carrotPie), new ItemStack(Items.carrot), new ItemStack(Items.carrot), new ItemStack(Items.sugar), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.applePie), new ItemStack(Items.apple), new ItemStack(Items.apple), new ItemStack(Items.sugar), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.onionPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.red_flower, 1, 2), new ItemStack(Blocks.red_flower, 1, 2), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.wheat), new ItemStack(Items.fish), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSalmonPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.wheat), new ItemStack(Items.fish, 1, 1), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledFern), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.tallgrass, 1, 2), new ItemStack(Blocks.tallgrass, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortPie), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.wheat), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortSalad), new ItemStack(Items.bowl), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fermentedSaltWort), new ItemStack(Items.glass_bottle), new ItemStack(Items.ghast_tear), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.muffin), new ItemStack(ModItems.soda), new ItemStack(Items.egg), new ItemStack(Items.wheat), new ItemStack(Items.dye, 1, 3));
GameRegistry.addShapelessRecipe(new ItemStack(Items.milk_bucket), new ItemStack(ModItems.powderedMilk), new ItemStack(Items.water_bucket), new ItemStack(Items.bucket));
GameRegistry.addRecipe(new ItemStack(ModItems.salt), "xxx", "xxx", "xxx", 'x', ModItems.saltPinch);
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock), "xxx", "xxx", "xxx", 'x', ModItems.salt);
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltLamp), "x", "y", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0), 'y', new ItemStack(Blocks.torch));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 4, 5), "xx", "xx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 2, 2), "x", "x", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 1), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 8), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 1));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 9), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 2));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBrickStair, 6), " x", " xx", "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 0), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 1), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 2), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 2));
GameRegistry.addRecipe(new ItemStack(ModItems.cornedBeef), "xxx", "xyx", "xxx", 'x', ModItems.saltPinch, 'y', Items.rotten_flesh);
GameRegistry.addRecipe(new ItemStack(ModBlocks.mudBlock), "xx", "xx", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudHelmet), "xxx", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudChestplate), "x x", "xxx", "xxx", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudLeggings), "xxx", "x x", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudBoots), "x x", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModBlocks.extractor), "xyx", "x x", "xxx", 'x', Blocks.cobblestone, 'y', Items.cauldron);
GameRegistry.addSmelting(ModBlocks.saltOre, new ItemStack(ModItems.salt, 1), 0.7F);
GameRegistry.addSmelting(ModBlocks.saltLake, new ItemStack(ModItems.salt, 1), 0.7F);
GameRegistry.addSmelting(new ItemStack(ModBlocks.saltBlock, 1, 0), new ItemStack(ModBlocks.saltBlock, 1, 6), 0.0F);
GameRegistry.addSmelting(new ItemStack(ModBlocks.saltBlock, 1, 5), new ItemStack(ModBlocks.saltBlock, 1, 7), 0.0F);
GameRegistry.addSmelting(ModItems.saltWortSeed, new ItemStack(ModItems.soda, 1), 0.0F);
//Chest Content
ChestGenHooks.addItem(ChestGenHooks.BONUS_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 3, 3));
ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CORRIDOR, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CROSSING, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.MINESHAFT_CORRIDOR, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 10));
ChestGenHooks.addItem(ChestGenHooks.VILLAGE_BLACKSMITH, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 10));
ChestGenHooks.addItem(ChestGenHooks.PYRAMID_DESERT_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 3, 3));
ChestGenHooks.addItem(ChestGenHooks.PYRAMID_JUNGLE_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 5, 5));
//OreDictionary
OreDictionary.registerOre("oreSalt", ModBlocks.saltOre);
OreDictionary.registerOre("blockSalt", ModBlocks.saltBlock);
OreDictionary.registerOre("blockSaltCrystal", ModBlocks.saltCrystal);
OreDictionary.registerOre("lumpSalt", ModItems.salt);
OreDictionary.registerOre("dustSalt", ModItems.saltPinch);
OreDictionary.registerOre("dustSoda", ModItems.soda);
OreDictionary.registerOre("dustMilk", ModItems.powderedMilk);
OreDictionary.registerOre("cropSaltwort", ModItems.saltWortSeed);
OreDictionary.registerOre("materialMineralMud", ModItems.mineralMud);
}
public void postInit(FMLPostInitializationEvent event)
{
//TF Items & Recipe
Item venisonCooked = GameRegistry.findItem("TwilightForest", "item.venisonCooked");
if (venisonCooked != null){
GameRegistry.registerItem(saltVenisonCooked, "saltVenisonCooked");
GameRegistry.registerItem(saltWortVenison, "saltWortVenison");
GameRegistry.addShapelessRecipe(new ItemStack(saltVenisonCooked),
new Object[] {new ItemStack(ModItems.saltPinch), new ItemStack(venisonCooked)});
GameRegistry.addShapelessRecipe(new ItemStack(saltWortVenison),
new Object[] {new ItemStack(venisonCooked), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.bowl)});}
Item meefSteak = GameRegistry.findItem("TwilightForest", "item.meefSteak");
if (meefSteak != null){
GameRegistry.registerItem(saltMeefSteak, "saltMeefSteak");
GameRegistry.registerItem(saltWortMeefSteak, "saltWortMeefSteak");
GameRegistry.addShapelessRecipe(new ItemStack(saltMeefSteak),
new Object[] {new ItemStack(ModItems.saltPinch), new ItemStack(meefSteak)});
GameRegistry.addShapelessRecipe(new ItemStack(saltWortVenison),
new Object[] {new ItemStack(meefSteak), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.bowl)});}
Item meefStroganoff = GameRegistry.findItem("TwilightForest", "item.meefStroganoff");
if (meefStroganoff != null){
GameRegistry.registerItem(saltMeefStroganoff, "saltMeefStroganoff");
GameRegistry.addShapelessRecipe(new ItemStack(saltMeefStroganoff),
new Object[] {new ItemStack(ModItems.saltPinch), new ItemStack(meefStroganoff)});}
Item hydraChop = GameRegistry.findItem("TwilightForest", "item.hydraChop");
if (hydraChop != null){
GameRegistry.registerItem(saltHydraChop, "saltHydraChop");
GameRegistry.addShapelessRecipe(new ItemStack(saltHydraChop),
new Object[] {new ItemStack(ModItems.saltPinch), new ItemStack(hydraChop)});}
Block mushgloom = GameRegistry.findBlock("TwilightForest", "tile.TFPlant");
if (mushgloom != null){
GameRegistry.registerItem(pickledMushgloom, "pickledMushgloom");
GameRegistry.addShapelessRecipe(new ItemStack(pickledMushgloom),
new Object[] {new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(mushgloom, 1, 9), new ItemStack(mushgloom, 1, 9)});}
//Milk Registry
if (FluidRegistry.isFluidRegistered("milk"))
{
Fluid milk = FluidRegistry.getFluid("milk");
ExtractRegistry.instance().addExtracting(milk, ModItems.powderedMilk, 1000, 0.0F);
}
else
{
milk = new Fluid("milk");
FluidRegistry.registerFluid(milk);
FluidContainerRegistry.registerFluidContainer(new FluidStack(milk, FluidContainerRegistry.BUCKET_VOLUME), new ItemStack(Items.milk_bucket), FluidContainerRegistry.EMPTY_BUCKET);
ExtractRegistry.instance().addExtracting(milk, ModItems.powderedMilk, 1000, 0.0F);
}
}
}
|
package org.ccnx.ccn.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.CCNFileInputStream;
import org.ccnx.ccn.io.CCNInputStream;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* A command-line utility for pulling files out of ccnd or a repository.
* Note class name needs to match command name to work with ccn_run
*/
public class ccngetfile implements Usage {
static Usage u = new ccngetfile();
/**
* @param args
*/
public static void main(String[] args) {
Log.setDefaultLevel(Level.WARNING);
for (int i = 0; i < args.length - 2; i++) {
if (!CommonArguments.parseArguments(args, i, u)) {
u.usage();
System.exit(1);
}
if (CommonParameters.startArg > (i + 1))
i = CommonParameters.startArg - 1;
}
if (args.length < CommonParameters.startArg + 2) {
u.usage();
System.exit(1);
}
try {
int readsize = 1024; // make an argument for testing...
// If we get one file name, put as the specific name given.
// If we get more than one, put underneath the first as parent.
// Ideally want to use newVersion to get latest version. Start
// with random version.
ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]);
CCNHandle handle = CCNHandle.open();
File theFile = new File(args[CommonParameters.startArg + 1]);
if (theFile.exists()) {
System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]);
}
FileOutputStream output = new FileOutputStream(theFile);
long starttime = System.currentTimeMillis();
CCNInputStream input;
if (CommonParameters.unversioned)
input = new CCNInputStream(argName, handle);
else
input = new CCNFileInputStream(argName, handle);
if (CommonParameters.timeout != null) {
input.setTimeout(CommonParameters.timeout);
}
byte [] buffer = new byte[readsize];
int readcount = 0;
long readtotal = 0;
//while (!input.eof()) {
while ((readcount = input.read(buffer)) != -1){
//readcount = input.read(buffer);
readtotal += readcount;
output.write(buffer, 0, readcount);
output.flush();
}
if (CommonParameters.verbose)
System.out.println("ccngetfile took: "+(System.currentTimeMillis() - starttime)+"ms");
System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes.");
System.exit(0);
} catch (ConfigurationException e) {
System.out.println("Configuration exception in ccngetfile: " + e.getMessage());
e.printStackTrace();
} catch (MalformedContentNameStringException e) {
System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("Cannot write file or read content. " + e.getMessage());
e.printStackTrace();
}
System.exit(1);
}
public void usage() {
System.out.println("usage: ccngetfile [-unversioned] [-timeout millis] [-as pathToKeystore] [-ac (access control)] <ccnname> <filename>");
}
}
|
package de.sb.messenger.persistence;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.validation.constraints.Size;
@Entity
@Table(name = "Message")
@DiscriminatorValue(value = "Message")
@PrimaryKeyJoinColumn(name="identity")
public class Message extends BaseEntity {
@ManyToOne
@JoinColumn(name="identity")
private Person author;
@ManyToOne
@JoinColumn(name="identity")
private BaseEntity subject;
@Column(name = "body")
@Size(min = 1, max = 4093)
private String body;
public Message(Person author, BaseEntity subject, String body) {
this.author = author;
this.subject = subject;
this.body = body;
}
protected Message() {
this.author = null;
this.subject = null;
this.body = null;
}
public Person getAuthor() {
return author;
}
public BaseEntity getSubject() {
return subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public BaseEntity getSubjectReference() {
return this.subject;
}
}
|
package dr.app.checkpoint;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.tree.TreeParameterModel;
import dr.inference.markovchain.MarkovChain;
import dr.inference.markovchain.MarkovChainListener;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.operators.AdaptableMCMCOperator;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.OperatorSchedule;
import dr.inference.state.*;
import dr.math.MathUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* A state loader / saver
* @author Andrew Rambaut
* @author Guy Baele
*/
public class BeastCheckpointer implements StateLoaderSaver {
private static final boolean DEBUG = false;
// A debugging flag to do a check that the state gives the same likelihood after loading
private static final boolean CHECK_LOAD_STATE = true;
public final static String LOAD_STATE_FILE = "load.state.file";
public final static String SAVE_STATE_FILE = "save.state.file";
public final static String SAVE_STATE_AT = "save.state.at";
public final static String SAVE_STATE_EVERY = "save.state.every";
public final static String SAVE_STEM = "save.state.stem";
public final static String FORCE_RESUME = "force.resume";
public final static String CHECKPOINT_SEED = "checkpoint.seed";
private final String loadStateFileName;
private final String saveStateFileName;
private final String stemFileName;
private boolean forceResume = false;
public BeastCheckpointer() {
loadStateFileName = System.getProperty(LOAD_STATE_FILE, null);
saveStateFileName = System.getProperty(SAVE_STATE_FILE, null);
stemFileName = System.getProperty(SAVE_STEM, null);
final List<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
if (System.getProperty(SAVE_STATE_AT) != null) {
final long saveStateAt = Long.parseLong(System.getProperty(SAVE_STATE_AT));
listeners.add(new StateSaverChainListener(BeastCheckpointer.this, saveStateAt,false));
}
if (System.getProperty(SAVE_STATE_EVERY) != null) {
final long saveStateEvery = Long.parseLong(System.getProperty(SAVE_STATE_EVERY));
listeners.add(new StateSaverChainListener(BeastCheckpointer.this, saveStateEvery,true));
}
Factory.INSTANCE = new Factory() {
@Override
public StateLoader getInitialStateLoader() {
if (loadStateFileName == null) {
return null;
} else {
return getStateLoaderObject();
}
}
@Override
public MarkovChainListener[] getStateSaverChainListeners() {
return listeners.toArray(new MarkovChainListener[0]);
}
@Override
public StateLoaderSaver getStateLoaderSaver(final File loadFile, final File saveFile) {
return new StateLoaderSaver() {
@Override
public boolean saveState(MarkovChain markovChain, long state, double lnL) {
return BeastCheckpointer.this.writeStateToFile(saveFile, state, lnL, markovChain);
}
@Override
public long loadState(MarkovChain markovChain, double[] savedLnL) {
return BeastCheckpointer.this.readStateFromFile(loadFile, markovChain, savedLnL);
}
@Override
public void checkLoadState(double savedLnL, double lnL) {
// do nothing.
}
};
}
};
}
private BeastCheckpointer getStateLoaderObject() {
return this;
}
@Override
public boolean saveState(MarkovChain markovChain, long state, double lnL) {
String fileName = "";
if (stemFileName != null) {
fileName = stemFileName + "_" + state;
} else {
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(Calendar.getInstance().getTime());
fileName = (this.saveStateFileName != null ? this.saveStateFileName : "beast_state_" + timeStamp);
}
return writeStateToFile(new File(fileName), state, lnL, markovChain);
}
@Override
public long loadState(MarkovChain markovChain, double[] savedLnL) {
return readStateFromFile(new File(loadStateFileName), markovChain, savedLnL);
}
@Override
public void checkLoadState(double savedLnL, double lnL) {
if (CHECK_LOAD_STATE) {
if (System.getProperty(FORCE_RESUME) != null) {
forceResume = Boolean.parseBoolean(System.getProperty(FORCE_RESUME));
//System.out.println("FORCE_RESUME? " + System.getProperty(FORCE_RESUME) + " (" + forceResume + "");
}
//first perform a simple check for equality of two doubles
//when this test fails, go over the digits
if (forceResume) {
System.out.println("Forcing analysis to resume regardless of recomputed likelihood values (" + lnL + " vs. " + savedLnL + ").");
} else if (lnL != savedLnL) {
System.out.println("COMPARING LIKELIHOODS: " + lnL + " vs. " + savedLnL);
//15 is the floor value for the number of decimal digits when representing a double
//checking for 15 identical digits below
String originalString = Double.toString(savedLnL);
String restoredString = Double.toString(lnL);
System.out.println(lnL + " " + originalString);
System.out.println(savedLnL + " " + restoredString);
//assume values will be nearly identical
int digits = 0;
for (int i = 0; i < Math.min(originalString.length(), restoredString.length()); i++) {
if (originalString.charAt(i) == restoredString.charAt(i)) {
if (!(originalString.charAt(i) == '-' || originalString.charAt(i) == '.')) {
digits++;
}
} else {
break;
}
}
//System.err.println("digits = " + digits);
//the translation table is constructed upon loading the initial tree for the analysis
//if that tree is user-defined or a UPGMA starting tree, the starting seed won't matter
//if that tree is constructed at random, we currently don't provide a way to retrieve the original translation table
if (digits < 15) {
//currently use the general BEAST -threshold argument
//TODO Evaluate whether a checkpoint-specific threshold option is required or useful
double threshold = 0.0;
if (System.getProperty("mcmc.evaluation.threshold") != null) {
threshold = Double.parseDouble(System.getProperty("mcmc.evaluation.threshold"));
}
if (Math.abs(lnL - savedLnL) > threshold) {
throw new RuntimeException("Saved lnL does not match recomputed value for loaded state: stored lnL: " + savedLnL +
", recomputed lnL: " + lnL + " (difference " + (savedLnL - lnL) + ")." +
"\nYour XML may require the construction of a randomly generated starting tree. " +
"Try resuming the analysis by using the same starting seed as for the original BEAST run.");
} else {
System.out.println("Saved lnL does not match recomputed value for loaded state: stored lnL: " + savedLnL +
", recomputed lnL: " + lnL + " (difference " + (savedLnL - lnL) + ")." +
"\nThreshold of " + threshold + " for restarting analysis not exceeded; continuing ...");
}
}
} else {
System.out.println("IDENTICAL LIKELIHOODS");
System.out.println("lnL" + " = " + lnL);
System.out.println("savedLnL[0]" + " = " + savedLnL);
}
}
}
protected boolean writeStateToFile(File file, long state, double lnL, MarkovChain markovChain) {
OperatorSchedule operatorSchedule = markovChain.getSchedule();
OutputStream fileOut = null;
try {
fileOut = new FileOutputStream(file);
PrintStream out = new PrintStream(fileOut);
ArrayList<TreeParameterModel> traitModels = new ArrayList<TreeParameterModel>();
int[] rngState = MathUtils.getRandomState();
out.print("rng");
for (int i = 0; i < rngState.length; i++) {
out.print("\t");
out.print(rngState[i]);
}
out.println();
out.print("state\t");
out.println(state);
out.print("lnL\t");
out.println(lnL);
for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
if (!parameter.isImmutable()) {
out.print("parameter");
out.print("\t");
out.print(parameter.getParameterName());
out.print("\t");
out.print(parameter.getDimension());
for (int dim = 0; dim < parameter.getDimension(); dim++) {
out.print("\t");
out.print(parameter.getParameterUntransformedValue(dim));
}
}
out.print("\n");
}
for (int i = 0; i < operatorSchedule.getOperatorCount(); i++) {
MCMCOperator operator = operatorSchedule.getOperator(i);
out.print("operator");
out.print("\t");
out.print(operator.getOperatorName());
out.print("\t");
out.print(operator.getAcceptCount());
out.print("\t");
out.print(operator.getRejectCount());
if (operator instanceof AdaptableMCMCOperator) {
out.print("\t");
out.print(((AdaptableMCMCOperator)operator).getAdaptableParameter());
out.print("\t");
out.print(((AdaptableMCMCOperator)operator).getAdaptationCount());
}
out.println();
}
//check up front if there are any TreeParameterModel objects
for (Model model : Model.CONNECTED_MODEL_SET) {
if (model instanceof TreeParameterModel) {
//System.out.println("\nDetected TreeParameterModel: " + ((TreeParameterModel) model).toString());
traitModels.add((TreeParameterModel) model);
}
}
for (Model model : Model.CONNECTED_MODEL_SET) {
if (model instanceof TreeModel) {
out.print("tree");
out.print("\t");
out.println(model.getModelName());
//replace Newick format by printing general graph structure
//out.println(((TreeModel) model).getNewick());
out.println("#node height taxon");
int nodeCount = ((TreeModel) model).getNodeCount();
out.println(nodeCount);
for (int i = 0; i < nodeCount; i++) {
out.print(((TreeModel) model).getNode(i).getNumber());
out.print("\t");
out.print(((TreeModel) model).getNodeHeight(((TreeModel) model).getNode(i)));
if (((TreeModel) model).isExternal(((TreeModel) model).getNode(i))) {
out.print("\t");
out.print(((TreeModel) model).getNodeTaxon(((TreeModel) model).getNode(i)).getId());
}
out.println();
}
out.println("#edges");
out.println("#child-node parent-node L/R-child traits");
out.println(nodeCount);
for (int i = 0; i < nodeCount; i++) {
NodeRef parent = ((TreeModel) model).getParent(((TreeModel) model).getNode(i));
if (parent != null) {
out.print(((TreeModel) model).getNode(i).getNumber());
out.print("\t");
out.print(((TreeModel) model).getParent(((TreeModel) model).getNode(i)).getNumber());
out.print("\t");
if ((((TreeModel) model).getChild(parent, 0) == ((TreeModel) model).getNode(i))) {
//left child
out.print(0);
} else if ((((TreeModel) model).getChild(parent, 1) == ((TreeModel) model).getNode(i))) {
//right child
out.print(1);
} else {
throw new RuntimeException("Operation currently only supported for nodes with 2 children.");
}
//only print the TreeParameterModel that matches the TreeModel currently being written
for (TreeParameterModel tpm : traitModels) {
if (model == tpm.getTreeModel()) {
out.print("\t");
out.print(tpm.getNodeValue((TreeModel) model, ((TreeModel) model).getNode(i)));
}
}
out.println();
} else {
if (DEBUG) {
System.out.println(((TreeModel) model).getNode(i) + " has no parent.");
}
}
}
}
}
out.close();
fileOut.close();
} catch (IOException ioe) {
System.err.println("Unable to write file: " + ioe.getMessage());
return false;
}
if (DEBUG) {
for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
System.err.println(likelihood.getId() + ": " + likelihood.getLogLikelihood());
}
}
return true;
}
protected long readStateFromFile(File file, MarkovChain markovChain, double[] lnL) {
OperatorSchedule operatorSchedule = markovChain.getSchedule();
long state = -1;
ArrayList<TreeParameterModel> traitModels = new ArrayList<TreeParameterModel>();
try {
FileReader fileIn = new FileReader(file);
BufferedReader in = new BufferedReader(fileIn);
int[] rngState = null;
String line = in.readLine();
String[] fields = line.split("\t");
if (fields[0].equals("rng")) {
// if there is a random number generator state present then load it...
try {
rngState = new int[fields.length - 1];
for (int i = 0; i < rngState.length; i++) {
rngState[i] = Integer.parseInt(fields[i + 1]);
}
} catch (NumberFormatException nfe) {
throw new RuntimeException("Unable to read state number from state file");
}
line = in.readLine();
fields = line.split("\t");
}
try {
if (!fields[0].equals("state")) {
throw new RuntimeException("Unable to read state number from state file");
}
state = Long.parseLong(fields[1]);
} catch (NumberFormatException nfe) {
throw new RuntimeException("Unable to read state number from state file");
}
line = in.readLine();
fields = line.split("\t");
try {
if (!fields[0].equals("lnL")) {
throw new RuntimeException("Unable to read lnL from state file");
}
if (lnL != null) {
lnL[0] = Double.parseDouble(fields[1]);
}
} catch (NumberFormatException nfe) {
throw new RuntimeException("Unable to read lnL from state file");
}
for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
line = in.readLine();
fields = line.split("\t");
//if (!fields[0].equals(parameter.getParameterName())) {
// System.err.println("Unable to match state parameter: " + fields[0] + ", expecting " + parameter.getParameterName());
int dimension = Integer.parseInt(fields[2]);
if (dimension != parameter.getDimension()) {
System.err.println("Unable to match state parameter dimension: " + dimension + ", expecting " + parameter.getDimension() + " for parameter: " + parameter.getParameterName());
System.err.print("Read from file: ");
for (int i = 0; i < fields.length; i++) {
System.err.print(fields[i] + "\t");
}
System.err.println();
}
if (fields[1].equals("branchRates.categories.rootNodeNumber")) {
// System.out.println("eek");
double value = Double.parseDouble(fields[3]);
parameter.setParameterValue(0, value);
if (DEBUG) {
System.out.println("restoring " + fields[1] + " with value " + value);
}
} else {
if (DEBUG) {
System.out.print("restoring " + fields[1] + " with values ");
}
for (int dim = 0; dim < parameter.getDimension(); dim++) {
try {
parameter.setParameterUntransformedValue(dim, Double.parseDouble(fields[dim + 3]));
} catch (RuntimeException rte) {
System.err.println(rte);
continue;
}
if (DEBUG) {
System.out.print(Double.parseDouble(fields[dim + 3]) + " ");
}
}
if (DEBUG) {
System.out.println();
}
}
}
for (int i = 0; i < operatorSchedule.getOperatorCount(); i++) {
//TODO we can no longer assume these are in the right order
//TODO best parse all the "operator" lines and store them so we can mix and match within this for loop
//TODO does not only apply to the operators but also to the parameters
//TODO test using additional tip-date sampling compared to previous run
MCMCOperator operator = operatorSchedule.getOperator(i);
line = in.readLine();
fields = line.split("\t");
if (!fields[1].equals(operator.getOperatorName())) {
throw new RuntimeException("Unable to match " + operator.getOperatorName() + " operator: " + fields[1]);
}
if (fields.length < 4) {
throw new RuntimeException("Operator missing values: " + fields[1]);
}
operator.setAcceptCount(Integer.parseInt(fields[2]));
operator.setRejectCount(Integer.parseInt(fields[3]));
if (operator instanceof AdaptableMCMCOperator) {
if (fields.length != 6) {
throw new RuntimeException("Coercable operator missing parameter: " + fields[1]);
}
((AdaptableMCMCOperator)operator).setAdaptableParameter(Double.parseDouble(fields[4]));
((AdaptableMCMCOperator)operator).setAdaptationCount(Long.parseLong(fields[5]));
}
}
// load the tree models last as we get the node heights from the tree (not the parameters which
// which may not be associated with the right node
Set<String> expectedTreeModelNames = new HashSet<String>();
//store list of TreeModels for debugging purposes
ArrayList<TreeModel> treeModelList = new ArrayList<TreeModel>();
for (Model model : Model.CONNECTED_MODEL_SET) {
if (model instanceof TreeModel) {
if (DEBUG) {
System.out.println("model " + model.getModelName());
}
treeModelList.add((TreeModel)model);
expectedTreeModelNames.add(model.getModelName());
if (DEBUG) {
System.out.println("\nexpectedTreeModelNames:");
for (String s : expectedTreeModelNames) {
System.out.println(s);
}
System.out.println();
}
}
//first add all TreeParameterModels to a list
if (model instanceof TreeParameterModel) {
traitModels.add((TreeParameterModel)model);
}
}
//explicitly link TreeModel (using its unique ID) to a list of TreeParameterModels
//this information is currently not yet used
HashMap<String, ArrayList<TreeParameterModel>> linkedModels = new HashMap<String, ArrayList<TreeParameterModel>>();
for (String name : expectedTreeModelNames) {
ArrayList<TreeParameterModel> tpmList = new ArrayList<TreeParameterModel>();
for (TreeParameterModel tpm : traitModels) {
if (tpm.getTreeModel().getId().equals(name)) {
tpmList.add(tpm);
if (DEBUG) {
System.out.println("TreeModel: " + name + " has been assigned TreeParameterModel: " + tpm.toString());
}
}
}
linkedModels.put(name, tpmList);
}
line = in.readLine();
fields = line.split("\t");
// Read in all (possibly more than one) trees
while (fields[0].equals("tree")) {
if (DEBUG) {
System.out.println("\ntree: " + fields[1]);
}
for (Model model : Model.CONNECTED_MODEL_SET) {
if (model instanceof TreeModel && fields[1].equals(model.getModelName())) {
line = in.readLine();
line = in.readLine();
fields = line.split("\t");
//read number of nodes
int nodeCount = Integer.parseInt(fields[0]);
double[] nodeHeights = new double[nodeCount];
String[] taxaNames = new String[(nodeCount+1)/2];
for (int i = 0; i < nodeCount; i++) {
line = in.readLine();
fields = line.split("\t");
nodeHeights[i] = Double.parseDouble(fields[1]);
if (i < taxaNames.length) {
taxaNames[i] = fields[2];
}
}
//on to reading edge information
line = in.readLine();
line = in.readLine();
line = in.readLine();
fields = line.split("\t");
int edgeCount = Integer.parseInt(fields[0]);
if (DEBUG) {
System.out.println("edge count = " + edgeCount);
}
//create data matrix of doubles to store information from list of TreeParameterModels
//size of matrix depends on the number of TreeParameterModels assigned to a TreeModel
double[][] traitValues = new double[linkedModels.get(model.getId()).size()][edgeCount];
//create array to store whether a node is left or right child of its parent
//can be important for certain tree transition kernels
int[] childOrder = new int[edgeCount];
for (int i = 0; i < childOrder.length; i++) {
childOrder[i] = -1;
}
int[] parents = new int[edgeCount];
for (int i = 0; i < edgeCount; i++){
parents[i] = -1;
}
for (int i = 0; i < edgeCount-1; i++) {
line = in.readLine();
if (line != null) {
if (DEBUG) {
System.out.println("DEBUG: " + line);
}
fields = line.split("\t");
parents[Integer.parseInt(fields[0])] = Integer.parseInt(fields[1]);
// childOrder[i] = Integer.parseInt(fields[2]);
childOrder[Integer.parseInt(fields[0])] = Integer.parseInt(fields[2]);
for (int j = 0; j < linkedModels.get(model.getId()).size(); j++) {
// traitValues[j][i] = Double.parseDouble(fields[3+j]);
traitValues[j][Integer.parseInt(fields[0])] = Double.parseDouble(fields[3+j]);
}
}
}
//perform magic with the acquired information
if (DEBUG) {
System.out.println("adopting tree structure");
}
//adopt the loaded tree structure;
((TreeModel) model).beginTreeEdit();
((TreeModel) model).adoptTreeStructure(parents, nodeHeights, childOrder, taxaNames);
if (traitModels.size() > 0) {
System.out.println("adopting " + traitModels.size() + " trait models to treeModel " + ((TreeModel)model).getId());
((TreeModel) model).adoptTraitData(parents, traitModels, traitValues, taxaNames);
}
((TreeModel) model).endTreeEdit();
expectedTreeModelNames.remove(model.getModelName());
}
}
line = in.readLine();
if (line != null) {
fields = line.split("\t");
}
}
if (expectedTreeModelNames.size() > 0) {
StringBuilder sb = new StringBuilder();
for (String notFoundName : expectedTreeModelNames) {
sb.append("Expecting, but unable to match state parameter:" + notFoundName + "\n");
}
throw new RuntimeException("\n" + sb.toString());
}
if (DEBUG) {
System.out.println("\nDouble checking:");
for (Parameter parameter : Parameter.CONNECTED_PARAMETER_SET) {
if (parameter.getParameterName().equals("branchRates.categories.rootNodeNumber")) {
System.out.println(parameter.getParameterName() + ": " + parameter.getParameterValue(0));
}
}
System.out.println("\nPrinting trees:");
for (TreeModel tm : treeModelList) {
System.out.println(tm.getId() + ": ");
System.out.println(tm.getNewick());
}
}
if (System.getProperty(BeastCheckpointer.CHECKPOINT_SEED) != null) {
MathUtils.setSeed(Long.parseLong(System.getProperty(BeastCheckpointer.CHECKPOINT_SEED)));
} else if (rngState != null) {
MathUtils.setRandomState(rngState);
}
in.close();
fileIn.close();
//This shouldn't be necessary and if it is then it might be hiding a bug...
/*for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) {
likelihood.makeDirty();
}*/
} catch (IOException ioe) {
throw new RuntimeException("Unable to read file: " + ioe.getMessage());
}
return state;
}
}
|
package edu.brandeis.cs.steele.wn;
import java.util.logging.*;
import java.util.EnumSet;
import java.util.Set;
/**
* An <code>IndexWord</code> represents a line of the <var>pos</var><code>.index</code> file.
* An <code>IndexWord</code> is created retrieved or retrieved via {@link DictionaryDatabase#lookupIndexWord},
* and has a <i>lemma</i>, a <i>pos</i>, and a set of <i>senses</i>, which are of type {@link Synset}.
*
* @author Oliver Steele, steele@cs.brandeis.edu
* @version 1.0
*/
public class IndexWord {
private static final Logger log = Logger.getLogger(IndexWord.class.getName());
/** offset in <var>pos</var><code>.index<code> file */
protected final int offset;
/** No case "lemma". Each {@link Word} has at least 1 true case lemma
* (could vary by POS).
*/
protected final String lemma;
// number of senses with counts in sense tagged corpora
protected final int taggedSenseCount;
// senses are initially stored as offsets, and paged in on demand.
protected int[] synsetOffsets;
/** This is null until {@link #getSynsets()} has been called. */
protected Synset[] synsets;
protected final EnumSet<PointerType> ptrTypes;
protected final byte posOrdinal;
// Initialization
IndexWord(final CharSequence line, final int offset) {
try {
log.log(Level.FINEST, "parsing line: {0}", line);
final CharSequenceTokenizer tokenizer = new CharSequenceTokenizer(line, " ");
this.lemma = tokenizer.nextToken().toString().replace('_', ' ');
this.posOrdinal = (byte) POS.lookup(tokenizer.nextToken()).ordinal();
tokenizer.skipNextToken(); // poly_cnt
final int p_cnt = tokenizer.nextInt();
this.ptrTypes = EnumSet.noneOf(PointerType.class);
for (int i = 0; i < p_cnt; ++i) {
try {
ptrTypes.add(PointerType.parseKey(tokenizer.nextToken()));
} catch (final java.util.NoSuchElementException exc) {
log.log(Level.SEVERE, "IndexWord() got PointerType.parseKey() error:", exc);
}
}
this.offset = offset;
//XXX what's the difference between poly_cnt and senseCount ?
final int senseCount = tokenizer.nextInt();
this.taggedSenseCount = tokenizer.nextInt();
this.synsetOffsets = new int[senseCount];
for (int i = 0; i < senseCount; ++i) {
synsetOffsets[i] = tokenizer.nextInt();
}
} catch (final RuntimeException e) {
log.log(Level.SEVERE, "IndexWord parse error on offset: {0} line:\n\"{1}\"",
new Object[]{ offset, line });
log.log(Level.SEVERE, "", e);
throw e;
}
}
// Object methods
@Override public boolean equals(final Object object) {
return (object instanceof IndexWord)
&& ((IndexWord) object).posOrdinal == posOrdinal
&& ((IndexWord) object).offset == offset;
}
@Override public int hashCode() {
// times 10 shifts left by 1 decimal place
return ((int) offset * 10) + getPOS().hashCode();
}
@Override public String toString() {
return new StringBuilder("[IndexWord ").
append(offset).
append("@").
append(getPOS().getLabel()).
append(": \"").
append(getLemma()).
append("\"]").toString();
}
// Accessors
public POS getPOS() {
return POS.fromOrdinal(posOrdinal);
}
/**
* The pointer types available for this indexed word. May not apply to all
* senses of the word.
*/
public Set<PointerType> getPointerTypes() {
return ptrTypes;
}
/** Return the word's lowercased <i>lemma</i>. Its lemma is its orthographic
* representation, for example <code>"dog"</code> or <code>"get up"</code>
* or <code>"u.s."</code>.
*/
public String getLemma() {
return lemma;
}
public int getTaggedSenseCount() {
return taggedSenseCount;
}
public Synset[] getSynsets() {
if (synsets == null) {
final FileBackedDictionary dictionary = FileBackedDictionary.getInstance();
//XXX could synsets be a WeakReference ?
final Synset[] syns = new Synset[synsetOffsets.length];
for (int i = 0; i < synsetOffsets.length; ++i) {
syns[i] = dictionary.getSynsetAt(getPOS(), synsetOffsets[i]);
assert syns[i] != null : "null Synset at index "+i+" of "+this;
}
synsets = syns;
}
return synsets;
}
public Word[] getSenses() {
final Word[] senses = new Word[getSynsets().length];
int senseNumberMinusOne = 0;
for(final Synset synset : getSynsets()) {
final Word word = synset.getWord(this);
senses[senseNumberMinusOne] = word;
assert senses[senseNumberMinusOne] != null :
this+" null Word at senseNumberMinusOne: "+senseNumberMinusOne;
senseNumberMinusOne++;
}
return senses;
}
}
|
package edu.cmu.cs.diamond.opendiamond;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String scopeName = null;
if (args.length >= 1) {
scopeName = args[0];
}
// get scopes
Scope scope = null;
List<Scope> scopes = ScopeSource.getPredefinedScopeList();
for (Scope s : scopes) {
System.out.println(s);
if (s.getName().equals(scopeName)) {
scope = s;
}
}
if (scope == null) {
System.out.println("Cannot find scope \"" + scopeName + "\" from command line");
System.exit(1);
}
// set up the rgb filter
Filter rgb = null;
try {
FilterCode c = new FilterCode(new FileInputStream(
"/opt/diamond/lib/fil_rgb.a"));
rgb = new Filter("RGB", c, "f_eval_img2rgb", "f_init_img2rgb",
"f_fini_img2rgb", 1, new String[0], new String[0], 400);
System.out.println(rgb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// init diamond
Search search = Search.getSharedInstance();
search.setScope(scope);
// make a new searchlet
Searchlet searchlet = new Searchlet();
searchlet.addFilter(rgb);
searchlet.setApplicationDependencies(new String[] { "RGB" });
search.setSearchlet(searchlet);
Result r;
DoubleComposer sum = new DoubleComposer() {
public double compose(String key, double a, double b) {
// ignore key
return a + b;
}
};
for (int ii = 0; ii < 1; ii++) {
// begin search
search.start();
Map<String, Double> map = new HashMap<String, Double>();
map.put("Hi", 42.0);
map.put("Oops", 23842938.0);
search.setSessionVariables(map);
// read some results
int count = 0;
try {
while ((r = search.getNextResult()) != null && count < 10) {
processResult(r);
System.out.println(search.getSessionVariables(sum));
count++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Test.class) {
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
search.stop();
}
}
private static void processResult(Result r) {
System.out.println(r);
byte data[] = r.getData();
try {
// try reading the data
ByteArrayInputStream in = new ByteArrayInputStream(data);
BufferedImage img = ImageIO.read(in);
// else, try the other one
data = r.getValue("_rgb_image.rgbimage");
byte tmp[] = r.getValue("_cols.int");
int w = Util.extractInt(tmp);
tmp = r.getValue("_rows.int");
int h = Util.extractInt(tmp);
System.out.println(w + "x" + h);
img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int i = (y * w + x) * 4;
// System.out.println(x);
// System.out.println(y);
int val = (data[i] & 0xFF) << 16
| (data[i + 1] & 0xFF) << 8 | (data[i + 2] & 0xFF);
img.setRGB(x, y, val);
}
}
// JFrame j = new JFrame();
// j.setLocationByPlatform(true);
// j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// j.getContentPane().add(new JButton(new ImageIcon(img)));
// j.pack();
// j.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package edu.iu.grid.oim.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.divrep.DivRep;
import com.divrep.DivRepEvent;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.view.BootMenuView;
import edu.iu.grid.oim.view.BootPage;
import edu.iu.grid.oim.view.ContactAssociationView;
import edu.iu.grid.oim.view.GenericView;
import edu.iu.grid.oim.view.HtmlView;
import edu.iu.grid.oim.view.IView;
import edu.iu.grid.oim.view.LinkView;
import edu.iu.grid.oim.view.SideContentView;
public class HomeServlet extends ServletBase {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(HomeServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
UserContext context = new UserContext(request);
//Authorization auth = context.getAuthorization();
BootMenuView menuview = new BootMenuView(context, "home");
BootPage page = new BootPage(context, menuview, new Content(context), createSideView(context));
GenericView header = new GenericView();
header.add(new HtmlView("<h1>OSG Information Management System</h1>"));
header.add(new HtmlView("<p class=\"lead\">Defines the topology used by various OSG services based on the <a target=\"_blank\" href=\"http://osg-docdb.opensciencegrid.org/cgi-bin/ShowDocument?docid=18\">OSG Blueprint Document</a></p>"));
page.setPageHeader(header);
page.render(response.getWriter());
}
class Content implements IView {
UserContext context;
public Content(UserContext context) {
this.context = context;
}
@Override
public void render(PrintWriter out) {
out.write("<div id=\"content\">");
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
try {
ContactRecord user = auth.getContact();
Confirmation conf = new Confirmation(user.id, context);
conf.render(out);
} catch (SQLException e) {
log.error(e);
}
//show entities that this user is associated
try {
ContactAssociationView caview = new ContactAssociationView(context, auth.getContact().id);
caview.showNewButtons(true);
caview.render(out);
} catch (SQLException e) {
log.error(e);
}
} else {
//guest view
out.write("<div class=\"row-fluid\">");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='topology';\">");
out.write("<h2>Topology</h2>");
out.write("<p>Defines resource hierarchy</p>");
out.write("<img src=\"images/topology.png\">");
out.write("</div>");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='vo';\">");
out.write("<h2>Virtual Organization</h2>");
out.write("<p>Defines access for group of users</p>");
out.write("<img src=\"images/voicon.png\">");
out.write("</div>");
out.write("<div class=\"span4 hotlink\" onclick=\"document.location='sc';\">");
out.write("<h2>Support Centers</h2>");
out.write("<p>Defines who supports virtual organization</p>");
out.write("<img src=\"images/scicon.png\">");
out.write("</div>");
out.write("</div>");
}
out.write("</div>");
}
}
private SideContentView createSideView(UserContext context)
{
SideContentView contentview = new SideContentView();
Authorization auth = context.getAuthorization();
if(auth.isUnregistered()) {
contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>Your certificate is not yet registered with OIM.</p><p><a class=\"btn btn-info\" href=\"register\">Register</a></p></div>"));
} else if(auth.isDisabled()) {
contentview.add(new HtmlView("<div class=\"alert alert-danger\"><p>Your contact is disabled. Please contact GOC for more information.</p><a class=\"btn btn-danger\" href=\"https://ticket.grid.iu.edu\">Contact GOC</a></p></div>"));
} else if(!auth.isUser()) {
String text = "<p>OIM requires an X509 certificate issued by an <a target=\"_blank\" href='http://software.grid.iu.edu/cadist/'>OSG-approved Certifying Authority (CA)</a> to authenticate.</p>"+
"<p><a class=\"btn btn-info\" target=\"blank\" href=\"http://pki1.doegrids.org/ca/\">Request New Certificate</a></p>"+
"If you already have a certificate installed on your browser, please login.</p><p><a class=\"btn btn-info\" href=\""+context.getSecureUrl()+"\">Login</a></p>";
contentview.add(new HtmlView("<div class=\"alert alert-info\"><p>"+text+"</p></div>"));
}
contentview.add(new HtmlView("<h2>Documentations</h2>"));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMTermDefinition", "OIM Definitions", true));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMRegistrationInstructions", "Registration", true));
contentview.add(new LinkView("https://twiki.grid.iu.edu/twiki/bin/view/Operations/OIMMaintTool", "Resource Downtime", true));
if(auth.isUser()) {
contentview.addContactLegend();
}
return contentview;
}
@SuppressWarnings("serial")
class Confirmation extends DivRep
{
final ContactRecord crec;
final ContactModel cmodel;
final UserContext context;
public Confirmation(Integer contact_id, UserContext _context) throws SQLException {
super(_context.getPageRoot());
cmodel = new ContactModel(_context);
crec = (ContactRecord) cmodel.get(contact_id);//.clone();
context = _context;
}
protected void onEvent(DivRepEvent e) {
// TODO Auto-generated method stub
}
public void render(PrintWriter out) {
if(crec.isConfirmationExpired()) {
out.write("<div id=\""+getNodeID()+"\">");
out.write("<h2>Content Confirmation</h2>");
out.write("<p class=\"divrep_round divrep_elementerror\">You have not recently confirmed that your information in OIM is current</p>");
out.write("<p>The last time you confirmed your profile information was "+crec.confirmed.toString()+"</p>");
out.write("<p>Please go to the ");
out.write("<a href=\"profileedit\">My Profile</a>");
out.write(" page to check your profile information</p>");
out.write("</div>");
}
}
}
}
|
package edu.wheaton.simulator.entity;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException;
import edu.wheaton.simulator.datastructure.Field;
public class Entity {
/**
* The list of all fields (variables) associated with this agent.
*/
private Map<String, String> fields;
private final EntityID id;
public Entity() {
id = new EntityID();
fields = new HashMap<String, String>();
}
/**
* Note that if a field already exists for this agent with the same name as
* the new candidate, it won't be added and will instead throw an
* exception.
*
* @throws ElementAlreadyContainedException
*/
public void addField(Object name, Object value)
throws ElementAlreadyContainedException {
assertNoSuchField(name);
putField(name,value);
}
/**
* if the entity has a field by that name it updates it's value. Otherwise
* throws NoSuchElementException()
*
* @return returns the old field
*/
public Field updateField(Object name, Object value) {
assertHasField(name);
String oldvalue = putField(name,value);
return new Field(name, oldvalue);
}
private String putField(Object name, Object value){
return fields.put(name.toString(),value.toString());
}
/**
* Removes a field from this Entity and returns it.
*/
public Field removeField(Object name) {
assertHasField(name);
String value = fields.remove(name.toString());
return new Field(name, value);
}
public Field getField(Object name) {
assertHasField(name);
return new Field(name.toString(), getFieldValue(name));
}
public String getFieldValue(Object name) {
assertHasField(name);
return fields.get(name.toString());
}
private void assertHasField(Object name){
if(hasField(name) == false)
throw new NoSuchElementException();
}
private void assertNoSuchField(Object name) throws ElementAlreadyContainedException{
if(hasField(name) == true)
throw new ElementAlreadyContainedException();
}
/**
* Tells if this prototype has a Field corresponding to the given name
*
* @param name
* @return
*/
public boolean hasField(Object name) {
return (fields.containsKey(name.toString()));
}
public Map<String, String> getFieldMap() {
return fields;
}
public EntityID getEntityID() {
return id;
}
}
|
package ex17.RyanNewsomKyleFrisbie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* This is the instance of the Knapsack problem
* To Solve Knapsack Problem with Branch and Bound you...
* 1)
*/
public class Knapsack {
protected ArrayList<Node> mPossibleNodesForExploration = new ArrayList<>();
private ArrayList<Item> mItems = new ArrayList<>();
private int mMaximumWeightForSack;
/**
* Empty default constructor, not for use
*/
private Knapsack() {
}
/**
* Constructor
*
* @param maxWeightForSack - the maximum weight the sack can hold before it rips
* @param availableItems - the Item's available to be put in the sack
*/
public Knapsack(int maxWeightForSack, ArrayList<Item> availableItems) {
Node rootNode = new Node();
mItems = availableItems;
mMaximumWeightForSack = maxWeightForSack;
rootNode.setMaximumPossibleProfit(calculateHighestPossibleProfit(rootNode));
mPossibleNodesForExploration.add(rootNode);
}
/**
* Determines the optimal items to use for the Knapsack Problem
*
* @return - the best option for the particular instance
*/
public Node determineOptimalStrategyForKnapsackProblem() {
Node bestNode = null; //The node with the highest possible profit
Logger.beginExploration();
while (mPossibleNodesForExploration.size() > 0) {
bestNode = seeWhoToExploreNext();
createChildren(bestNode);
Logger.exploring(bestNode);
if (mPossibleNodesForExploration.size() == 0) {
break;
}
pruneNodes();
}
if (bestNode == null) {
return null; //"Error, no best node found";
} else {
return bestNode;
}
}
protected double calculateHighestPossibleProfit(Node node) {
//Check the nodes restrictions in terms of who it can/can't use
//to use
//return that value
ArrayList<Item> itemsWeCanUse = new ArrayList<>();
int accumulatedHypotheticalWeight = 0;
double maximumPossibleProfit = 0;
itemsWeCanUse.addAll(mItems);
itemsWeCanUse.removeAll(node.getItemsNotAvailableForUse());
//Look at the list of items and determine the highest profit using the items we are allowed
for (int i = 0; i < itemsWeCanUse.size(); i++) {
Item item = itemsWeCanUse.get(i);
if ((accumulatedHypotheticalWeight + item.getWeight()) > mMaximumWeightForSack) {
//add fraction of that item
int weightNumerator = mMaximumWeightForSack - accumulatedHypotheticalWeight;
double weightRatio = (double) weightNumerator / (double) item.getWeight();
maximumPossibleProfit += (item.getPrice() * weightRatio);
break;
} else {
// include the full value for the item
maximumPossibleProfit += item.getPrice();
accumulatedHypotheticalWeight += item.getWeight();
}
}
return maximumPossibleProfit;
}
protected Node seeWhoToExploreNext() {
Collections.sort(mPossibleNodesForExploration, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return (o1.getMaximumPossibleProfit() >= o2.getMaximumPossibleProfit()) ? -1 : 1;
}
});
return mPossibleNodesForExploration.remove(0);
}
/**
* Getting the next item available base off the Node's item's it's used, and is barred from using
*
* @param node - Node to look at
* @return - the next item to use for the node
*/
protected Item getNextItemToUse(Node node) {
ArrayList<Item> possibleItems = new ArrayList<>();
possibleItems.addAll(mItems);
possibleItems.removeAll(node.getItemsUsed());
possibleItems.removeAll(node.getItemsNotAvailableForUse());
if (possibleItems.size() == 0) {
return null;
}
return possibleItems.get(0);
}
/**
* Create the right child of a parent node
*
* @param parentNode - node right child is being added to
*/
protected Node createRightNode(Node parentNode) {
Item nextToUse = getNextItemToUse(parentNode);
Node rightChild;
// if we are out of items to use, don't create another child
if (nextToUse == null) {
return null;
}
rightChild = new Node(parentNode.getItemsUsed(), parentNode.getItemsNotAvailableForUse(),
parentNode.getMaximumPossibleProfit(), parentNode.getActualProfit(), parentNode.getActualWeight());
rightChild.addItemToUse(nextToUse);
return rightChild;
}
/**
* Create the left child of a parent node
*
* @param parentNode - node left child is being added to
*/
protected Node createLeftNode(Node parentNode) {
ArrayList<Item> decisionItems = new ArrayList<>();
// discover what is the next item not to use
decisionItems.addAll(mItems);
decisionItems.removeAll(parentNode.getItemsUsed());
decisionItems.removeAll(parentNode.getItemsNotAvailableForUse());
// add properties to leftChild
Node leftChild = new Node(parentNode.getItemsUsed(), parentNode.getItemsNotAvailableForUse(),
parentNode.getActualProfit(), parentNode.getActualWeight());
leftChild.addItemNotAvailableForUse(decisionItems.get(0));
leftChild.setMaximumPossibleProfit(calculateHighestPossibleProfit(leftChild));
return leftChild;
}
/**
* Creates children for a node
*
* @param node - the node to have children added to
* @return - true if children were created, false if there's no more children to be created
*/
protected void createChildren(Node node) {
Node rightChild = createRightNode(node);
if(rightChild == null) {
return;
}
node.setRightChild(rightChild);
node.setLeftChild(createLeftNode(node));
// only add the right child if another item doesn't make it too heavy
if (rightChild.getActualWeight() <= mMaximumWeightForSack) {
mPossibleNodesForExploration.add(node.getRightChild());
}
mPossibleNodesForExploration.add(node.getLeftChild());
}
protected void pruneNodes() {
Node highestActualProfit = mPossibleNodesForExploration.get(0);
for (int i = 1; i < mPossibleNodesForExploration.size(); i++) {
if (highestActualProfit.getMaximumPossibleProfit() <
mPossibleNodesForExploration.get(i).getMaximumPossibleProfit()) {
highestActualProfit = mPossibleNodesForExploration.get(i);
}
}
ArrayList<Node> nodesNotPruned = (ArrayList<Node>) mPossibleNodesForExploration.clone();
for (int i = 0; i < mPossibleNodesForExploration.size(); i++) {
if (highestActualProfit.getActualProfit() >
mPossibleNodesForExploration.get(i).getMaximumPossibleProfit()) {
Node nodeToPrune = mPossibleNodesForExploration.get(i);
Logger.prunedNode(nodeToPrune);
nodesNotPruned.remove(nodeToPrune);
}
}
mPossibleNodesForExploration = nodesNotPruned;
}
}
|
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//This library is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//You should have received a copy of the GNU Lesser General Public
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.tools.postag;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import opennlp.maxent.GISModel;
import opennlp.maxent.MaxentModel;
import opennlp.maxent.io.BinaryGISModelReader;
import opennlp.tools.dictionary.Dictionary;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.ModelUtil;
/**
* The {@link POSModel} is the model used
* by a learnable {@link POSTagger}.
*
* @see POSTaggerME
*/
public final class POSModel {
private static final String MAXENT_MODEL_ENTRY_NAME = "pos.bin";
private static final String TAG_DICTIONARY_ENTRY_NAME = "tag-dictionary.xml";
private static final String NGRAM_DICTIONARY_ENTRY_NAME = "ngram-dictionary.xml";
private final GISModel maxentPosModel;
private final POSDictionary tagDictionary;
private final Dictionary ngramDict;
public POSModel(GISModel maxentPosModel, POSDictionary tagDictionary,
Dictionary ngramDict) {
if (maxentPosModel == null)
throw new IllegalArgumentException("The maxentPosModel param must not be null!");
// the model is always valid, because there
// is nothing that can be assumed about the used
// tags
this.maxentPosModel = maxentPosModel;
this.tagDictionary = tagDictionary;
this.ngramDict = ngramDict;
}
public MaxentModel getMaxentPosModel() {
return maxentPosModel;
}
/**
* Retrieves the tag dictionary.
*
* @return tag dictionary or null if not used
*/
public POSDictionary getTagDictionary() {
return tagDictionary;
}
/**
* Retrieves the ngram dictionary.
*
* @return ngram dictionary or null if not used
*/
public Dictionary getNgramDictionary() {
return ngramDict;
}
/**
* .
*
* After the serialization is finished the provided
* {@link OutputStream} is closed.
*
* @param out
*
* @throws IOException
*/
public void serialize(OutputStream out) throws IOException {
ZipOutputStream zip = new ZipOutputStream(out);
zip.putNextEntry(new ZipEntry(MAXENT_MODEL_ENTRY_NAME));
ModelUtil.writeModel(maxentPosModel, zip);
zip.closeEntry();
if (getTagDictionary() != null) {
zip.putNextEntry(new ZipEntry(TAG_DICTIONARY_ENTRY_NAME));
getTagDictionary().serialize(zip);
zip.closeEntry();
}
if (getNgramDictionary() != null) {
zip.putNextEntry(new ZipEntry(NGRAM_DICTIONARY_ENTRY_NAME));
getNgramDictionary().serialize(out);
zip.closeEntry();
}
zip.close();
}
public static POSModel create(InputStream in) throws IOException, InvalidFormatException {
ZipInputStream zip = new ZipInputStream(in);
GISModel maxentPosModel = null;
POSDictionary posDictionary = null;
Dictionary ngramDictionary = null;
ZipEntry entry;
while((entry = zip.getNextEntry()) != null ) {
if (MAXENT_MODEL_ENTRY_NAME.equals(entry.getName())) {
maxentPosModel = new BinaryGISModelReader(
new DataInputStream(zip)).getModel();
zip.closeEntry();
}
else if (TAG_DICTIONARY_ENTRY_NAME.equals(entry.getName())) {
posDictionary = POSDictionary.create(zip);
zip.closeEntry();
}
else if (NGRAM_DICTIONARY_ENTRY_NAME.equals(entry.getName())) {
// Note: ngram dictionary is not case sensitive
ngramDictionary = new Dictionary(zip);
}
else {
throw new InvalidFormatException("Model contains unkown resource!");
}
}
if (maxentPosModel == null)
throw new InvalidFormatException("Could not find maxent pos model!");
return new POSModel(maxentPosModel, posDictionary, ngramDictionary);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.